/** * Custom options downloader */ public function downloadCustomOptionAction() { $quoteItemOptionId = $this->getRequest()->getParam('id'); $secretKey = $this->getRequest()->getParam('key'); $option = AO::getModel('sales/quote_item_option')->load($quoteItemOptionId); if ($option->getId()) { try { $info = unserialize($option->getValue()); if ($secretKey != $info['secret_key']) { throw new Exception(); } $filePath = AO::getBaseDir() . $info['order_path']; if (!is_file($filePath) || !is_readable($filePath)) { // try get file from quote $filePath = AO::getBaseDir() . $info['quote_path']; if (!is_file($filePath) || !is_readable($filePath)) { throw new Exception(); } } $this->getResponse()->setHttpResponseCode(200)->setHeader('Pragma', 'public', true)->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)->setHeader('Content-type', $info['type'], true)->setHeader('Content-Length', $info['size'])->setHeader('Content-Disposition', 'inline' . '; filename=' . $info['title']); $this->getResponse()->clearBody(); $this->getResponse()->sendHeaders(); readfile($filePath); } catch (Exception $e) { $this->_forward('noRoute'); } } else { $this->_forward('noRoute'); } }
public function install() { $data = $this->getConfigData(); foreach (AO::getModel('core/config')->getDistroServerVars() as $index => $value) { if (!isset($data[$index])) { $data[$index] = $value; } } if (isset($data['unsecure_base_url'])) { $data['unsecure_base_url'] .= substr($data['unsecure_base_url'], -1) != '/' ? '/' : ''; if (!$this->_getInstaller()->getDataModel()->getSkipBaseUrlValidation()) { $this->_checkUrl($data['unsecure_base_url']); } } if (isset($data['secure_base_url'])) { $data['secure_base_url'] .= substr($data['secure_base_url'], -1) != '/' ? '/' : ''; if (!empty($data['use_secure']) && !$this->_getInstaller()->getDataModel()->getSkipUrlValidation()) { $this->_checkUrl($data['secure_base_url']); } } $data['date'] = self::TMP_INSTALL_DATE_VALUE; $data['key'] = self::TMP_ENCRYPT_KEY_VALUE; $data['var_dir'] = $data['root_dir'] . '/var'; $data['use_script_name'] = isset($data['use_script_name']) ? 'true' : 'false'; $this->_getInstaller()->getDataModel()->setConfigData($data); $template = file_get_contents(AO::getBaseDir('etc') . DS . 'local.xml.template'); foreach ($data as $index => $value) { $template = str_replace('{{' . $index . '}}', '<![CDATA[' . $value . ']]>', $template); } file_put_contents($this->_localConfigFile, $template); chmod($this->_localConfigFile, 0777); }
/** * Get all packages identifiers * * @return array */ protected function _fetchPackages() { $baseDir = AO::getBaseDir('var') . DS . 'pear'; $files = array(); $this->_collectRecursive($baseDir, $files); $result = array(); foreach ($files as $file) { $file = preg_replace(array('/^' . preg_quote($baseDir . DS, '/') . '/', '/\\.(xml|ser)$/'), '', $file); $result[] = array('filename' => $file, 'filename_id' => $file); } return $result; }
public function getUrl($object, $size = null) { $url = false; $image = $object->getData($this->getAttribute()->getAttributeCode()); if (!is_null($size) && file_exists(AO::getBaseDir('media') . DS . 'catalog' . DS . 'product' . DS . $size . DS . $image)) { # resized image is cached $url = AO::getBaseUrl('media') . 'catalog/product/' . $size . '/' . $image; } elseif (!is_null($size)) { # resized image is not cached $url = AO::getBaseUrl() . 'catalog/product/image/size/' . $size . '/' . $image; } elseif ($image) { # using original image $url = AO::getBaseUrl('media') . 'catalog/product/' . $image; } return $url; }
/** * 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) { $product = $this->_initProduct($productId, $store); $gallery = $this->_getGalleryAttribute($product); if (!isset($data->file) || !isset($data->file->mime) || !isset($data->file->content)) { $this->_fault('data_invalid', AO::helper('catalog')->__('Image not specified.')); } if (!isset($this->_mimeTypes[$data->file->mime])) { $this->_fault('data_invalid', AO::helper('catalog')->__('Invalid image type.')); } $fileContent = @base64_decode($data->file->content, true); if (!$fileContent) { $this->_fault('data_invalid', AO::helper('catalog')->__('Image content is not valid base64 data.')); } unset($data->file->content); $tmpDirectory = AO::getBaseDir('var') . DS . 'api' . DS . $this->_getSession()->getSessionId(); $fileName = 'image.' . $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); $_imageData = $this->_prepareImageData($data); $gallery->getBackend()->updateImage($product, $file, $_imageData); 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', AO::helper('catalog')->__('Can\'t create image.')); } return $gallery->getBackend()->getRenamedImage($file); }
/** * Enter description here... * * @param Varien_Object $object */ public function beforeSave($object) { $value = $object->getData($this->getAttribute()->getName()); if (is_array($value) && !empty($value['delete'])) { $object->setData($this->getAttribute()->getName(), ''); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); return; } $path = AO::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS; try { $uploader = new Varien_File_Uploader($this->getAttribute()->getName()); $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png')); $uploader->setAllowRenameFiles(true); $uploader->save($path); $object->setData($this->getAttribute()->getName(), $uploader->getUploadedFileName()); $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getName()); } catch (Exception $e) { /** @TODO ??? */ return; } }
public function start() { if (VPROF) { Varien_Profiler::start(__METHOD__ . '/setOptions'); } $options = array('save_path' => AO::getBaseDir('session'), 'use_only_cookies' => 'off'); if ($this->getCookieDomain()) { $options['cookie_domain'] = $this->getCookieDomain(); } if ($this->getCookiePath()) { $options['cookie_path'] = $this->getCookiePath(); } if ($this->getCookieLifetime()) { $options['cookie_lifetime'] = $this->getCookieLifetime(); } Zend_Session::setOptions($options); if (VPROF) { Varien_Profiler::stop(__METHOD__ . '/setOptions'); } /* if (VPROF) Varien_Profiler::start(__METHOD__.'/setHandler'); $sessionResource = AO::getResourceSingleton('core/session'); if ($sessionResource->hasConnection()) { Zend_Session::setSaveHandler($sessionResource); } if (VPROF) Varien_Profiler::stop(__METHOD__.'/setHandler'); */ if (VPROF) { Varien_Profiler::start(__METHOD__ . '/start'); } Zend_Session::start(); if (VPROF) { Varien_Profiler::stop(__METHOD__ . '/start'); } return $this; }
public function installAction() { $params = array('comment' => AO::helper('adminhtml')->__("Pending installation...") . "\r\n\r\n"); if ($this->getRequest()->getParam('do')) { switch ($this->getRequest()->getParam('file_type')) { case 'local': if (empty($_FILES['local']['tmp_name'])) { $params['comment'] = AO::helper('adminhtml')->__("Error uploading the file") . "\r\n\r\n"; break; } $tmpDir = AO::getBaseDir('var') . DS . 'pear'; if (!is_dir($tmpDir)) { mkdir($tmpDir, 0777, true); } $pkg = $tmpDir . DS . $_FILES['local']['name']; move_uploaded_file($_FILES['local']['tmp_name'], $pkg); break; case 'remote': $pkg = $this->getRequest()->getParam('remote'); if (empty($pkg)) { $params['comment'] = AO::helper('adminhtml')->__("Invalid URL") . "\r\n\r\n"; } break; } if (!empty($pkg)) { $params['comment'] = AO::helper('adminhtml')->__("Installing {$pkg}, please wait...") . "\r\n\r\n"; $params['command'] = 'install'; $params['options'] = array(); $params['params'] = array($pkg); } } $result = Varien_Pear::getInstance()->runHtmlConsole($params); if (!$result instanceof PEAR_Error) { AO::getModel('adminhtml/extension')->clearAllCache(); } }
protected function _loadFiles() { if (!$this->_isLoaded) { $readPath = AO::getBaseDir('var') . DS . "backups"; $ioProxy = new Varien_Io_File(); try { $ioProxy->open(array('path' => $readPath)); } catch (Exception $e) { $ioProxy->mkdir($readPath, 0777); $ioProxy->chmod($readPath, 0777); $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); $item->setSize($entry['size']); 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; }
/** * Render block * * @return string */ public function renderView() { if (VPROF) { Varien_Profiler::start(__METHOD__); } $this->setScriptPath(AO::getBaseDir('design')); $params = array('_relative' => true); if ($area = $this->getArea()) { $params['_area'] = $area; } $templateName = Mage_Core_Model_Design_Package::getDesign()->getTemplateFilename($this->getTemplate(), $params); $templateName = scrunchName($templateName, 5); //var_dump($templateName); //var_dump(get_class($this)); $html = $this->fetchView($templateName); if (VPROF) { Varien_Profiler::stop(__METHOD__); } return $html; }
public function releaseAction() { #Varien_Pear::getInstance()->runHtmlConsole(array('command'=>'list-channels')); if (empty($_POST)) { $serFiles = @glob(AO::getBaseDir('var') . DS . 'pear' . DS . '*.ser'); if (!$serFiles) { return; } $pkg = new Varien_Object(); echo '<html><head><style type="text/css">* { font:normal 12px Arial }</style></head> <body><form method="post"><table border="1" cellpadding="3" cellspacing="0"><thead> <tr><th>Update/Package</th><th>Version</th><th>State</th></tr> </thead><tbody>'; foreach ($serFiles as $i => $file) { $serialized = file_get_contents($file); $pkg->setData(unserialize($serialized)); $n = $pkg->getName(); echo '<tr><td><input type="checkbox" name="pkgs[' . $i . '][name]" id="pkg_' . $i . '" value="' . $n . '"/> <label for="pkg_' . $i . '">' . $n . '</label> <input type="hidden" name="pkgs[' . $i . '][file]" value="' . $file . '"/> </td> <td><input name="pkgs[' . $i . '][release_version]" value="' . $pkg->getData('release_version') . '"/></td> <td><input name="pkgs[' . $i . '][release_stability]" value="' . $pkg->getData('release_stability') . '"/></td> </tr>'; #echo "<pre>"; print_r($pkg->getData()); echo "</pre>"; exit; } echo '</tbody></table><button type="submit">Save and Generate Packages</button></form></body></html>'; } else { @set_time_limit(0); ob_implicit_flush(); foreach ($_POST['pkgs'] as $r) { if (empty($r['name'])) { continue; } echo "<hr/><h4>" . $r['name'] . "</h4>"; $ext = AO::getModel('adminhtml/extension'); $ext->setData(unserialize(file_get_contents($r['file']))); $ext->setData('release_version', $r['release_version']); $ext->setData('release_stability', $r['release_stability']); #echo "<pre>"; print_r($ext->getData()); echo "</pre>"; $result = $ext->savePackage(); if (!$result) { echo "ERROR while creating the package"; continue; } else { echo "Package created; "; } $result = $ext->createPackage(); $pear = Varien_Pear::getInstance(); if ($result) { $data = $pear->getOutput(); print_r($data[0]['output']); } else { echo "ERROR:"; print_r($result->getMessage()); } } echo '<hr/><a href="' . $_SERVER['REQUEST_URI'] . '">Refresh</a>'; } exit; }
/** * Backup database * * @param string $failPath redirect path if backup failed * @param array $arguments * @return Mage_Adminhtml_System_StoreController */ protected function _backupDatabase($failPath, $arguments = array()) { if (!$this->getRequest()->getParam('create_backup')) { return $this; } try { $backupDb = AO::getModel('backup/db'); $backup = AO::getModel('backup/backup')->setTime(time())->setType('db')->setPath(AO::getBaseDir('var') . DS . 'backups'); $backupDb->createBackup($backup); $this->_getSession()->addSuccess(AO::helper('backup')->__('Database was successfuly backed up.')); } catch (Mage_Core_Exception $e) { $this->_getSession()->addError($e->getMessage()); $this->_redirect($failPath, $arguments); return; } catch (Exception $e) { $this->_getSession()->addException($e, AO::helper('backup')->__('Unable to create backup. Please, try again later.')); $this->_redirect($failPath, $arguments); return; } return $this; }
/** * Retrive translated template file * * @param string $file * @param string $type * @param string $localeCode * @return string */ public function getTemplateFile($file, $type, $localeCode = null) { if (is_null($localeCode) || preg_match('/[^a-zA-Z_]/', $localeCode)) { $localeCode = $this->getLocale(); } $filePath = AO::getBaseDir('locale') . DS . $localeCode . DS . 'template' . DS . $type . DS . $file; if (!file_exists($filePath)) { // If no template specified for this locale, use store default $filePath = AO::getBaseDir('locale') . DS . AO::app()->getLocale()->getDefaultLocale() . DS . 'template' . DS . $type . DS . $file; } if (!file_exists($filePath)) { // If no template specified as store default locale, use en_US $filePath = AO::getBaseDir('locale') . DS . Mage_Core_Model_Locale::DEFAULT_LOCALE . DS . 'template' . DS . $type . DS . $file; } $ioAdapter = new Varien_Io_File(); $ioAdapter->open(array('path' => AO::getBaseDir('locale'))); return (string) $ioAdapter->read($filePath); }
/** * Retrieve cache object * * @return Zend_Cache_Core */ public function getCache() { if (!$this->_cache) { $backend = strtolower((string) AO::getConfig()->getNode('global/cache/backend')); if (extension_loaded('apc') && ini_get('apc.enabled') && $backend == 'apc') { $backend = 'Apc'; $backendAttributes = array('cache_prefix' => (string) AO::getConfig()->getNode('global/cache/prefix')); } elseif ('memcached' == $backend && extension_loaded('memcache')) { $backend = 'Memcached'; $memcachedConfig = AO::getConfig()->getNode('global/cache/memcached'); $backendAttributes = array('compression' => (bool) $memcachedConfig->compression, 'cache_dir' => (string) $memcachedConfig->cache_dir, 'hashed_directory_level' => (string) $memcachedConfig->hashed_directory_level, 'hashed_directory_umask' => (string) $memcachedConfig->hashed_directory_umask, 'file_name_prefix' => (string) $memcachedConfig->file_name_prefix, 'servers' => array()); foreach ($memcachedConfig->servers->children() as $serverConfig) { $backendAttributes['servers'][] = array('host' => (string) $serverConfig->host, 'port' => (string) $serverConfig->port, 'persistent' => (string) $serverConfig->persistent); } } else { $backend = 'File'; $backendAttributes = array('cache_dir' => AO::getBaseDir('cache'), 'hashed_directory_level' => 1, 'hashed_directory_umask' => 0777, 'file_name_prefix' => 'mage'); } $lifetime = AO::getConfig()->getNode('global/cache/lifetime'); if ($lifetime !== false) { $lifetime = (int) $lifetime; } else { $lifetime = 7200; } $this->_cache = Zend_Cache::factory('Core', $backend, array('caching' => true, 'lifetime' => $lifetime, 'automatic_cleaning_factor' => 0), $backendAttributes); } return $this->_cache; }
/** * Get sesssion save path * * @return string */ public function getSessionSavePath() { return AO::getBaseDir('session'); }
protected function _setFontItalic($object, $size = 7) { $font = Zend_Pdf_Font::fontWithPath(AO::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_It-2.8.2.ttf'); $object->setFont($font, $size); return $font; }
public function getThemeList($package = null) { $result = array(); if (is_null($package)) { foreach ($this->getPackageList() as $package) { $result[$package] = $this->getThemeList($package); } } else { $directory = AO::getBaseDir('design') . DS . 'frontend' . DS . $package; $result = $this->_listDirectories($directory); } return $result; }
public function clearCache() { $directory = AO::getBaseDir('media') . DS . 'catalog' . DS . 'product' . DS . 'cache' . DS; $io = new Varien_Io_File(); $io->rmdir($directory, true); }
public function getBaseTmpMediaPath() { return AO::getBaseDir('media') . DS . 'tmp' . DS . 'catalog' . DS . 'product'; }
/** * Return real file path * * @return string */ protected function getPath() { if (is_null($this->_filePath)) { $this->_filePath = str_replace('//', '/', AO::getBaseDir() . $this->getSitemapPath()); } return $this->_filePath; }
/** * Redirect action. Redirect to Paybox using commandline mode * */ public function commandlineAction() { $session = $this->getCheckout(); $session->setPayboxQuoteId($session->getQuoteId()); $order = AO::getModel('sales/order')->loadByIncrementId($this->getCheckout()->getLastRealOrderId()); $order->addStatusToHistory($order->getStatus(), $this->__('Customer was redirected to Paybox using \'command line\' mode')); $order->save(); $session->setPayboxOrderId(AO::helper('core')->encrypt($session->getLastRealOrderId())); $session->setPayboxPaymentAction($order->getPayment()->getMethodInstance()->getPaymentAction()); $session->unsQuoteId(); $payment = $order->getPayment()->getMethodInstance(); $fieldsArr = $payment->getFormFields(); $paramStr = ''; foreach ($fieldsArr as $k => $v) { $paramStr .= $k . '=' . $v . ' '; } $paramStr = str_replace(';', '\\;', $paramStr); $result = shell_exec(AO::getBaseDir() . '/' . $this->getModel()->getPayboxFile() . ' ' . $paramStr); if (isset($fieldsArr['PBX_PING']) && $fieldsArr['PBX_PING'] == '1') { $fieldsArr['PBX_PING'] = '0'; $fieldsArr['PBX_PAYBOX'] = trim(substr($result, strpos($result, 'http'))); $paramStr = ''; foreach ($fieldsArr as $k => $v) { $paramStr .= $k . '=' . $v . ' '; } $paramStr = str_replace(';', '\\;', $paramStr); $result = shell_exec(AO::getBaseDir() . '/' . $this->getModel()->getPayboxFile() . ' ' . $paramStr); } $this->loadLayout(false); $this->getResponse()->setBody($result); $this->renderLayout(); }
/** * Retrieve real path to tmp dir * * @return string */ public function getPath() { if (is_null($this->_path)) { $this->_path = $this->getIoAdapter()->getCleanPath(AO::getBaseDir('tmp')); $this->getIoAdapter()->checkAndCreateFolder($this->_path); } return $this->_path; }
/** * Main Destination directory * * @param boolean $relative If true - returns relative path to the webroot * @return string */ public function getTargetDir($relative = false) { $fullPath = AO::getBaseDir('media') . DS . 'custom_options'; return $relative ? str_replace(AO::getBaseDir(), '', $fullPath) : $fullPath; }
/** * Retrieve Resource file handle (socket, file pointer etc) * * @return resource */ protected function _getHandle() { if (!$this->_resourceFile) { AO::throwException(AO::helper('downloadable')->__('Please set resource file and link type')); } if (is_null($this->_handle)) { if ($this->_linkType == self::LINK_TYPE_URL) { $port = 80; /** * Validate URL */ $urlProp = parse_url($this->_resourceFile); if (!isset($urlProp['scheme']) || strtolower($urlProp['scheme'] != 'http')) { AO::throwException(AO::helper('downloadable')->__('Invalid download URL scheme')); } if (!isset($urlProp['host'])) { AO::throwException(AO::helper('downloadable')->__('Invalid download URL host')); } $hostname = $urlProp['host']; if (isset($urlProp['port'])) { $port = (int) $urlProp['port']; } $path = '/'; if (isset($urlProp['path'])) { $path = $urlProp['path']; } $query = ''; if (isset($urlProp['query'])) { $query = '?' . $urlProp['query']; } try { $this->_handle = fsockopen($hostname, $port, $errno, $errstr); } catch (Exception $e) { throw $e; } if ($this->_handle === false) { AO::throwException(AO::helper('downloadable')->__('Can\'t connect to remote host, error: %s', $errstr)); } $headers = 'GET ' . $path . $query . ' HTTP/1.0' . "\r\n" . 'Host: ' . $hostname . "\r\n" . 'User-Agent: Magento ver/' . AO::getVersion() . "\r\n" . 'Connection: close' . "\r\n" . "\r\n"; fwrite($this->_handle, $headers); while (!feof($this->_handle)) { $str = fgets($this->_handle, 1024); if ($str == "\r\n") { break; } $match = array(); if (preg_match('#^([^:]+): (.*)\\s+$#', $str, $match)) { $k = strtolower($match[1]); if ($k == 'set-cookie') { continue; } else { $this->_urlHeaders[$k] = trim($match[2]); } } elseif (preg_match('#^HTTP/[0-9\\.]+ (\\d+) (.*)\\s$#', $str, $match)) { $this->_urlHeaders['code'] = $match[1]; $this->_urlHeaders['code-string'] = trim($match[2]); } } if (!isset($this->_urlHeaders['code']) || $this->_urlHeaders['code'] != 200) { AO::throwException(AO::helper('downloadable')->__('Sorry, the was an error getting requested content. Please contact store owner.')); } } elseif ($this->_linkType == self::LINK_TYPE_FILE) { $this->_handle = new Varien_Io_File(); $this->_handle->open(array('path' => AO::getBaseDir('var'))); if (!$this->_handle->fileExists($this->_resourceFile, true)) { AO::throwException(AO::helper('downloadable')->__('File does not exists')); } $this->_handle->streamOpen($this->_resourceFile, 'r'); } else { AO::throwException(AO::helper('downloadable')->__('Invalid download link type')); } } return $this->_handle; }
/** * Get temporary data directory name * * @param string $path * @param string $type * @return string */ public function getVarDir($path = null, $type = 'var') { $dir = AO::getBaseDir($type) . ($path !== null ? DS . $path : ''); if (!$this->createDirIfNotExists($dir)) { return false; } return $dir; }
/** * Save product (import) * * @param array $importData * @throws Mage_Core_Exception * @return bool */ public function saveRow(array $importData) { $product = $this->getProductModel(); $product->setData(array()); if ($stockItem = $product->getStockItem()) { $stockItem->setData(array()); } if (empty($importData['store'])) { if (!is_null($this->getBatchParams('store'))) { $store = $this->getStoreById($this->getBatchParams('store')); } else { $message = AO::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store'); AO::throwException($message); } } else { $store = $this->getStoreByCode($importData['store']); } if ($store === false) { $message = AO::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']); AO::throwException($message); } if (empty($importData['sku'])) { $message = AO::helper('catalog')->__('Skip import row, required field "%s" not defined', 'sku'); AO::throwException($message); } $product->setStoreId($store->getId()); $productId = $product->getIdBySku($importData['sku']); if ($productId) { $product->load($productId); } else { $productTypes = $this->getProductTypes(); $productAttributeSets = $this->getProductAttributeSets(); /** * Check product define type */ if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) { $value = isset($importData['type']) ? $importData['type'] : ''; $message = AO::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type'); AO::throwException($message); } $product->setTypeId($productTypes[strtolower($importData['type'])]); /** * Check product define attribute set */ if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) { $value = isset($importData['attribute_set']) ? $importData['attribute_set'] : ''; $message = AO::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'attribute_set'); AO::throwException($message); } $product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]); foreach ($this->_requiredFields as $field) { $attribute = $this->getAttribute($field); if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) { $message = AO::helper('catalog')->__('Skip import row, required field "%s" for new products not defined', $field); AO::throwException($message); } } } if (isset($importData['category_ids'])) { $product->setCategoryIds($importData['category_ids']); } foreach ($this->_ignoreFields as $field) { if (isset($importData[$field])) { unset($importData[$field]); } } if ($store->getId() != 0) { $websiteIds = $product->getWebsiteIds(); if (!is_array($websiteIds)) { $websiteIds = array(); } if (!in_array($store->getWebsiteId(), $websiteIds)) { $websiteIds[] = $store->getWebsiteId(); } $product->setWebsiteIds($websiteIds); } if (isset($importData['websites'])) { $websiteIds = $product->getWebsiteIds(); if (!is_array($websiteIds)) { $websiteIds = array(); } $websiteCodes = split(',', $importData['websites']); foreach ($websiteCodes as $websiteCode) { try { $website = AO::app()->getWebsite(trim($websiteCode)); if (!in_array($website->getId(), $websiteIds)) { $websiteIds[] = $website->getId(); } } catch (Exception $e) { } } $product->setWebsiteIds($websiteIds); unset($websiteIds); } foreach ($importData as $field => $value) { if (in_array($field, $this->_inventorySimpleFields)) { continue; } if (in_array($field, $this->_imageFields)) { continue; } $attribute = $this->getAttribute($field); if (!$attribute) { continue; } $isArray = false; $setValue = $value; if ($attribute->getFrontendInput() == 'multiselect') { $value = split(self::MULTI_DELIMITER, $value); $isArray = true; $setValue = array(); } if ($value && $attribute->getBackendType() == 'decimal') { $setValue = $this->getNumber($value); } if ($attribute->usesSource()) { $options = $attribute->getSource()->getAllOptions(false); if ($isArray) { foreach ($options as $item) { if (in_array($item['label'], $value)) { $setValue[] = $item['value']; } } } else { $setValue = null; foreach ($options as $item) { if ($item['label'] == $value) { $setValue = $item['value']; } } } } $product->setData($field, $setValue); } if (!$product->getVisibility()) { $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE); } $stockData = array(); $inventoryFields = $product->getTypeId() == 'simple' ? $this->_inventorySimpleFields : $this->_inventoryOtherFields; foreach ($inventoryFields as $field) { if (isset($importData[$field])) { if (in_array($field, $this->_toNumber)) { $stockData[$field] = $this->getNumber($importData[$field]); } else { $stockData[$field] = $importData[$field]; } } } $product->setStockData($stockData); $imageData = array(); foreach ($this->_imageFields as $field) { if (!empty($importData[$field]) && $importData[$field] != 'no_selection') { if (!isset($imageData[$importData[$field]])) { $imageData[$importData[$field]] = array(); } $imageData[$importData[$field]][] = $field; } } foreach ($imageData as $file => $fields) { try { $product->addImageToMediaGallery(AO::getBaseDir('media') . DS . 'import' . $file, $fields); } catch (Exception $e) { } } $product->setIsMassupdate(true); $product->setExcludeUrlRewrite(true); $product->save(); return true; }
/** * Save products data * * @param Mage_Oscommerce_Model_Oscommerce $obj * @param array $data */ protected function _saveProduct($data) { $importModel = $this->getImportModel(); $productAdapterModel = $this->getProductAdapterModel(); $productModel = $this->getProductModel(); $mageStores = $this->getLanguagesToStores(); $storeInfo = $this->getOscStoreInformation(); $storeName = $storeInfo['STORE_NAME']; $oscProductId = $data['id']; unset($data['id']); if ($this->_isProductWithCategories) { if ($categories = $this->getProductCategories($oscProductId)) { $data['category_ids'] = $categories; } } /** * Checking product by using sku and website */ if (empty($data['sku'])) { $data['sku'] = $storeName . ' - ' . $oscProductId; } $productModel->unsetData(); $productId = $productModel->getIdBySku($data['sku']); $productModel->load($productId); if ($productModel->getId()) { $websiteIds = $productModel->getWebsiteIds(); if ($websiteIds) { foreach ($websiteIds as $websiteId) { if ($websiteId == $this->getWebsiteModel()->getId()) { $this->_addErrors(AO::helper('oscommerce')->__('SKU %s was not imported since it already exists in %s', $data['sku'], $this->getWebsiteModel()->getName())); return; } } } } try { if (isset($data['image'])) { if (substr($data['image'], 0, 1) != DS) { $data['image'] = DS . $data['image']; } if (!file_exists(AO::getBaseDir('media') . DS . 'import' . $data['image'])) { unset($data['image']); } else { $data['thumbnail'] = $data['small_image'] = $data['image']; } } if ($stores = $this->getProductStores($oscProductId)) { foreach ($stores as $storeId => $store) { if (!($storeCode = $this->getStoreCodeById($mageStores[$storeId]))) { $storeCode = $this->getCurrentWebsite()->getDefaultStore()->getCode(); } $data['store'] = $storeCode; $data['name'] = html_entity_decode($this->convert($store['name']), ENT_QUOTES, self::DEFAULT_MAGENTO_CHARSET); $data['description'] = html_entity_decode($this->convert($store['description']), ENT_QUOTES, self::DEFAULT_MAGENTO_CHARSET); $data['short_description'] = $data['description']; $productAdapterModel->saveRow($data); } } $productId = $productAdapterModel->getProductModel()->getId(); $this->saveLogs(array($oscProductId => $productId), 'product'); $this->_saveRows++; } catch (Exception $e) { $this->_addErrors(AO::helper('oscommerce')->__('SKU %s cannot be saved because of %s', $data['sku'], $e->getMessage())); } }
/** * log facility (??) * * @param string $message * @param integer $level * @param string $file */ public static function log($message, $level = null, $file = '') { if (!self::getConfig()) { return; } if (!AO::getStoreConfig('dev/log/active')) { return; } static $loggers = array(); $level = is_null($level) ? Zend_Log::DEBUG : $level; if (empty($file)) { $file = AO::getStoreConfig('dev/log/file'); $file = empty($file) ? 'system.log' : $file; } try { if (!isset($loggers[$file])) { $logFile = AO::getBaseDir('var') . DS . 'log' . DS . $file; $logDir = AO::getBaseDir('var') . DS . 'log'; if (!is_dir(AO::getBaseDir('var') . DS . 'log')) { mkdir(AO::getBaseDir('var') . DS . 'log', 0777); } if (!file_exists($logFile)) { file_put_contents($logFile, ''); chmod($logFile, 0777); } $format = '%timestamp% %priorityName% (%priority%): %message%' . PHP_EOL; $formatter = new Zend_Log_Formatter_Simple($format); $writer = new Zend_Log_Writer_Stream($logFile); $writer->setFormatter($formatter); $loggers[$file] = new Zend_Log($writer); } if (is_array($message) || is_object($message)) { $message = print_r($message, true); } $loggers[$file]->log($message, $level); } catch (Exception $e) { } }
public static function getBasePath() { return AO::getBaseDir('media') . DS . 'downloadable' . DS . 'files' . DS . 'samples'; }
/** * Delete backup action */ public function deleteAction() { try { $backup = AO::getModel('backup/backup')->setTime((int) $this->getRequest()->getParam('time'))->setType($this->getRequest()->getParam('type'))->setPath(AO::getBaseDir("var") . DS . "backups")->deleteFile(); $this->_getSession()->addSuccess(AO::helper('adminhtml')->__('Backup record was deleted')); } catch (Exception $e) { // Nothing } $this->_redirect('*/*/'); }