Example #1
1
 /**
  * Change columns position
  *
  * @param string $table
  * @param string $column
  * @param boolean $after
  * @param boolean $first
  * @return Enterprise_SalesArchive_Model_Resource_Helper_Mysql4
  */
 public function changeColumnPosition($table, $column, $after = false, $first = false)
 {
     if ($after && $first) {
         if (is_string($after)) {
             $first = false;
         } else {
             $after = false;
         }
     } elseif (!$after && !$first) {
         // If no new position specified
         return $this;
     }
     if (!$this->_getWriteAdapter()->isTableExists($table)) {
         Mage::throwException(Mage::helper('enterprise_salesarchive')->__('Table not found'));
     }
     $columns = array();
     $adapter = $this->_getWriteAdapter();
     $description = $adapter->describeTable($table);
     foreach ($description as $columnDescription) {
         $columns[$columnDescription['COLUMN_NAME']] = $adapter->getColumnDefinitionFromDescribe($columnDescription);
     }
     if (!isset($columns[$column])) {
         Mage::throwException(Mage::helper('enterprise_salesarchive')->__('Column not found'));
     } elseif ($after && !isset($columns[$after])) {
         Mage::throwException(Mage::helper('enterprise_salesarchive')->__('Positioning column not found'));
     }
     if ($after) {
         $sql = sprintf('ALTER TABLE %s MODIFY COLUMN %s %s AFTER %s', $adapter->quoteIdentifier($table), $adapter->quoteIdentifier($column), $columns[$column], $adapter->quoteIdentifier($after));
     } else {
         $sql = sprintf('ALTER TABLE %s MODIFY COLUMN %s %s FIRST', $adapter->quoteIdentifier($table), $adapter->quoteIdentifier($column), $columns[$column]);
     }
     $adapter->query($sql);
     return $this;
 }
 /**
  * Prepares and render result of composite product configuration request
  *
  * $configureResult holds either:
  *  - 'ok' = true, and 'product_id', 'buy_request', 'current_store_id', 'current_customer' or 'current_customer_id'
  *  - 'error' = true, and 'message' to show
  *
  * @param Mage_Adminhtml_Controller_Action $controller
  * @param Varien_Object $configureResult
  * @return Mage_Adminhtml_Helper_Catalog_Product_Composite
  */
 public function renderConfigureResult($controller, Varien_Object $configureResult)
 {
     try {
         if (!$configureResult->getOk()) {
             Mage::throwException($configureResult->getMessage());
         }
         $currentStoreId = (int) $configureResult->getCurrentStoreId();
         if (!$currentStoreId) {
             $currentStoreId = Mage::app()->getStore()->getId();
         }
         $product = Mage::getModel('catalog/product')->setStoreId($currentStoreId)->load($configureResult->getProductId());
         if (!$product->getId()) {
             Mage::throwException($this->__('Product is not loaded.'));
         }
         Mage::register('current_product', $product);
         Mage::register('product', $product);
         // Prepare buy request values
         $buyRequest = $configureResult->getBuyRequest();
         if ($buyRequest) {
             Mage::helper('catalog/product')->prepareProductOptions($product, $buyRequest);
         }
         $isOk = true;
         $productType = $product->getTypeId();
     } catch (Exception $e) {
         $isOk = false;
         $productType = null;
         Mage::register('composite_configure_result_error_message', $e->getMessage());
     }
     $this->_initConfigureResultLayout($controller, $isOk, $productType);
     $controller->renderLayout();
 }
Example #3
0
 /**
  * Retrieve required options from parent
  */
 protected function _beforeToHtml()
 {
     if (!$this->getParentBlock()) {
         Mage::throwException(Mage::helper('adminhtml')->__('Invalid parent block for this block'));
     }
     parent::_beforeToHtml();
 }
Example #4
0
 /**
  * Create additional xml index file with links to other xml files (if number of them more than 1)
  */
 public function createIndexSitemapFile()
 {
     if (sizeof($this->filenamesForIndexSitemap) > 1) {
         $io = new Varien_Io_File();
         $io->setAllowCreateFolders(true);
         $io->open(array('path' => $this->getPath()));
         $fileToCreate = Mage::helper('ascurl')->insertStringToFilename($this->getSitemapFilename(), '_index');
         if ($io->fileExists($fileToCreate) && !$io->isWriteable($fileToCreate)) {
             Mage::throwException(Mage::helper('sitemap')->__('File "%s" cannot be saved. Please, make sure the directory "%s" is writeable by web server.', $fileToCreate, $this->getPath()));
         }
         $io->streamOpen($fileToCreate);
         $io->streamWrite('<?xml version="1.0" encoding="UTF-8"?>' . "\n");
         $io->streamWrite('<sitemapindex ' . self::URLSET . '>');
         $storeId = $this->getStoreId();
         $baseUrl = Mage::app()->getStore($storeId)->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
         $date = Mage::getSingleton('core/date')->gmtDate('Y-m-d');
         $path = $this->getSitemapPath();
         $fullPath = preg_replace('/(?<=[^:])\\/{2,}/', '/', $baseUrl . $path);
         foreach ($this->filenamesForIndexSitemap as $item) {
             $xml = sprintf('<sitemap><loc>%s</loc><lastmod>%s</lastmod></sitemap>', htmlspecialchars($fullPath . $item), $date);
             $io->streamWrite($xml);
         }
         $io->streamWrite('</sitemapindex>');
         $io->streamClose();
     }
 }
 /**
  * Render shipping methods xml
  *
  * @return string
  */
 protected function _toHtml()
 {
     /** @var $methodsXmlObj Mage_XmlConnect_Model_Simplexml_Element */
     $methodsXmlObj = Mage::getModel('xmlconnect/simplexml_element', '<shipping_methods></shipping_methods>');
     $_shippingRateGroups = $this->getShippingRates();
     if ($_shippingRateGroups) {
         $store = $this->getQuote()->getStore();
         $_sole = count($_shippingRateGroups) == 1;
         foreach ($_shippingRateGroups as $code => $_rates) {
             $methodXmlObj = $methodsXmlObj->addChild('method');
             $methodXmlObj->addAttribute('label', $methodsXmlObj->escapeXml($this->getCarrierName($code)));
             $ratesXmlObj = $methodXmlObj->addChild('rates');
             $_sole = $_sole && count($_rates) == 1;
             foreach ($_rates as $_rate) {
                 $rateXmlObj = $ratesXmlObj->addChild('rate');
                 $rateXmlObj->addAttribute('label', $methodsXmlObj->escapeXml($_rate->getMethodTitle()));
                 $rateXmlObj->addAttribute('code', $_rate->getCode());
                 if ($_rate->getErrorMessage()) {
                     $rateXmlObj->addChild('error_message', $methodsXmlObj->escapeXml($_rate->getErrorMessage()));
                 } else {
                     $price = Mage::helper('tax')->getShippingPrice($_rate->getPrice(), Mage::helper('tax')->displayShippingPriceIncludingTax(), $this->getAddress());
                     $formattedPrice = $store->convertPrice($price, true, false);
                     $rateXmlObj->addAttribute('price', Mage::helper('xmlconnect')->formatPriceForXml($store->convertPrice($price, false, false)));
                     $rateXmlObj->addAttribute('formated_price', $formattedPrice);
                 }
             }
         }
     } else {
         Mage::throwException($this->__('Shipping to this address is not possible.'));
     }
     return $methodsXmlObj->asNiceXml();
 }
Example #6
0
 /**
  * Check if group uses as default
  *
  * @param  Mage_Core_Model_Abstract $group
  * @throws Mage_Core_Exception
  * @return Mage_Core_Model_Resource_Db_Abstract
  */
 protected function _beforeDelete(Mage_Core_Model_Abstract $group)
 {
     if ($group->usesAsDefault()) {
         Mage::throwException(Mage::helper('Mage_Customer_Helper_Data')->__('The group "%s" cannot be deleted', $group->getCode()));
     }
     return parent::_beforeDelete($group);
 }
 /**
  * Perform actions before object save
  *
  * @param Mage_Core_Model_Abstract $object
  * @return Mage_Core_Model_Resource_Db_Abstract
  * @throws Mage_Core_Exception
  */
 public function _beforeSave(Mage_Core_Model_Abstract $object)
 {
     if ($date = $object->getDateFrom()) {
         $object->setDateFrom($this->formatDate($date));
     } else {
         $object->setDateFrom(null);
     }
     if ($date = $object->getDateTo()) {
         $object->setDateTo($this->formatDate($date));
     } else {
         $object->setDateTo(null);
     }
     if (!is_null($object->getDateFrom()) && !is_null($object->getDateTo()) && Varien_Date::toTimestamp($object->getDateFrom()) > Varien_Date::toTimestamp($object->getDateTo())) {
         Mage::throwException(Mage::helper('core')->__('Start date cannot be greater than end date.'));
     }
     $check = $this->_checkIntersection($object->getStoreId(), $object->getDateFrom(), $object->getDateTo(), $object->getId());
     if ($check) {
         Mage::throwException(Mage::helper('core')->__('Your design change for the specified store intersects with another one, please specify another date range.'));
     }
     if ($object->getDateFrom() === null) {
         $object->setDateFrom(new Zend_Db_Expr('null'));
     }
     if ($object->getDateTo() === null) {
         $object->setDateTo(new Zend_Db_Expr('null'));
     }
     parent::_beforeSave($object);
 }
Example #8
0
 /**
  * REWRITE to properly trigger afterSave event
  *
  * Check base currency is available in installed currencies
  *
  * @return Mage_Adminhtml_Model_System_Config_Backend_Currency_Base
  */
 protected function _afterSave()
 {
     if (!in_array($this->getValue(), $this->_getInstalledCurrencies())) {
         Mage::throwException(Mage::helper('adminhtml')->__('Selected base currency is not available in installed currencies.'));
     }
     return parent::_afterSave();
 }
Example #9
0
 /**
  * Retrieve Product List Type identifier
  *
  * @throws Mage_Core_Exception
  *
  * @return int
  */
 public function getListType()
 {
     if (is_null($this->_listType)) {
         Mage::throwException(Mage::helper('enterprise_targetrule')->__('Product list type identifier does not defined'));
     }
     return $this->_listType;
 }
Example #10
0
 /**
  * Forced fetch reports action
  */
 public function fetchAction()
 {
     try {
         $reports = Mage::getModel('paypal/report_settlement');
         /* @var $reports Mage_Paypal_Model_Report_Settlement */
         $credentials = $reports->getSftpCredentials();
         if (empty($credentials)) {
             Mage::throwException(Mage::helper('paypal')->__('Nothing to fetch because of an empty configuration.'));
         }
         foreach ($credentials as $config) {
             try {
                 $fetched = $reports->fetchAndSave($config);
                 $this->_getSession()->addSuccess(Mage::helper('paypal')->__("Fetched %s report rows from '%s@%s'.", $fetched, $config['username'], $config['hostname']));
             } catch (Exception $e) {
                 $this->_getSession()->addError(Mage::helper('paypal')->__("Failed to fetch reports from '%s@%s'.", $config['username'], $config['hostname']));
                 Mage::logException($e);
             }
         }
     } catch (Mage_Core_Exception $e) {
         $this->_getSession()->addError($e->getMessage());
     } catch (Exception $e) {
         Mage::logException($e);
     }
     $this->_redirect('*/*/index');
 }
Example #11
0
 /**
  * Get API Token
  *
  * @return string
  */
 public function getApiToken()
 {
     if (!$this->_apiToken) {
         Mage::throwException(Mage::helper('iugu')->__('You need to configure API Token before performing requests.'));
     }
     return $this->_apiToken;
 }
Example #12
0
 protected function AutoSubmit()
 {
     $oOrder = $this->_getOrder();
     $oBilling = $oOrder->getBillingAddress();
     $szHtml = '';
     if ($oOrder) {
         try {
             $oPayment = new AllInOne();
             $oPayment->ServiceURL = $this->_getConfigData('test_mode') ? 'http://payment-stage.allpay.com.tw/Cashier/AioCheckOut' : 'https://payment.allpay.com.tw/Cashier/AioCheckOut';
             $oPayment->HashKey = $this->_getConfigData('hash_key');
             $oPayment->HashIV = $this->_getConfigData('hash_iv');
             $oPayment->MerchantID = $this->_getConfigData('merchant_id');
             $oPayment->Send['ReturnURL'] = Mage::getUrl('alipay/processing/response');
             $oPayment->Send['ClientBackURL'] = Mage::getUrl('');
             $oPayment->Send['OrderResultURL'] = Mage::getUrl('alipay/processing/result');
             $oPayment->Send['MerchantTradeNo'] = ($this->_getConfigData('test_mode') ? $this->_getConfigData('test_order_prefix') : '') . $oOrder->getIncrementId();
             $oPayment->Send['MerchantTradeDate'] = date('Y/m/d H:i:s');
             $oPayment->Send['TotalAmount'] = (int) $oOrder->getGrandTotal();
             $oPayment->Send['TradeDesc'] = "AllPay_Magento_Module";
             $oPayment->Send['ChoosePayment'] = PaymentMethod::Alipay;
             $oPayment->Send['Remark'] = '';
             $oPayment->Send['ChooseSubPayment'] = PaymentMethodItem::None;
             $oPayment->Send['NeedExtraPaidInfo'] = ExtraPaymentInfo::No;
             $oPayment->Send['DeviceSource'] = DeviceType::PC;
             array_push($oPayment->Send['Items'], array('Name' => Mage::helper('alipay')->__('Commodity Group'), 'Price' => (int) $oOrder->getGrandTotal(), 'Currency' => Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol(), 'Quantity' => 1, 'URL' => ''));
             $oPayment->SendExtend['Email'] = $oBilling->getEmail();
             $oPayment->SendExtend['PhoneNo'] = $oBilling->getTelephone();
             $oPayment->SendExtend['UserName'] = $oBilling->getName();
             $szHtml = $oPayment->CheckOutString();
         } catch (Exception $e) {
             Mage::throwException($e->getMessage());
         }
     }
     return $szHtml;
 }
Example #13
0
 /**
  * @return Bronto_Common_Model_System_Config_Backend_Token
  */
 protected function _beforeSave()
 {
     $commonHelper = Mage::helper('bronto_common');
     $value = $this->getValue();
     if (!empty($value)) {
         if ($commonHelper->validApiToken($value) === false) {
             // reset the verified status
             Mage::helper('bronto_verify/apitoken')->setStatus(Mage::helper('bronto_verify/apitoken')->getPath('token_status'), '2', $this->getScope(), $this->getScopeId());
             Mage::throwException($commonHelper->__('The Bronto API Token you have entered appears to be invalid.'));
         }
         // reset the verified status
         Mage::helper('bronto_verify/apitoken')->setStatus(Mage::helper('bronto_verify/apitoken')->getPath('token_status'), '1', $this->getScope(), $this->getScopeId());
         // Enable Common Module
         Mage::getModel('core/config_data')->load(Bronto_Common_Helper_Data::XML_PATH_ENABLED, 'path')->setValue(1)->setPath(Bronto_Common_Helper_Data::XML_PATH_ENABLED)->setScope($this->getScope())->setScopeId($this->getScopeId())->save();
         //  API key is new and doesn't match existing API key
         $currentApiKey = $commonHelper->getApiToken();
         if (!empty($currentApiKey) && $currentApiKey !== $value) {
             Mage::getSingleton('adminhtml/session')->addNotice($commonHelper->__('You have changed your Bronto API Token so all Bronto modules have been disabled for this configuration scope.' . '<br />Please proceed to each module and reconfigure all available options to avoid undesired behavior.'));
             $this->_disableAndUnlink();
         }
     } else {
         Mage::getSingleton('adminhtml/session')->addNotice($commonHelper->__('You have removed your Bronto API Token so all Bronto modules have been disabled for this configuration scope.'));
         // reset the verified status
         Mage::helper('bronto_verify/apitoken')->setStatus(Mage::helper('bronto_verify/apitoken')->getPath('token_status'), '0', $this->getScope(), $this->getScopeId());
         $this->_disableAndUnlink(true);
     }
     return parent::_beforeSave();
 }
Example #14
0
 public function saveAction()
 {
     $session = $this->_getSession();
     if ($data = $this->getRequest()->getPost()) {
         try {
             $data['is_shorten'] = empty($data['is_shorten']) ? 0 : $data['is_shorten'];
             $data['is_published'] = empty($data['is_published']) ? 1 : $data['is_published'];
             if ($data['is_shorten'] == 1 && empty($data['shorten_article'])) {
                 Mage::throwException('Please write a shorten article or disable it');
             }
             $model = Mage::getModel('yanws/news');
             $model->setData($data)->setId($this->getRequest()->getParam('id'));
             $model->save();
             $session->addSuccess($this->__('News was saved successfully'));
             $session->setFormData(false);
             $this->_redirect('*/*/');
         } catch (Exception $e) {
             $session->addError($e->getMessage());
             $session->setFormData($data);
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
         }
         return;
     }
     $session->addError($this->__('Unable to find item to save'));
     $this->_redirect('*/*/');
 }
 /**
  * Cron settings after save
  *
  * @return Mage_Adminhtml_Model_System_Config_Backend_Log_Cron
  */
 protected function _afterSave()
 {
     $enabled = $this->getData('groups/cron/fields/enabled/value');
     $time = $this->getData('groups/cron/fields/time/value');
     $frequncy = $this->getData('groups/cron/fields/frequency/value');
     $frequencyDaily = Mage_Adminhtml_Model_System_Config_Source_Cron_Frequency::CRON_DAILY;
     $frequencyWeekly = Mage_Adminhtml_Model_System_Config_Source_Cron_Frequency::CRON_WEEKLY;
     $frequencyMonthly = Mage_Adminhtml_Model_System_Config_Source_Cron_Frequency::CRON_MONTHLY;
     if ($enabled) {
         $cronDayOfWeek = date('N');
         $cronExprArray = array(intval($time[1]), intval($time[0]), $frequncy == $frequencyMonthly ? '1' : '*', '*', $frequncy == $frequencyWeekly ? '1' : '*');
         $cronExprString = join(' ', $cronExprArray);
     } else {
         $cronExprString = '';
     }
     try {
         Mage::getModel('core/config_data')->load(self::CRON_STRING_PATH, 'path')->setValue($cronExprString)->setPath(self::CRON_STRING_PATH)->save();
         Mage::getModel('core/config_data')->load(self::CRON_MODEL_PATH, 'path')->setValue((string) Mage::getConfig()->getNode(self::CRON_MODEL_PATH))->setPath(self::CRON_MODEL_PATH)->save();
         if (!empty($cronExprString)) {
             Mage::getSingleton('adminhtml/session')->addNotice(Mage::helper('maverick_crawler')->__('Cron Expression Set To [%s]', $cronExprString));
         }
     } catch (Exception $e) {
         Mage::throwException(Mage::helper('maverick_crawler')->__('Unable to save the cron expression.'));
     }
 }
Example #16
0
 public function scheduledUpdateCurrencyRates($schedule)
 {
     $importWarnings = array();
     if (!Mage::getStoreConfig(self::IMPORT_ENABLE) || !Mage::getStoreConfig(self::CRON_STRING_PATH)) {
         return;
     }
     $service = Mage::getStoreConfig(self::IMPORT_SERVICE);
     if (!$service) {
         $importWarnings[] = Mage::helper('directory')->__('FATAL ERROR:') . ' ' . Mage::helper('directory')->__('Invalid Import Service specified.');
     }
     try {
         $importModel = Mage::getModel(Mage::getConfig()->getNode('global/currency/import/services/' . $service . '/model')->asArray());
     } catch (Exception $e) {
         $importWarnings[] = Mage::helper('directory')->__('FATAL ERROR:') . ' ' . Mage::throwException(Mage::helper('directory')->__('Unable to initialize the import model.'));
     }
     $rates = $importModel->fetchRates();
     $errors = $importModel->getMessages();
     if (sizeof($errors) > 0) {
         foreach ($errors as $error) {
             $importWarnings[] = Mage::helper('directory')->__('WARNING:') . ' ' . $error;
         }
     }
     if (sizeof($importWarnings) == 0) {
         Mage::getModel('directory/currency')->saveRates($rates);
     } else {
         $translate = Mage::getSingleton('core/translate');
         /* @var $translate Mage_Core_Model_Translate */
         $translate->setTranslateInline(false);
         /* @var $mailTemplate Mage_Core_Model_Email_Template */
         $mailTemplate = Mage::getModel('core/email_template');
         $mailTemplate->setDesignConfig(array('area' => 'frontend'))->sendTransactional(Mage::getStoreConfig(self::XML_PATH_ERROR_TEMPLATE), Mage::getStoreConfig(self::XML_PATH_ERROR_IDENTITY), Mage::getStoreConfig(self::XML_PATH_ERROR_RECIPIENT), null, array('warnings' => join("\n", $importWarnings)));
         $translate->setTranslateInline(true);
     }
 }
 public function fetchRatesAction()
 {
     try {
         $service = $this->getRequest()->getParam('rate_services');
         $this->_getSession()->setCurrencyRateService($service);
         if (!$service) {
             throw new Exception(Mage::helper('adminhtml')->__('Invalid Import Service Specified'));
         }
         try {
             $importModel = Mage::getModel(Mage::getConfig()->getNode('global/currency/import/services/' . $service . '/model')->asArray());
         } catch (Exception $e) {
             Mage::throwException(Mage::helper('adminhtml')->__('Unable to initialize import model'));
         }
         $rates = $importModel->fetchRates();
         $errors = $importModel->getMessages();
         if (sizeof($errors) > 0) {
             foreach ($errors as $error) {
                 Mage::getSingleton('adminhtml/session')->addWarning($error);
             }
             Mage::getSingleton('adminhtml/session')->addWarning(Mage::helper('adminhtml')->__('All possible rates were fetched, please click on "Save" to apply'));
         } else {
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('All rates were fetched, please click on "Save" to apply'));
         }
         Mage::getSingleton('adminhtml/session')->setRates($rates);
     } catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
     }
     $this->_redirect('*/*/');
 }
Example #18
0
    /**
     * Run script
     *
     */
    public function run()
    {
    	try {
    		$data = array();
            $data['schedule_id']    = uniqid(rand(), true);
            $data['mage_cron']      = false;
            $data['verbose']        = $this->getArg('verbose') ? true : false;
            $data['missing_img']    = $this->getArg('missing_img') ? true : false;
            $data['store_code']     = $this->getArg('store_code') ? $this->getArg('store_code') : Mage_Core_Model_App::DISTRO_STORE_CODE;
            $data['batch_mode']     = $this->getArg('batch_mode') ? true : false;
            $data['test_mode']      = $this->getArg('test_mode') ? true : false;
            $data['test_sku']       = $this->getArg('test_sku') ? $this->getArg('test_sku') : false;
            $data['test_limit']     = $this->getArg('test_limit') ? $this->getArg('test_limit') : 0;
            $data['test_offset']    = $this->getArg('test_offset') ? $this->getArg('test_offset') : 0;

	        @Mage::app('admin')->setUseSessionInUrl(false);
	        
	        set_time_limit(0);
			/* Setting memory limit depends on the number of products exported.*/
			// ini_set('memory_limit','600M');
			error_reporting(E_ALL);

            try {
                $store_id = Mage::app()->getStore($data['store_code'])->getStoreId();
            } catch (Exception $e) {
                Mage::throwException(sprintf('Store with code \'%s\' doesn\'t exists.', $data['store_code']));
            }

			$Generator = Mage::getSingleton('googlebasefeedgenerator/tools')->addData($data)->getGenerator($store_id);
            $Generator->run();

    	} catch (Exception $e) {
    		echo $e->getMessage() . PHP_EOL;
    	}
    }
 /**
  * New subscription action
  */
 public function newAction()
 {
     if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
         $session = Mage::getSingleton('core/session');
         $customerSession = Mage::getSingleton('customer/session');
         $email = (string) $this->getRequest()->getPost('email');
         try {
             if (!Zend_Validate::is($email, 'EmailAddress')) {
                 Mage::throwException($this->__('Please enter a valid email address.'));
             }
             if (Mage::getStoreConfig(Mage_Newsletter_Model_Subscriber::XML_PATH_ALLOW_GUEST_SUBSCRIBE_FLAG) != 1 && !$customerSession->isLoggedIn()) {
                 Mage::throwException($this->__('Sorry, but administrator denied subscription for guests. Please <a href="%s">register</a>.', Mage::helper('customer')->getRegisterUrl()));
             }
             $ownerId = Mage::getModel('customer/customer')->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($email)->getId();
             if ($ownerId !== null && $ownerId != $customerSession->getId()) {
                 Mage::throwException($this->__('This email address is already assigned to another user.'));
             }
             $status = Mage::getModel('newsletter/subscriber')->subscribe($email);
             if ($status == Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE) {
                 $session->addSuccess($this->__('Confirmation request has been sent.'));
             } else {
                 $session->addSuccess($this->__('Thank you for your subscription.'));
             }
         } catch (Mage_Core_Exception $e) {
             $session->addException($e, $this->__('There was a problem with the subscription: %s', $e->getMessage()));
         } catch (Exception $e) {
             $session->addException($e, $this->__('There was a problem with the subscription.'));
         }
     }
     $this->_redirectReferer();
 }
 /**
  * Retrieve stockreminder object
  * @param int $stockreminderId
  * @return Edge_StockReminder_Model_StockReminder|bool
  */
 protected function _getStockreminder($stockreminderId = null)
 {
     $stockreminder = Mage::registry('stockreminder');
     if ($stockreminder) {
         return $stockreminder;
     }
     try {
         if (!$stockreminderId) {
             $stockreminderId = $this->getRequest()->getParam('stockreminder_id');
         }
         $customerId = Mage::getSingleton('customer/session')->getCustomerId();
         /* @var Edge_StockReminder_Model_StockReminder $stockreminder */
         $stockreminder = Mage::getModel('stockreminder/stockreminder');
         if ($stockreminderId) {
             $stockreminder->load($stockreminderId);
         } else {
             $stockreminder->loadByCustomer($customerId, true);
         }
         if (!$stockreminder->getId() || $stockreminder->getCustomerId() != $customerId) {
             $stockreminder = null;
             Mage::throwException(Mage::helper('stockreminder')->__("Requested stockreminder doesn't exist"));
         }
         Mage::register('stockreminder', $stockreminder);
     } catch (Mage_Core_Exception $e) {
         Mage::getSingleton('stockreminder/session')->addError($e->getMessage());
         return false;
     } catch (Exception $e) {
         Mage::getSingleton('stockreminder/session')->addException($e, Mage::helper('stockreminder')->__('Stockreminder could not be created.'));
         return false;
     }
     return $stockreminder;
 }
Example #21
0
 /**
  * Prepare form
  *
  * @deprecated will delete in the next version
  * @throws Mage_Core_Exception
  * @return Mage_XmlConnect_Block_Adminhtml_Mobile_Widget_Form
  */
 protected function _prepareForm()
 {
     $form = new Varien_Data_Form();
     $fieldset = $form->addFieldset('field_logo', array());
     $this->_addElementTypes($fieldset);
     $this->addImage($fieldset, 'conf[native][navigationBar][icon]', $this->__('Logo in Header'), $this->__('Recommended size %spx x %spx.', 35, 35), $this->_getDesignPreviewImageUrl('conf/native/navigationBar/icon'), true);
     $deviceType = Mage::helper('xmlconnect')->getDeviceType();
     switch ($deviceType) {
         case Mage_XmlConnect_Helper_Data::DEVICE_TYPE_IPHONE:
             $this->addImage($fieldset, 'conf[native][body][bannerImage]', $this->__('Banner on Home Screen'), $this->__('Recommended size %spx x %spx.', 320, 230) . $this->__(' Note: Image size affects the performance of your app.') . $this->__('Keep your image size below %s KB for optimal performance.', 50), $this->_getDesignPreviewImageUrl('conf/native/body/bannerImage'), true);
             $this->addImage($fieldset, 'conf[native][body][backgroundImage]', $this->__('App Background'), $this->__('Recommended size %spx x %spx.', 320, 367) . $this->__('Note: Image size affects the performance of your app.') . $this->__('Keep your image size below %s KB for optimal performance.', 75), $this->_getDesignPreviewImageUrl('conf/native/body/backgroundImage'), true);
             break;
         case Mage_XmlConnect_Helper_Data::DEVICE_TYPE_IPAD:
             $this->addImage($fieldset, 'conf[native][body][bannerIpadLandscapeImage]', $this->__('Banner on Home Screen (landscape mode)'), $this->__('Recommended size %spx x %spx.', 1024, 344) . $this->__('Note: Image size affects the performance of your app.'), $this->_getDesignPreviewImageUrl('conf/native/body/bannerIpadLandscapeImage'), true);
             $this->addImage($fieldset, 'conf[native][body][bannerIpadImage]', $this->__('Banner on Home Screen (portrait mode)'), $this->__('Recommended size %spx x %spx.', 768, 294) . $this->__('Note: Image size affects the performance of your app.'), $this->_getDesignPreviewImageUrl('conf/native/body/bannerIpadImage'), true);
             $this->addImage($fieldset, 'conf[native][body][backgroundIpadLandscapeImage]', $this->__('App Background (landscape mode)'), $this->__('Recommended size %spx x %spx.', 1024, 704) . $this->__('Note: Image size affects the performance of your app.'), $this->_getDesignPreviewImageUrl('conf/native/body/backgroundIpadLandscapeImage'), true);
             $this->addImage($fieldset, 'conf[native][body][backgroundIpadPortraitImage]', $this->__('App Background (portrait mode)'), $this->__('Recommended size %spx x %spx.', 768, 960) . $this->__('Note: Image size affects the performance of your app.'), $this->_getDesignPreviewImageUrl('conf/native/body/backgroundIpadPortraitImage'), true);
             break;
         case Mage_XmlConnect_Helper_Data::DEVICE_TYPE_ANDROID:
             $this->addImage($fieldset, 'conf[native][body][bannerAndroidImage]', $this->__('Banner on Home Screen'), $this->__('Recommended size %spx x %spx.', 320, 258) . $this->__('Note: Image size affects the performance of your app.') . $this->__('Keep your image size below %s KB for optimal performance.', 50), $this->_getDesignPreviewImageUrl('conf/native/body/bannerAndroidImage'), true);
             break;
         default:
             Mage::throwException($this->__('Device doesn\'t recognized: "%s". Unable to load a helper.', $deviceType));
             break;
     }
     $form->setValues(Mage::helper('xmlconnect')->getApplication()->getFormData());
     $this->setForm($form);
     return parent::_prepareForm();
 }
Example #22
0
 /**
  * Add subscribers to queue
  *
  * @param Mage_Newsletter_Model_Queue $queue
  * @param array $subscriberIds
  */
 public function addSubscribersToQueue(Mage_Newsletter_Model_Queue $queue, array $subscriberIds)
 {
     if (count($subscriberIds) == 0) {
         Mage::throwException(Mage::helper('newsletter')->__('No subscribers selected.'));
     }
     if (!$queue->getId() && $queue->getQueueStatus() != Mage_Newsletter_Model_Queue::STATUS_NEVER) {
         Mage::throwException(Mage::helper('newsletter')->__('Invalid queue selected.'));
     }
     $adapter = $this->_getWriteAdapter();
     $select = $adapter->select();
     $select->from($this->getTable('newsletter/queue_link'), 'subscriber_id')->where('queue_id = ?', $queue->getId())->where('subscriber_id in (?)', $subscriberIds);
     $usedIds = $adapter->fetchCol($select);
     $adapter->beginTransaction();
     try {
         foreach ($subscriberIds as $subscriberId) {
             if (in_array($subscriberId, $usedIds)) {
                 continue;
             }
             $data = array();
             $data['queue_id'] = $queue->getId();
             $data['subscriber_id'] = $subscriberId;
             $adapter->insert($this->getTable('newsletter/queue_link'), $data);
         }
         $adapter->commit();
     } catch (Exception $e) {
         $adapter->rollBack();
     }
 }
Example #23
0
 public function getStandardCheckoutFormFields()
 {
     $order = $this->getOrder();
     if (!$order instanceof Mage_Sales_Model_Order) {
         Mage::throwException($this->_getHelper()->__('Cannot retrieve order object'));
     }
     $billingAddress = $order->getBillingAddress();
     $shippingAddress = $order->getShippingAddress();
     $streets = $billingAddress->getStreet();
     $street = isset($streets[0]) && $streets[0] != '' ? $streets[0] : (isset($streets[1]) && $streets[1] != '' ? $streets[1] : '');
     if ($this->getConfig()->getDescription()) {
         $transDescription = $this->getConfig()->getDescription();
     } else {
         $transDescription = Mage::helper('Avenues')->__('Order #%s', $order->getRealOrderId());
     }
     if ($order->getCustomerEmail()) {
         $email = $order->getCustomerEmail();
     } elseif ($billingAddress->getEmail()) {
         $email = $billingAddress->getEmail();
     } else {
         $email = '';
     }
     $fields = array('Merchant_Id' => $this->getConfig()->getAccountId(), 'WorkingKey' => $this->getConfigData('workingkey'), 'product_price' => $order->getBaseGrandTotal(), 'Redirect_Url' => Mage::getUrl('Avenues/standard/success', array('_secure' => true)), 'product_name' => $transDescription, 'language' => $this->getConfig()->getLanguage(), 'billing_cust_name' => $billingAddress->getFirstname() . ' ' . $billingAddress->getLastname(), 'billing_last_name' => $billingAddress->getLastname(), 'billing_cust_address' => $street, 'billing_cust_city' => $billingAddress->getCity(), 'billing_cust_state' => $billingAddress->getRegionCode(), 'billing_zip_code' => $billingAddress->getPostcode(), 'billing_cust_country' => $billingAddress->getCountryModel()->getName(), 'billing_cust_tel' => $billingAddress->getTelephone(), 'billing_cust_email' => $email, 'delivery_cust_name' => $shippingAddress->getFirstname() . ' ' . $shippingAddress->getLastname(), 'delivery_last_name' => $shippingAddress->getLastname(), 'delivery_cust_address' => $shippingAddress->getStreetFull(), 'delivery_cust_city' => $shippingAddress->getCity(), 'delivery_cust_state' => $shippingAddress->getRegionCode(), 'delivery_zip_code' => $shippingAddress->getPostcode(), 'delivery_cust_country' => $shippingAddress->getCountryModel()->getName(), 'delivery_cust_tel' => $shippingAddress->getTelephone(), 'cb_url' => $this->getNotificationURL(), 'cb_type' => 'P', 'decline_url' => $this->getFailureURL(), 'cs1' => $order->getRealOrderId(), 'Checksum' => getCheckSum($this->getConfig()->getAccountId(), $order->getBaseGrandTotal(), $order->getRealOrderId(), Mage::getUrl('Avenues/standard/success', array('_secure' => true)), $this->getConfigData('workingkey')));
     if ($this->getConfig()->getDebug()) {
         $debug = Mage::getModel('Avenues/api_debug')->setRequestBody($this->getAvenuesUrl() . "\n" . print_r($fields, 1))->save();
         $fields['cs2'] = $debug->getId();
     }
     return $fields;
 }
Example #24
0
 public function toOptionArray($exclude = true)
 {
     $result = array();
     $result['Magento'] = array('label' => 'Magento');
     $path = Mage::getModuleDir('', 'Mirasvit_SearchIndex') . DS . 'Model' . DS . 'Index';
     $io = new Varien_Io_File();
     $io->open();
     $io->cd($path);
     foreach ($io->ls(Varien_Io_File::GREP_DIRS) as $space) {
         $io->cd($space['id']);
         foreach ($io->ls(Varien_Io_File::GREP_DIRS) as $module) {
             $io->cd($module['id']);
             foreach ($io->ls(Varien_Io_File::GREP_DIRS) as $entity) {
                 if ($io->fileExists($entity['id'] . DS . 'Index.php', true)) {
                     $indexCode = $space['text'] . '_' . $module['text'] . '_' . $entity['text'];
                     $index = Mage::helper('searchindex/index')->getIndexModel($indexCode);
                     if (is_object($index)) {
                         if ($index->canUse()) {
                             if (!isset($result[$index->getBaseGroup()])) {
                                 $result[$index->getBaseGroup()] = array('label' => $index->getBaseGroup(), 'value' => array());
                             }
                             $result[$index->getBaseGroup()]['value'][] = array('value' => $index->getCode(), 'label' => $index->getBaseTitle());
                         }
                     } else {
                         Mage::throwException('Wrong model for index ' . $indexCode);
                     }
                 }
             }
         }
     }
     return $result;
 }
Example #25
0
 /**
  * Retrieve Product Type Code
  *
  * @return string
  */
 public function getTypeId()
 {
     if (is_null($this->_typeId)) {
         Mage::throwException(Mage::helper('catalog')->__('A product type is not defined for the indexer.'));
     }
     return $this->_typeId;
 }
Example #26
0
    /**
     * Send checkout data to google
     *
     * @return Mage_GoogleCheckout_Model_Api_Xml_Checkout
     */
    public function checkout()
    {
        $quote = $this->getQuote();
        if (!$quote instanceof Mage_Sales_Model_Quote) {
            Mage::throwException('Invalid quote');
        }
        $xmlns = self::CHECKOUT_SHOPPING_CART_XMLNS;
        $xml = <<<EOT
<checkout-shopping-cart xmlns="{$xmlns}">
    <shopping-cart>
{$this->_getItemsXml()}
{$this->_getMerchantPrivateDataXml()}
{$this->_getCartExpirationXml()}
    </shopping-cart>
    <checkout-flow-support>
{$this->_getMerchantCheckoutFlowSupportXml()}
    </checkout-flow-support>
    <order-processing-support>
{$this->_getRequestInitialAuthDetailsXml()}
    </order-processing-support>
</checkout-shopping-cart>
EOT;
        $result = $this->_call($xml);
        $this->setRedirectUrl($result->{'redirect-url'});
        return $this;
    }
Example #27
0
 /**
  * Validate website code before object save
  *
  * @param Mage_Core_Model_Abstract $object
  * @return Mage_Core_Model_Resource_Website
  */
 protected function _beforeSave(Mage_Core_Model_Abstract $object)
 {
     if (!preg_match('/^[a-z]+[a-z0-9_]*$/', $object->getCode())) {
         Mage::throwException(Mage::helper('core')->__('Website code may only contain letters (a-z), numbers (0-9) or underscore(_), the first character must be a letter'));
     }
     return parent::_beforeSave($object);
 }
Example #28
0
 /**
  * Check store code before save
  *
  * @param Mage_Core_Model_Abstract $model
  * @return Mage_Core_Model_Resource_Store
  */
 protected function _beforeSave(Mage_Core_Model_Abstract $model)
 {
     if (!preg_match('/^[a-z]+[a-z0-9_]*$/', $model->getCode())) {
         Mage::throwException(Mage::helper('core')->__('The store code may contain only letters (a-z), numbers (0-9) or underscore(_), the first character must be a letter'));
     }
     return $this;
 }
 /**
  * Process page data before saving
  *
  * @param Mage_Core_Model_Abstract $object
  */
 protected function _beforeSave(Mage_Core_Model_Abstract $object)
 {
     /*
      * For two attributes which represent datetime data in DB
      * we should make converting such as:
      * If they are empty we need to convert them into DB
      * type NULL so in DB they will be empty and not some default value.
      */
     foreach (array('custom_theme_from', 'custom_theme_to') as $dataKey) {
         if (!$object->getData($dataKey)) {
             $object->setData($dataKey, new Zend_Db_Expr('NULL'));
         }
     }
     if (!$this->getIsUniquePageToStores($object)) {
         Mage::throwException(Mage::helper('cms')->__('Page URL Key for specified store already exist.'));
     }
     if ($this->isNumericPageIdentifier($object)) {
         Mage::throwException(Mage::helper('cms')->__('Page URL Key cannot consist only of numbers.'));
     }
     if (!$object->getId()) {
         $object->setCreationTime(Mage::getSingleton('core/date')->gmtDate());
     }
     $object->setUpdateTime(Mage::getSingleton('core/date')->gmtDate());
     return $this;
 }
Example #30
0
 /**
  * Performs the scan for associated products
  *
  * @return array
  */
 public function collect()
 {
     if (is_null($this->_recommendation)) {
         Mage::throwException('Product Recommendation is required for collecting recommended products');
     }
     Mage::dispatchEvent("bronto_product_before_collect", array('collect' => $this, 'recommendation' => $this->_recommendation));
     foreach ($this->_recommendation->getSources() as $source => $method) {
         if ($this->_recommendation->isProductRelated($source)) {
             if (empty($this->_hash)) {
                 Mage::helper('bronto_product')->writeInfo('originalHash cannot be empty for a product related source. Skipping');
                 continue;
             }
             foreach ($this->_hash as $productId => $product) {
                 if ($this->isReachedMax()) {
                     break;
                 }
                 $this->_invokeSource($source, $method, $product);
             }
         } else {
             $this->_invokeSource($source, $method);
         }
     }
     Mage::dispatchEvent("bronto_product_after_collect", array('collect' => $this, 'recommendation' => $this->_recommendation));
     return $this->_products;
 }