示例#1
0
 protected function _loadFiles()
 {
     if (!$this->_isLoaded) {
         $readPath = Mage::getBaseDir("var") . DS . "backups";
         $ioProxy = new Varien_Io_File();
         try {
             $ioProxy->open(array('path' => $readPath));
         } catch (Exception $e) {
             $ioProxy->mkdir($readPath, 0755);
             $ioProxy->chmod($readPath, 0755);
             $ioProxy->open(array('path' => $readPath));
         }
         if (!is_file($readPath . DS . ".htaccess")) {
             // Deny from reading in browser
             $ioProxy->write(".htaccess", "deny from all", 0644);
         }
         $list = $ioProxy->ls(Varien_Io_File::GREP_FILES);
         $fileExtension = constant($this->_itemObjectClass . "::BACKUP_EXTENSION");
         foreach ($list as $entry) {
             if ($entry['filetype'] == $fileExtension) {
                 $item = new $this->_itemObjectClass();
                 $item->load($entry['text'], $readPath);
                 if ($this->_checkCondition($item)) {
                     $this->addItem($item);
                 }
             }
         }
         $this->_totalRecords = count($this->_items);
         if ($this->_totalRecords > 1) {
             usort($this->_items, array(&$this, 'compareByTypeOrDate'));
         }
         $this->_isLoaded = true;
     }
     return $this;
 }
 /**
  * Write Sample Data to File. Store in folder: "skin/frontend/default/ves theme name/import/"
  */
 public function writeSampleDataFile($importDir, $file_name, $content = "")
 {
     $file = new Varien_Io_File();
     //Create import_ready folder
     $error = false;
     if (!file_exists($importDir)) {
         $importReadyDirResult = $file->mkdir($importDir);
         $error = false;
         if (!$importReadyDirResult) {
             //Handle error
             $error = true;
             Mage::getSingleton('adminhtml/session')->addError(Mage::helper('ves_tempcp')->__('Can not create folder "%s".', $importDir));
         }
     } else {
         $file->open(array('path' => $importDir));
     }
     if (!$file->write($importDir . $file_name, $content)) {
         //Handle error
         $error = true;
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('ves_tempcp')->__('Can not save import sample file "%s".', $file_name));
     }
     if (!$error) {
         Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('cms')->__('Successfully, Stored sample data file "%s".', $file_name));
     }
     return !$error;
 }
示例#3
0
 /**
  * Create/update file in file system
  *
  * @return bool|int
  */
 protected function _saveFile()
 {
     $filePath = $this->getFilePath(true);
     $this->_ioFile->checkAndCreateFolder(dirname($filePath));
     $result = $this->_ioFile->write($filePath, $this->getContent());
     $this->_design->cleanMergedJsCss();
     return $result;
 }
 /**
  * Write xml nfe in folder
  *
  * @return true
  */
 public function write()
 {
     // load template array, fill data and convert to XML
     $this->_init()->_addCustomer()->_addItens()->_addOtherInfo()->_toXML();
     $io = new Varien_Io_File();
     $io->setAllowCreateFolders(true);
     $io->createDestinationDir($this->_path);
     $return = $io->write($this->_path . $this->_getFileName(), $this->_stringFinalXML);
     return true;
 }
示例#5
0
 protected function finaliseStoreData()
 {
     // Write DOM to file
     $filename = $this->info("clean_store_name") . '-products.xml';
     $io = new Varien_Io_File();
     $io->setAllowCreateFolders(true);
     $io->open(array('path' => $this->getPath()));
     $io->write($filename, $this->_dom->saveXML());
     $io->close();
 }
示例#6
0
文件: Pdf.php 项目: AleksNesh/pandora
 /**
  * @param $file
  * @param $filename
  * @throws Exception
  */
 public function saveFile($file, $filename)
 {
     $varienFile = new Varien_Io_File();
     $varienFile->open();
     $path = $this->getFilePath($filename);
     $varienFile->checkAndCreateFolder($path);
     if ($varienFile->write($path . DS . $filename, $file) !== false) {
         return $path . DS . $filename;
     } else {
         throw new Exception('Could not save PDF file');
     }
 }
 public function __construct()
 {
     parent::__construct();
     $this->_baseDir = Mage::getBaseDir('export');
     // check for valid base dir
     $ioProxy = new Varien_Io_File();
     $ioProxy->mkdir($this->_baseDir);
     if (!is_file($this->_baseDir . DS . '.htaccess')) {
         $ioProxy->open(array('path' => $this->_baseDir));
         $ioProxy->write('.htaccess', 'deny from all', 0644);
     }
     $this->setOrder('file_created', self::SORT_ORDER_DESC)->addTargetDir($this->_baseDir)->setCollectRecursively(false);
 }
示例#8
0
文件: File.php 项目: buttasg/cowgirlk
    protected function _rewriteGrid($blcgClass, $originalClass, $gridType)
    {
        $classParts = explode('_', str_replace($this->_getBlcgClassPrefix(), '', $blcgClass));
        $fileName = array_pop($classParts) . '.php';
        $rewriteDir = dirname(__FILE__) . '/../../../Block/Rewrite/' . implode('/', $classParts);
        $ioFile = new Varien_Io_File();
        $ioFile->setAllowCreateFolders(true);
        $ioFile->checkAndCreateFolder($rewriteDir);
        $ioFile->cd($rewriteDir);
        // Use open() to initialize Varien_Io_File::$_iwd
        // Prevents a warning when chdir() is used without error control in Varien_Io_File::read()
        if ($ioFile->fileExists($fileName, true) && $ioFile->open()) {
            if ($content = $ioFile->read($fileName)) {
                $lines = preg_split('#\\R#', $content, 3);
                $isUpToDate = false;
                if (isset($lines[0]) && isset($lines[1]) && $lines[0] == '<?php' && preg_match('#^// BLCG_REWRITE_CODE_VERSION\\=([0-9]+)$#', $lines[1], $matches)) {
                    if ($matches[1] === strval(self::REWRITE_CODE_VERSION)) {
                        $isUpToDate = true;
                    }
                }
            }
            $ioFile->close();
            if ($isUpToDate) {
                return $this;
            }
        }
        $content = '<?php
// BLCG_REWRITE_CODE_VERSION=' . self::REWRITE_CODE_VERSION . '
// This file was generated automatically. Do not alter its content.

/**
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 * @category   BL
 * @package    BL_CustomGrid
 * @copyright  Copyright (c) ' . date('Y') . ' Benoît Leulliette <*****@*****.**>
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

';
        $content .= $this->_getRewriteCode($blcgClass, $originalClass, $gridType);
        if (!$ioFile->write($fileName, $content)) {
            Mage::throwException();
        }
        return $this;
    }
示例#9
0
 /**
  * Set collection specific parameters and make sure backups folder will exist
  */
 public function __construct()
 {
     parent::__construct();
     $this->_baseDir = Mage::getBaseDir('var') . DS . Ebizmarts_Mailchimp_Model_BulkSynchro::FLDR;
     // check for valid base dir
     $ioProxy = new Varien_Io_File();
     $ioProxy->mkdir($this->_baseDir);
     if (!is_file($this->_baseDir . DS . '.htaccess')) {
         $ioProxy->open(array('path' => $this->_baseDir));
         $ioProxy->write('.htaccess', 'deny from all', 0644);
     }
     // set collection specific params
     $this->setOrder('time', self::SORT_ORDER_DESC)->addTargetDir($this->_baseDir)->setFilesFilter('/^[a-z0-9\\-\\_]+\\.' . preg_quote(Ebizmarts_Mailchimp_Model_BulkSynchro::FILE_EXTENSION . "." . Ebizmarts_Mailchimp_Model_BulkSynchro::BULK_EXTENSION, '/') . '$/')->setCollectRecursively(false);
 }
示例#10
0
文件: V1.php 项目: nemphys/magento2
 /**
  * Product image add
  *
  * @throws Mage_Api2_Exception
  * @param array $data
  * @return string
  */
 protected function _create(array $data)
 {
     /* @var $validator Mage_Catalog_Model_Api2_Product_Image_Validator_Image */
     $validator = Mage::getModel('Mage_Catalog_Model_Api2_Product_Image_Validator_Image');
     if (!$validator->isValidData($data)) {
         foreach ($validator->getErrors() as $error) {
             $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
         }
         $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
     }
     $imageFileContent = @base64_decode($data['file_content'], true);
     if (!$imageFileContent) {
         $this->_critical('The image content must be valid base64 encoded data', Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
     }
     unset($data['file_content']);
     $apiTempDir = Mage::getBaseDir('var') . DS . 'api' . DS . Mage::getSingleton('Mage_Api_Model_Session')->getSessionId();
     $imageFileName = $this->_getFileName($data);
     try {
         $ioAdapter = new Varien_Io_File();
         $ioAdapter->checkAndCreateFolder($apiTempDir);
         $ioAdapter->open(array('path' => $apiTempDir));
         $ioAdapter->write($imageFileName, $imageFileContent, 0666);
         unset($imageFileContent);
         // try to create Image object to check if image data is valid
         try {
             $adapter = Mage::helper('Mage_Core_Helper_Data')->getImageAdapterType();
             new Varien_Image($apiTempDir . DS . $imageFileName, $adapter);
         } catch (Exception $e) {
             $ioAdapter->rmdir($apiTempDir, true);
             $this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
         }
         $product = $this->_getProduct();
         $imageFileUri = $this->_getMediaGallery()->addImage($product, $apiTempDir . DS . $imageFileName, null, false, false);
         $ioAdapter->rmdir($apiTempDir, true);
         // updateImage() must be called to add image data that is missing after addImage() call
         $this->_getMediaGallery()->updateImage($product, $imageFileUri, $data);
         if (isset($data['types'])) {
             $this->_getMediaGallery()->setMediaAttribute($product, $data['types'], $imageFileUri);
         }
         $product->save();
         return $this->_getImageLocation($this->_getCreatedImageId($imageFileUri));
     } catch (Mage_Core_Exception $e) {
         $this->_critical($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
     } catch (Exception $e) {
         $this->_critical(self::RESOURCE_UNKNOWN_ERROR);
     }
 }
示例#11
0
 /**
  * Save result to destination file from temporary
  *
  * @return Mage_Dataflow_Model_Convert_Adapter_Io
  */
 public function save()
 {
     if (!$this->getResource(true)) {
         return $this;
     }
     $batchModel = Mage::getSingleton('dataflow/batch');
     $dataFile = $batchModel->getIoAdapter()->getFile(true);
     $filename = $this->getVar('filename');
     /*         * Start Code For Vendor* */
     $isVendor = Mage::helper('marketplace')->isVendor();
     //current user is vendor or not
     if ($isVendor) {
         /*             * Fetch Current User Name* */
         $user = Mage::getSingleton('admin/session');
         $userName = $user->getUser()->getUsername();
         $filename = 'export_product_' . $userName . '.csv';
     }
     /*         * End Code For Vendor* */
     $result = $this->getResource()->write($filename, $dataFile, 0777);
     if (false === $result) {
         $message = Mage::helper('dataflow')->__('Could not save file: %s.', $filename);
         Mage::throwException($message);
     } else {
         /*             * Start Code For Vendor* */
         if ($isVendor) {
             $localpath = 'vendor/';
             //create path if not exist
             if (!file_exists($localpath)) {
                 mkdir($localpath, 0777, true);
             }
             $fileWithPath = $localpath . '/' . $filename;
             $localResource = new Varien_Io_File();
             $localResource->write($fileWithPath, $dataFile, 0777);
         }
         $message = Mage::helper('dataflow')->__('Saved successfully: "%s" [%d byte(s)].', $filename, $batchModel->getIoAdapter()->getFileSize());
         if ($batchModel->getIoAdapter()->getFileSize() == 0 && $isVendor) {
             $message = Mage::helper('dataflow')->__("You don't have any product to download");
             Mage::throwException($message);
         }
         if ($this->getVar('link')) {
             $message .= Mage::helper('dataflow')->__('<a href="%s" target="_blank">Link</a>', $this->getVar('link'));
         }
         $this->addException($message);
     }
     return $this;
 }
示例#12
0
 function writeRewriteFile()
 {
     $adapter = Mage::getModel('freelunchlabs_cloudfront/refreshadapters_apache');
     $base_dir = Mage::getBaseDir() . DS;
     $file = new Varien_Io_File();
     try {
         if ($file->cd($base_dir) && $file->checkAndCreateFolder($this->cdn_rewrite_directory, 0755)) {
             if ($file->cd($base_dir . $this->cdn_rewrite_directory)) {
                 if (!$file->write($adapter->filename, $adapter->buildFileContents(), 0644)) {
                     throw new Exception("Could not write .htaccess to: " . $file->pwd());
                 }
             }
         }
     } catch (Exception $e) {
         Mage::getSingleton('core/session')->addWarning('Configuration saved but there was an error creating the .htaccess file: ' . $e->getMessage());
     }
 }
示例#13
0
 /**
  * Set collection specific parameters and make sure backups folder will exist
  */
 public function __construct()
 {
     parent::__construct();
     $this->_baseDir = Mage::getBaseDir('var') . DS . 'backups';
     // check for valid base dir
     $ioProxy = new Varien_Io_File();
     $ioProxy->mkdir($this->_baseDir);
     if (!is_file($this->_baseDir . DS . '.htaccess')) {
         $ioProxy->open(array('path' => $this->_baseDir));
         $ioProxy->write('.htaccess', 'deny from all', 0644);
     }
     // set collection specific params
     $extensions = Mage::helper('backup')->getExtensions();
     foreach ($extensions as $key => $value) {
         $extensions[] = '(' . preg_quote($value, '/') . ')';
     }
     $extensions = implode('|', $extensions);
     $this->setOrder('time', self::SORT_ORDER_DESC)->addTargetDir($this->_baseDir)->setFilesFilter('/^[a-z0-9\\-\\_]+\\.' . $extensions . '$/')->setCollectRecursively(false);
 }
示例#14
0
 protected function finaliseStoreData()
 {
     // Write CSV data to temp file
     $memoryLimit = 16 * 1024 * 1024;
     $fp = fopen("php://temp/maxmemory:{$memoryLimit}", 'r+');
     foreach ($this->_rows as $row) {
         fputcsv($fp, $row, $this->_separator);
     }
     rewind($fp);
     // Write temp file data to file
     $cleanStoreName = str_replace('+', '-', strtolower(urlencode($this->_store->getName())));
     $filename = $cleanStoreName . '-products.csv';
     $io = new Varien_Io_File();
     $io->setAllowCreateFolders(true);
     $io->open(array('path' => $this->getPath()));
     $io->write($filename, $fp);
     $io->close();
     fclose($fp);
 }
示例#15
0
 protected function createConfigFile()
 {
     $base_url = explode("/", Mage::getBaseUrl('js'));
     $base_url = explode($base_url[count($base_url) - 2], Mage::getBaseUrl('js'));
     $this->_base_url = $base_url[0];
     $base_URLs = preg_replace('/http:\\/\\//is', 'https://', $base_url[0]);
     /** Create file config for javascript */
     $js = "var mw_baseUrl = '{BASE_URL}';\n";
     $js = str_replace("{BASE_URL}", $base_url[0], $js);
     $js .= "var mw_baseUrls = '{$base_URLs}';\n";
     $js .= "var FACEBOOK_ID = '" . Mage::helper('mw_socialgift')->getFBID() . "';\n";
     $file = new Varien_Io_File();
     $file->checkAndCreateFolder($this->baseDir . "/media/mw_socialgift/js/");
     $file->checkAndCreateFolder($this->baseDir . "/media/mw_socialgift/css/");
     foreach ($this->_multi_path_js as $code => $path) {
         if (!file_exists($path) && Mage::app()->getStore()->getCode() == $code) {
             $file->write($path, $js);
             $file->close();
         }
     }
     return $js;
 }
示例#16
0
 public function buildFeeds()
 {
     foreach (Mage::app()->getStores() as $store) {
         if (Mage::getStoreConfig('clerk/settings/active', $store->getId()) && Mage::getStoreConfig('clerk/datasync/magentocron', $store->getId())) {
             $feedData = array();
             $feedData['products'] = $this->__getFeedProductData($store->getId());
             $feedData['categories'] = $this->__getFeedCategoryData($store->getId());
             if (Mage::getStoreConfig('clerk/datasync/include_historical_salesdata', $store->getId() == -1)) {
                 $feedData['sales'] = $this->__getFeedSalesData($store->getId());
             }
             $feedData['created'] = (int) time();
             $filename = Mage::helper('clerk')->getFileName($store);
             $path = Mage::getBaseDir('media') . "/clerk/feeds/";
             $file = new Varien_Io_File();
             $file->checkAndCreateFolder($path);
             $file->open(array('path' => $path));
             $file->write($filename, json_encode($feedData, JSON_HEX_QUOT));
             Mage::getModel('clerk/communicator')->startImportOfFeed($store->getId());
         }
     }
     return true;
 }
示例#17
0
 /**
  */
 protected function _beforeSave()
 {
     if ($this->getValue()) {
         $host = $this->getFieldsetDataValue('host');
         $client = new Zend_Http_Client($host . self::PIWIK_JS);
         $reponde = $client->request();
         if ($reponde->getStatus() == 200) {
             try {
                 $dir = Mage::getBaseDir() . DS . 'js' . DS . 'integernet_piwik';
                 $file = new Varien_Io_File();
                 $file->setAllowCreateFolders(true);
                 $file->open(array('path' => $dir));
                 $file->write(self::PIWIK_JS, $reponde->getBody());
             } catch (Exception $e) {
                 $this->setValue(0);
                 Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             }
         } else {
             $this->setValue(0);
             Mage::getSingleton('adminhtml/session')->addError(Mage::helper('integernet_piwik')->__('Cannot load %s from host "%s"', self::PIWIK_JS, $host));
         }
     }
     return $this;
 }
示例#18
0
 public function buildFeeds($storeId, $type, $page)
 {
     $store = Mage::app()->getStore($storeId);
     if (Mage::getStoreConfig('clerk/settings/active', $store->getId())) {
         $feedData = array();
         if ($type == 'products') {
             $feedData[$type] = $this->__getFeedProductData($store->getId(), $page);
         }
         if ($type == 'categories') {
             $feedData[$type] = $this->__getFeedCategoryData($store->getId(), $page);
         }
         if ($type == 'sales') {
             $feedData[$type] = $this->__getFeedSalesData($store->getId(), $page);
         }
         if ($type != 'done') {
             $filename_tmp = Mage::helper('clerk')->getFileName($store, $tmp = true);
             $path = Mage::getBaseDir('media') . "/clerk/feeds/";
             $file = new Varien_Io_File();
             $file->checkAndCreateFolder($path);
             $file->open(array('path' => $path));
             if (file_exists($path . $filename_tmp)) {
                 $content = $file->read($filename_tmp);
                 $json = json_decode($content, true);
                 if (isset($json[$type])) {
                     if ($type == 'products') {
                         $add = true;
                         foreach ($json[$type] as $item_added) {
                             if ($item_added['id'] == $feedData[$type][0]['id']) {
                                 $add = false;
                                 break;
                             }
                         }
                         if ($add) {
                             $json[$type] = array_merge($json[$type], $feedData[$type]);
                         }
                     } else {
                         $json[$type] = array_merge($json[$type], $feedData[$type]);
                     }
                 } else {
                     $json[$type] = $feedData[$type];
                 }
                 $json['created'] = (int) time();
                 $file->write($filename_tmp, json_encode($json, JSON_HEX_QUOT));
             } else {
                 $feedData['created'] = (int) time();
                 $file->write($filename_tmp, json_encode($feedData, JSON_HEX_QUOT));
             }
         } else {
             $filename_tmp = Mage::helper('clerk')->getFileName($store, $tmp = true);
             $filename = Mage::helper('clerk')->getFileName($store, $tmp = false);
             $path = Mage::getBaseDir('media') . "/clerk/feeds/";
             $file = new Varien_Io_File();
             $file->checkAndCreateFolder($path);
             $file->open(array('path' => $path));
             $file->mv($filename_tmp, $filename);
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('clerk')->__("Done building feed. Data stored in %s", $filename));
             Mage::getModel('clerk/communicator')->startImportOfFeed($storeId);
         }
     }
     return true;
 }
示例#19
0
 /**
  * Create new image for product and return image filename
  *
  * @param int|string $productId
  * @param array $data
  * @param string|int $store
  * @return string
  */
 public function create($productId, $data, $store = null, $identifierType = null)
 {
     $product = $this->_initProduct($productId, $store, $identifierType);
     $gallery = $this->_getGalleryAttribute($product);
     if (!isset($data['file']) || !isset($data['file']['mime']) || !isset($data['file']['content'])) {
         $this->_fault('data_invalid', Mage::helper('catalog')->__('The image is not specified.'));
     }
     if (!isset($this->_mimeTypes[$data['file']['mime']])) {
         $this->_fault('data_invalid', Mage::helper('catalog')->__('Invalid image type.'));
     }
     $fileContent = @base64_decode($data['file']['content'], true);
     if (!$fileContent) {
         $this->_fault('data_invalid', Mage::helper('catalog')->__('The image contents is not valid base64 data.'));
     }
     unset($data['file']['content']);
     $tmpDirectory = Mage::getBaseDir('var') . DS . 'api' . DS . $this->_getSession()->getSessionId();
     if (isset($data['file']['name']) && $data['file']['name']) {
         $fileName = $data['file']['name'];
     } else {
         $fileName = 'image';
     }
     $fileName .= '.' . $this->_mimeTypes[$data['file']['mime']];
     $ioAdapter = new Varien_Io_File();
     try {
         // Create temporary directory for api
         $ioAdapter->checkAndCreateFolder($tmpDirectory);
         $ioAdapter->open(array('path' => $tmpDirectory));
         // Write image file
         $ioAdapter->write($fileName, $fileContent, 0666);
         unset($fileContent);
         // Adding image to gallery
         $file = $gallery->getBackend()->addImage($product, $tmpDirectory . DS . $fileName, null, true);
         // Remove temporary directory
         $ioAdapter->rmdir($tmpDirectory, true);
         $gallery->getBackend()->updateImage($product, $file, $data);
         if (isset($data['types'])) {
             $gallery->getBackend()->setMediaAttribute($product, $data['types'], $file);
         }
         $product->save();
     } catch (Mage_Core_Exception $e) {
         $this->_fault('not_created', $e->getMessage());
     } catch (Exception $e) {
         $this->_fault('not_created', Mage::helper('catalog')->__('Cannot create image.'));
     }
     return $gallery->getBackend()->getRenamedImage($file);
 }
 /**
  * Cache the widget images.
  *
  * @param string $type type
  * @param string $tsId Trusted Rating Id
  *
  * @return void
  */
 private function _cacheImageData($type, $tsId = null)
 {
     $ioObject = new Varien_Io_File();
     $ioObject->open();
     if ($type == 'emailWidget') {
         $emailWidgetName = $this->getRatingLinkData('emailratingimage');
         $readPath = self::EMAIL_WIDGET_LINK . $emailWidgetName;
         $writePath = self::IMAGE_LOCAL_PATH . $emailWidgetName;
         $cacheId = self::EMAIL_CACHEID;
     } else {
         $readPath = self::WIDGET_LINK . $tsId . self::WIDGET_FILE_SUFFIX;
         $writePath = self::IMAGE_LOCAL_PATH . $tsId . self::WIDGET_FILE_SUFFIX;
         $cacheId = self::CACHEID;
     }
     $result = $ioObject->read($readPath);
     $ioObject->write($writePath, $result);
     Mage::app()->saveCache($writePath, $cacheId, array(), 1);
     $ioObject->close();
 }
示例#21
0
 /**
  *
  */
 public function writeToCache($folder, $file, $value, $e = 'css')
 {
     $file = $folder . preg_replace('/[^A-Z0-9\\._-]/i', '', $file) . '.' . $e;
     if (file_exists($file)) {
         unlink($file);
     }
     $flocal = new Varien_Io_File();
     $flocal->open(array('path' => $folder));
     $flocal->write($file, $value);
     $flocal->close();
     @chmod($file, 0755);
 }
示例#22
0
 /**
  * Import images before products
  *
  * @param Varien_Event_Observer $observer
  *
  * @return boolean
  */
 public function importMedia($observer)
 {
     $this->_createMediaImportFolder();
     $ioAdapter = new Varien_Io_File();
     $entities = $observer->getDataSourceModel()->getEntities();
     $uploader = $observer->getUploader();
     $tmpImportFolder = $uploader->getTmpDir();
     $attributes = Mage::getResourceModel('catalog/product_attribute_collection')->getItems();
     $mediaAttr = array();
     $mediaAttributeId = Mage::getModel('eav/entity_attribute')->load('media_gallery', 'attribute_code')->getAttributeId();
     foreach ($attributes as $attr) {
         if ($attr->getFrontendInput() === 'media_image') {
             $mediaAttr[] = $attr->getAttributeCode();
         }
     }
     foreach ($entities as $key => $entity) {
         foreach ($mediaAttr as $attr) {
             if ($this->_isImageToImport($entity, $attr)) {
                 try {
                     $ioAdapter->open(array('path' => $tmpImportFolder));
                     $ioAdapter->write(end(explode('/', $entity[$attr])), base64_decode($entity[$attr . '_content']), 0666);
                     $entities[$key]['_media_attribute_id'] = $mediaAttributeId;
                     unset($entities[$key][$attr . '_content']);
                 } catch (Exception $e) {
                     Mage::throwException($e->getMessage());
                 }
             }
         }
     }
     $observer->getDataSourceModel()->setEntities($entities);
     return true;
 }
 /**
  * Save operation file history.
  *
  * @throws Mage_Core_Exception
  * @param string $source
  * @return Enterprise_ImportExport_Model_Scheduled_Operation
  */
 protected function _saveOperationHistory($source)
 {
     $filePath = $this->getHistoryFilePath();
     $fs = new Varien_Io_File();
     $fs->open(array('path' => dirname($filePath)));
     if (!$fs->write(basename($filePath), $source)) {
         Mage::throwException(Mage::helper('enterprise_importexport')->__('Unable to save file history file'));
     }
     return $this;
 }
示例#24
0
 /**
  * Generates a lock file based on the contents defined in configuration XML and writes to the file defined by the file param
  */
 protected function generate()
 {
     // load configs to be locked and emails to be notified
     $protectedStores = Mage::getConfig()->getNode(self::PROTECTED_STORES_KEY);
     $contacts = Mage::getConfig()->getNode(self::CONTACT_EMAILS_KEY);
     if (!$protectedStores || !$contacts) {
         $this->fatal("Unable to access configuration properties");
     }
     $protectedStores = $protectedStores->asArray();
     $contacts = $contacts->asArray();
     $mandrillApiKey = null;
     // Check if mandrill has been enabled and code the credentials into the lock file.
     if (Mage::getConfig()->getModuleConfig('Ebizmarts_Mandrill')->is('active', 'true') && Mage::getStoreConfig('mandrill/general/active')) {
         $mandrillApiKey = Mage::helper('core')->encrypt(Mage::getStoreConfig("mandrill/general/apikey"));
     }
     $lockData = array('emails' => $contacts, 'mandrillApiKey' => $mandrillApiKey, 'hashes' => array());
     foreach ($protectedStores as $storeCode => $keys) {
         $this->debug($storeCode);
         $lockData['hashes'][$storeCode] = array();
         foreach ($keys as $key) {
             $this->debug($key);
             $store = Mage::getModel("core/store")->load($storeCode, "code");
             $configValue = Mage::getStoreConfig($key, $store);
             $this->debug($configValue);
             $hash = password_hash($configValue, PASSWORD_BCRYPT, array("cost" => self::BCRYPT_COST));
             $this->debug($hash);
             $lockData['hashes'][$storeCode][$key] = $hash;
         }
     }
     $data = json_encode($lockData);
     $lockFileName = $this->getArg('file');
     if ($lockFileName) {
         $outfile = new Varien_Io_File();
         $outfile->open(array('path' => dirname($lockFileName)));
         if (!$outfile->write(basename($lockFileName), $data)) {
             $this->fatal("Unable to write file");
         }
     } else {
         $this->fatal("Must supply file argument to write lock file");
     }
     $this->info("Lock file successfully written");
 }
 protected function _processContactImportReportFaults($id, $websiteId)
 {
     $helper = Mage::helper('ddg');
     $client = $helper->getWebsiteApiClient($websiteId);
     if ($client instanceof Dotdigitalgroup_Email_Model_Apiconnector_Client) {
         $data = $client->getContactImportReportFaults($id);
         if ($data) {
             $data = $this->_removeUtf8Bom($data);
             $fileName = Mage::getBaseDir('var') . DS . 'DmTempCsvFromApi.csv';
             $io = new Varien_Io_File();
             $io->open();
             $check = $io->write($fileName, $data);
             if ($check) {
                 try {
                     $csvArray = $this->_csvToArray($fileName);
                     $io->rm($fileName);
                     Mage::getResourceModel('ddg_automation/contact')->unsubscribe($csvArray);
                 } catch (Exception $e) {
                     Mage::logException($e);
                 }
             } else {
                 $helper->log('_processContactImportReportFaults: cannot save data to CSV file.');
             }
         }
     }
 }
示例#26
0
 public function checkLicense($product, $key, $update = false)
 {
     return true;
     //        if ($update)
     //            $this->checkUpdate();
     # Get Variables from storage (retrieve from wherever it's stored - DB, file, etc...)
     $session = Mage::getSingleton('adminhtml/session');
     $msgs = $session->getMessages(true);
     $msgs->deleteMessageByIdentifier($product);
     $licensekey = $key;
     $dir = Mage::getBaseDir("var") . DS . "smartosc" . DS . strtolower(substr($product, 0, 5)) . DS;
     $filepath = $dir . "license.dat";
     $file = new Varien_Io_File();
     if (!($localkey = $file->read($filepath))) {
         $localkey = "";
     }
     # The call below actually performs the license check. You need to pass in the license key and the local key data
     if (!$update) {
         $results = $this->_checkLicense($licensekey, $localkey);
     } else {
         $results = $this->_checkLicense($licensekey);
     }
     # For Debugging, Echo Results
     //        ob_start();
     //        echo "<textarea cols=100 rows=20>";
     //        print_r($results);
     //        echo "</textarea>";
     //die;
     if (strtoupper($results["status"]) == "ACTIVE") {
         # Allow Script to Run
         if (strtoupper($results['productname']) == strtoupper($product)) {
             if ($results["localkey"]) {
                 # Save Updated Local Key to DB or File
                 $localkeydata = $results["localkey"];
                 if (!is_dir_writeable($dir)) {
                     $file->checkAndCreateFolder($dir);
                 }
                 if (!$file->write($filepath, $localkeydata)) {
                     die('Cannot update licensing data to ' . $filepath);
                 }
             }
             Mage::getModel('core/config')->saveConfig($product . '/general/license_status', $results["status"] . " until " . $results['nextduedate']);
             Mage::getConfig()->cleanCache();
             if ($update) {
                 $session->addSuccess("The license key is valid!");
                 if ($msgs->getLastAddedMessage()) {
                     $msgs->getLastAddedMessage()->setIdentifier($product);
                 }
             }
             return true;
         }
     } elseif ($results["status"] == "Invalid") {
         $message = $results["status"];
     } elseif ($results["status"] == "Expired") {
         $message = $results["status"];
     } elseif ($results["status"] == "Suspended") {
         $message = $results["status"];
     }
     $session->addError('The "' . $product . '" extension has been disabled or your license key is invalid!');
     if ($msgs->getLastAddedMessage()) {
         $msgs->getLastAddedMessage()->setIdentifier($product);
     }
     Mage::getModel('core/config')->saveConfig($product . '/general/license_status', $message);
     Mage::getConfig()->cleanCache();
     return false;
 }
示例#27
0
 public static function update()
 {
     Mage::log('Fontis/Australia_Model_Getprice_Cron: Entered update function');
     if (Mage::getStoreConfig('fontis_feeds/getpricefeed/active')) {
         $io = new Varien_Io_File();
         $io->setAllowCreateFolders(true);
         $io->open(array('path' => self::getPath()));
         // Loop through all stores:
         foreach (Mage::app()->getStores() as $store) {
             Mage::log('Fontis/Australia_Model_Getprice_Cron: Processing store: ' . $store->getName());
             $clean_store_name = str_replace('+', '-', strtolower(urlencode($store->getName())));
             // Write the entire products xml file:
             Mage::log('Fontis/Australia_Model_Getprice_Cron: Generating All Products XML File');
             $products_result = self::getProductsXml($store);
             $io->write($clean_store_name . '-products.xml', $products_result['xml']);
             Mage::log('Fontis/Australia_Model_Getprice_Cron: Wrote to file: ' . $clean_store_name . '-products.xml', $products_result['xml']);
             // Write the leaf categories xml file:
             Mage::log('Fontis/Australia_Model_Getprice_Cron: Generating Categories XML File');
             $categories_result = self::getCategoriesXml($store);
             $io->write($clean_store_name . '-categories.xml', $categories_result['xml']);
             Mage::log('Fontis/Australia_Model_Getprice_Cron: Wrote to file: ' . $clean_store_name . '-categories.xml', $categories_result['xml']);
             // Write for each leaf category, their products xml file:
             foreach ($categories_result['link_ids'] as $link_id) {
                 Mage::log('Fontis/Australia_Model_Getprice_Cron: Generating Product Category XML File: ' . $link_id);
                 $subcategory_products_result = self::getProductsXml($store, $link_id);
                 $io->write($clean_store_name . '-products-' . $link_id . '.xml', $subcategory_products_result['xml']);
                 Mage::log('Fontis/Australia_Model_Getprice_Cron: Wrote to file: ' . $clean_store_name . '-products-' . $link_id . '.xml', $subcategory_products_result['xml']);
             }
         }
         $io->close();
     } else {
         Mage::log('Fontis/Australia_Model_Getprice_Cron: Disabled');
     }
 }
示例#28
0
 /**
  * Set the backup file content
  *
  * @param string $content
  * @return Mage_Backup_Model_Backup
  * @throws Mage_Backup_Exception
  */
 public function setFile(&$content)
 {
     if (!$this->hasData('time') || !$this->hasData('type') || !$this->hasData('path')) {
         Mage::throwException(Mage::helper('backup')->__('Wrong order of creation for new backup.'));
     }
     $ioProxy = new Varien_Io_File();
     $ioProxy->setAllowCreateFolders(true);
     $ioProxy->open(array('path' => $this->getPath()));
     $compress = 0;
     if (extension_loaded("zlib")) {
         $compress = 1;
     }
     $rawContent = '';
     if ($compress) {
         $rawContent = gzcompress($content, self::COMPRESS_RATE);
     } else {
         $rawContent = $content;
     }
     $fileHeaders = pack("ll", $compress, strlen($rawContent));
     $ioProxy->write($this->getFileName(), $fileHeaders . $rawContent);
     return $this;
 }
示例#29
0
 /**
  * Update image data
  *
  * @param int|string $productId
  * @param string $file
  * @param array $data
  * @param string|int $store
  * @return boolean
  */
 public function update($productId, $file, $data, $store = null, $identifierType = null)
 {
     $data = $this->_prepareImageData($data);
     $product = $this->_initProduct($productId, $store, $identifierType);
     $gallery = $this->_getGalleryAttribute($product);
     if (!$gallery->getBackend()->getImage($product, $file)) {
         $this->_fault('not_exists');
     }
     if (isset($data['file']['mime']) && isset($data['file']['content'])) {
         if (!isset($this->_mimeTypes[$data['file']['mime']])) {
             $this->_fault('data_invalid', Mage::helper('catalog')->__('Invalid image type.'));
         }
         $fileContent = @base64_decode($data['file']['content'], true);
         if (!$fileContent) {
             $this->_fault('data_invalid', Mage::helper('catalog')->__('Image content is not valid base64 data.'));
         }
         unset($data['file']['content']);
         $ioAdapter = new Varien_Io_File();
         try {
             $fileName = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $file;
             $ioAdapter->open(array('path' => dirname($fileName)));
             $ioAdapter->write(basename($fileName), $fileContent, 0666);
         } catch (Exception $e) {
             $this->_fault('not_created', Mage::helper('catalog')->__('Can\'t create image.'));
         }
     }
     $gallery->getBackend()->updateImage($product, $file, $data);
     if (isset($data['types']) && is_array($data['types'])) {
         $oldTypes = array();
         foreach ($product->getMediaAttributes() as $attribute) {
             if ($product->getData($attribute->getAttributeCode()) == $file) {
                 $oldTypes[] = $attribute->getAttributeCode();
             }
         }
         $clear = array_diff($oldTypes, $data['types']);
         if (count($clear) > 0) {
             $gallery->getBackend()->clearMediaAttribute($product, $clear);
         }
         $gallery->getBackend()->setMediaAttribute($product, $data['types'], $file);
     }
     try {
         $product->save();
     } catch (Mage_Core_Exception $e) {
         $this->_fault('not_updated', $e->getMessage());
     }
     return true;
 }
示例#30
0
 public static function update()
 {
     Mage::log('Fontis/Australia_Model_MyShopping_Cron: Entered update function');
     if (Mage::getStoreConfig('fontis_feeds/myshoppingfeed/active')) {
         $io = new Varien_Io_File();
         $io->setAllowCreateFolders(true);
         $io->open(array('path' => self::getPath()));
         // Loop through all stores:
         foreach (Mage::app()->getStores() as $store) {
             Mage::log('Fontis/Australia_Model_MyShopping_Cron: Processing store: ' . $store->getName());
             $clean_store_name = str_replace('+', '-', strtolower(urlencode($store->getName())));
             Fontis_Australia_Model_MyShopping_Cron::$debugCount = 0;
             // Write the entire products xml file:
             Mage::log('Fontis/Australia_Model_MyShopping_Cron: Generating All Products XML File');
             $products_result = self::getProductsXml($store);
             $filename = $clean_store_name . '-products.xml';
             $io->write($filename, $products_result['xml']);
             Mage::log('Fontis/Australia_Model_MyShopping_Cron: Wrote ' . Fontis_Australia_Model_MyShopping_Cron::$debugCount . " records to " . self::getPath() . $filename);
         }
         $io->close();
     } else {
         Mage::log('Fontis/Australia_Model_MyShopping_Cron: Disabled');
     }
 }