public function loaddataorderspaymentAction()
 {
     $this->_helper->viewRenderer->setNoRender();
     $this->_helper->getHelper("layout")->disableLayout();
     $aInputFilters = array("*" => array(new Zend_Filter_StringTrim()));
     $aInputValidators = array("num_row_per_page" => array(new Zend_Validate_Digits()), "curr_page" => array(new Zend_Validate_Digits()), "sort_column" => array(new AppCms2_Validate_SpecialAlpha()), "sort_method" => array(new Zend_Validate_Alpha()));
     $oInput = new Zend_Filter_Input($aInputFilters, $aInputValidators, $_POST);
     $nNumRowPerPage = $oInput->getUnescaped("num_row_per_page");
     $nCurrPage = $oInput->getUnescaped("curr_page");
     $sSortColumn = $oInput->getUnescaped("sort_column");
     $sSortMethod = $oInput->getUnescaped("sort_method");
     $aFilter = array();
     foreach ($aFilter as $sKey => $sValue) {
         if (!isset($sValue)) {
             unset($aFilter[$sKey]);
         }
     }
     $oModelVOrderPaymentHistory = new User_Model_VOrderPaymentHistory();
     $oRowset = $oModelVOrderPaymentHistory->getUserPayments($aFilter, $nNumRowPerPage, ($nCurrPage - 1) * $nNumRowPerPage, $sSortColumn . " " . $sSortMethod);
     $nNumRows = $oModelVOrderPaymentHistory->getUserPayments($aFilter)->count();
     $aJson = array("rowset" => $oRowset->toArray(), "num_rows" => $nNumRows);
     header("Content-type: application/json");
     echo Zend_Json::encode($aJson);
     exit;
 }
 /**
  * Save changes to an existing panel. This can be expanded to allow adding of new Panels in the future.
  *
  * @return void
  */
 protected function _savePanel()
 {
     // First of all we need to validate and sanitise the input from the form
     $urlFilter = new Zend_Filter();
     $urlFilter->addFilter(new Zend_Filter_StringTrim());
     $urlFilter->addFilter(new Zend_Filter_StringTrim('/'));
     $requiredText = new Zend_Validate();
     $requiredText->addValidator(new Zend_Validate_NotEmpty());
     $filters = array('id' => 'Digits');
     $validators = array('id' => array('allowEmpty' => true), 'content' => array('allowEmpty' => true));
     $input = new Zend_Filter_Input($filters, $validators, $_POST);
     if ($input->isValid()) {
         // Data is all valid, formatted and sanitized so we can save it in the database
         $panel = new Datasource_Cms_Panels();
         if (!$input->id) {
             // This is a new panel so we need to create a new ID
             // NOT IMPLEMENTED - YET
         } else {
             $panel->saveChanges($input->id, $input->getUnescaped('content'));
             $panelID = $input->id;
         }
         // Changes saved - so send them back with a nice success message
         $this->_helper->getHelper('FlashMessenger')->addMessage(array('saved' => true));
         $this->_helper->getHelper('Redirector')->goToUrl('/cms-admin/panels/edit?id=' . $panelID);
     } else {
         // Invalid data in form
         /*
         print_r($_POST);
         print_r($input->getErrors());
         print_r($input->getInvalid());
         */
     }
 }
Exemple #3
0
 /**
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  */
 public function executeInternal()
 {
     if ($this->getRequest()->getPostValue()) {
         try {
             /** @var \Magento\CatalogRule\Model\Rule $model */
             $model = $this->_objectManager->create('Magento\\CatalogRule\\Model\\Rule');
             $this->_eventManager->dispatch('adminhtml_controller_catalogrule_prepare_save', ['request' => $this->getRequest()]);
             $data = $this->getRequest()->getPostValue();
             $inputFilter = new \Zend_Filter_Input(['from_date' => $this->_dateFilter, 'to_date' => $this->_dateFilter], [], $data);
             $data = $inputFilter->getUnescaped();
             $id = $this->getRequest()->getParam('rule_id');
             if ($id) {
                 $model->load($id);
                 if ($id != $model->getId()) {
                     throw new LocalizedException(__('Wrong rule specified.'));
                 }
             }
             $validateResult = $model->validateData(new \Magento\Framework\DataObject($data));
             if ($validateResult !== true) {
                 foreach ($validateResult as $errorMessage) {
                     $this->messageManager->addError($errorMessage);
                 }
                 $this->_getSession()->setPageData($data);
                 $this->_redirect('catalog_rule/*/edit', ['id' => $model->getId()]);
                 return;
             }
             $data['conditions'] = $data['rule']['conditions'];
             unset($data['rule']);
             $model->loadPost($data);
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setPageData($model->getData());
             $model->save();
             $this->messageManager->addSuccess(__('You saved the rule.'));
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setPageData(false);
             if ($this->getRequest()->getParam('auto_apply')) {
                 $this->getRequest()->setParam('rule_id', $model->getId());
                 $this->_forward('applyRules');
             } else {
                 if ($model->isRuleBehaviorChanged()) {
                     $this->_objectManager->create('Magento\\CatalogRule\\Model\\Flag')->loadSelf()->setState(1)->save();
                 }
                 if ($this->getRequest()->getParam('back')) {
                     $this->_redirect('catalog_rule/*/edit', ['id' => $model->getId()]);
                     return;
                 }
                 $this->_redirect('catalog_rule/*/');
             }
             return;
         } catch (LocalizedException $e) {
             $this->messageManager->addError($e->getMessage());
         } catch (\Exception $e) {
             $this->messageManager->addError(__('Something went wrong while saving the rule data. Please review the error log.'));
             $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e);
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setPageData($data);
             $this->_redirect('catalog_rule/*/edit', ['id' => $this->getRequest()->getParam('rule_id')]);
             return;
         }
     }
     $this->_redirect('catalog_rule/*/');
 }
Exemple #4
0
 /**
  * Before model save
  * @param  \Magefan\Blog\Model\Post $model
  * @param  \Magento\Framework\App\Request\Http $request
  * @return void
  */
 protected function _beforeSave($model, $request)
 {
     /* Prepare dates */
     $dateFilter = $this->_objectManager->create('Magento\\Framework\\Stdlib\\DateTime\\Filter\\Date');
     $data = $model->getData();
     $filterRules = [];
     foreach (['publish_time', 'custom_theme_from', 'custom_theme_to'] as $dateField) {
         if (!empty($data[$dateField])) {
             $filterRules[$dateField] = $dateFilter;
         }
     }
     $inputFilter = new \Zend_Filter_Input($filterRules, [], $data);
     $data = $inputFilter->getUnescaped();
     $model->setData($data);
     /* Prepare author */
     if (!$model->getAuthorId()) {
         $authSession = $this->_objectManager->get('Magento\\Backend\\Model\\Auth\\Session');
         $model->setAuthorId($authSession->getUser()->getId());
     }
     /* Prepare relative links */
     $data = $request->getPost('data');
     $links = isset($data['links']) ? $data['links'] : null;
     if ($links && is_array($links)) {
         foreach (['post', 'product'] as $linkType) {
             if (!empty($links[$linkType]) && is_array($links[$linkType])) {
                 $linksData = [];
                 foreach ($links[$linkType] as $item) {
                     $linksData[$item['id']] = ['position' => $item['position']];
                 }
                 $links[$linkType] = $linksData;
             }
         }
         $model->setData('links', $links);
     }
     /* Prepare images */
     $data = $model->getData();
     foreach (['featured_img', 'og_img'] as $key) {
         if (isset($data[$key]) && is_array($data[$key])) {
             if (!empty($data[$key]['delete'])) {
                 $model->setData($key, null);
             } else {
                 if (isset($data[$key][0]['name']) && isset($data[$key][0]['tmp_name'])) {
                     $image = $data[$key][0]['name'];
                     $model->setData($key, Post::BASE_MEDIA_PATH . DIRECTORY_SEPARATOR . $image);
                     $imageUploader = $this->_objectManager->get('Magefan\\Blog\\ImageUpload');
                     $imageUploader->moveFileFromTmp($image);
                 } else {
                     if (isset($data[$key][0]['name'])) {
                         $model->setData($key, $data[$key][0]['name']);
                     }
                 }
             }
         } else {
             $model->setData($key, null);
         }
     }
 }
Exemple #5
0
 /**
  * @return void
  */
 public function execute()
 {
     if ($this->getRequest()->getPost()) {
         try {
             $model = $this->_objectManager->create('Magento\\CatalogRule\\Model\\Rule');
             $this->_eventManager->dispatch('adminhtml_controller_catalogrule_prepare_save', array('request' => $this->getRequest()));
             $data = $this->getRequest()->getPost();
             $inputFilter = new \Zend_Filter_Input(array('from_date' => $this->_dateFilter, 'to_date' => $this->_dateFilter), array(), $data);
             $data = $inputFilter->getUnescaped();
             $id = $this->getRequest()->getParam('rule_id');
             if ($id) {
                 $model->load($id);
                 if ($id != $model->getId()) {
                     throw new Exception(__('Wrong rule specified.'));
                 }
             }
             $validateResult = $model->validateData(new \Magento\Framework\Object($data));
             if ($validateResult !== true) {
                 foreach ($validateResult as $errorMessage) {
                     $this->messageManager->addError($errorMessage);
                 }
                 $this->_getSession()->setPageData($data);
                 $this->_redirect('catalog_rule/*/edit', array('id' => $model->getId()));
                 return;
             }
             $data['conditions'] = $data['rule']['conditions'];
             unset($data['rule']);
             $model->loadPost($data);
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setPageData($model->getData());
             $model->save();
             $this->messageManager->addSuccess(__('The rule has been saved.'));
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setPageData(false);
             if ($this->getRequest()->getParam('auto_apply')) {
                 $this->getRequest()->setParam('rule_id', $model->getId());
                 $this->_forward('applyRules');
             } else {
                 $this->_objectManager->create('Magento\\CatalogRule\\Model\\Flag')->loadSelf()->setState(1)->save();
                 if ($this->getRequest()->getParam('back')) {
                     $this->_redirect('catalog_rule/*/edit', array('id' => $model->getId()));
                     return;
                 }
                 $this->_redirect('catalog_rule/*/');
             }
             return;
         } catch (Exception $e) {
             $this->messageManager->addError($e->getMessage());
         } catch (\Exception $e) {
             $this->messageManager->addError(__('An error occurred while saving the rule data. Please review the log and try again.'));
             $this->_objectManager->get('Magento\\Framework\\Logger')->logException($e);
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setPageData($data);
             $this->_redirect('catalog_rule/*/edit', array('id' => $this->getRequest()->getParam('rule_id')));
             return;
         }
     }
     $this->_redirect('catalog_rule/*/');
 }
Exemple #6
0
 /**
  * filter dates
  *
  * @param array $data
  * @return array
  */
 public function filterData($data)
 {
     $inputFilter = new \Zend_Filter_Input(['dob' => $this->dateFilter], [], $data);
     $data = $inputFilter->getUnescaped();
     if (isset($data['awards'])) {
         if (is_array($data['awards'])) {
             $data['awards'] = implode(',', $data['awards']);
         }
     }
     return $data;
 }
Exemple #7
0
 /**
  * Before model save
  * @param  \Magefan\Blog\Model\Category $model
  * @param  \Magento\Framework\App\Request\Http $request
  * @return void
  */
 protected function _beforeSave($model, $request)
 {
     /* Prepare dates */
     $dateFilter = $this->_objectManager->create('Magento\\Framework\\Stdlib\\DateTime\\Filter\\Date');
     $data = $model->getData();
     $filterRules = [];
     foreach (['custom_theme_from', 'custom_theme_to'] as $dateField) {
         if (!empty($data[$dateField])) {
             $filterRules[$dateField] = $dateFilter;
         }
     }
     $inputFilter = new \Zend_Filter_Input($filterRules, [], $data);
     $data = $inputFilter->getUnescaped();
     $model->setData($data);
 }
Exemple #8
0
    /**
     * Generate Coupons action
     *
     * @return void
     */
    public function executeInternal()
    {
        if (!$this->getRequest()->isAjax()) {
            $this->_forward('noroute');
            return;
        }
        $result = [];
        $this->_initRule();

        /** @var $rule \Magento\SalesRule\Model\Rule */
        $rule = $this->_coreRegistry->registry('current_promo_quote_rule');

        if (!$rule->getId()) {
            $result['error'] = __('Rule is not defined');
        } else {
            try {
                $data = $this->getRequest()->getParams();
                if (!empty($data['to_date'])) {
                    $inputFilter = new \Zend_Filter_Input(['to_date' => $this->_dateFilter], [], $data);
                    $data = $inputFilter->getUnescaped();
                }

                /** @var $generator \Magento\SalesRule\Model\Coupon\Massgenerator */
                $generator = $this->_objectManager->get('Magento\SalesRule\Model\Coupon\Massgenerator');
                if (!$generator->validateData($data)) {
                    $result['error'] = __('Invalid data provided');
                } else {
                    $generator->setData($data);
                    $generator->generatePool();
                    $generated = $generator->getGeneratedCount();
                    $this->messageManager->addSuccess(__('%1 coupon(s) have been generated.', $generated));
                    $this->_view->getLayout()->initMessages();
                    $result['messages'] = $this->_view->getLayout()->getMessagesBlock()->getGroupedHtml();
                }
            } catch (\Magento\Framework\Exception\LocalizedException $e) {
                $result['error'] = $e->getMessage();
            } catch (\Exception $e) {
                $result['error'] = __(
                    'Something went wrong while generating coupons. Please review the log and try again.'
                );
                $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            }
        }
        $this->getResponse()->representJson(
            $this->_objectManager->get('Magento\Framework\Json\Helper\Data')->jsonEncode($result)
        );
    }
 public function execute()
 {
     if ($this->getRequest()->getPostValue()) {
         try {
             $model = $this->_objectManager->create('Lapisbard\\StoreLocator\\Model\\Locations');
             $data = $this->getRequest()->getPostValue();
             $inputFilter = new \Zend_Filter_Input([], [], $data);
             $data = $inputFilter->getUnescaped();
             $id = $this->getRequest()->getParam('id');
             if ($id) {
                 $model->load($id);
                 if ($id != $model->getId()) {
                     throw new \Magento\Framework\Exception\LocalizedException(__('The wrong item is specified.'));
                 }
             }
             $model->setData($data);
             $session = $this->_objectManager->get('Magento\\Backend\\Model\\Session');
             $session->setPageData($model->getData());
             $model->save();
             $this->messageManager->addSuccess(__('You saved the item.'));
             $session->setPageData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('lapisbard_storelocator/*/edit', ['id' => $model->getId()]);
                 return;
             }
             $this->_redirect('lapisbard_storelocator/*/');
             return;
         } catch (\Magento\Framework\Exception\LocalizedException $e) {
             $this->messageManager->addError($e->getMessage());
             $id = (int) $this->getRequest()->getParam('id');
             if (!empty($id)) {
                 $this->_redirect('lapisbard_storelocator/*/edit', ['id' => $id]);
             } else {
                 $this->_redirect('lapisbard_storelocator/*/new');
             }
             return;
         } catch (\Exception $e) {
             $this->messageManager->addError(__('Something went wrong while saving the item data. Please review the error log.'));
             $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e);
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setPageData($data);
             $this->_redirect('lapisbard_storelocator/*/edit', ['id' => $this->getRequest()->getParam('id')]);
             return;
         }
     }
     $this->_redirect('lapisbard_storelocator/*/');
 }
 /**
  * Report action init operations
  *
  * @param array|\Magento\Framework\DataObject $blocks
  * @return $this
  */
 public function _initReportAction($blocks)
 {
     if (!is_array($blocks)) {
         $blocks = [$blocks];
     }
     $requestData = $this->_objectManager->get('Magento\\Backend\\Helper\\Data')->prepareFilterString($this->getRequest()->getParam('filter'));
     $inputFilter = new \Zend_Filter_Input(['from' => $this->_dateFilter, 'to' => $this->_dateFilter], [], $requestData);
     $requestData = $inputFilter->getUnescaped();
     $requestData['store_ids'] = $this->getRequest()->getParam('store_ids');
     $params = new \Magento\Framework\DataObject();
     foreach ($requestData as $key => $value) {
         if (!empty($value)) {
             $params->setData($key, $value);
         }
     }
     foreach ($blocks as $block) {
         if ($block) {
             $block->setPeriodType($params->getData('period_type'));
             $block->setFilterData($params);
         }
     }
     return $this;
 }
Exemple #11
0
 /**
  * Initialize product from data
  *
  * @param \Magento\Catalog\Model\Product $product
  * @param array $productData
  * @return \Magento\Catalog\Model\Product
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function initializeFromData(\Magento\Catalog\Model\Product $product, array $productData)
 {
     unset($productData['custom_attributes']);
     unset($productData['extension_attributes']);
     if ($productData) {
         $stockData = isset($productData['stock_data']) ? $productData['stock_data'] : [];
         $productData['stock_data'] = $this->stockFilter->filter($stockData);
     }
     $productData = $this->normalize($productData);
     if (!empty($productData['is_downloadable'])) {
         $productData['product_has_weight'] = 0;
     }
     foreach (['category_ids', 'website_ids'] as $field) {
         if (!isset($productData[$field])) {
             $productData[$field] = [];
         }
     }
     foreach ($productData['website_ids'] as $websiteId => $checkboxValue) {
         if (!$checkboxValue) {
             unset($productData['website_ids'][$websiteId]);
         }
     }
     $wasLockedMedia = false;
     if ($product->isLockedAttribute('media')) {
         $product->unlockAttribute('media');
         $wasLockedMedia = true;
     }
     $dateFieldFilters = [];
     $attributes = $product->getAttributes();
     foreach ($attributes as $attrKey => $attribute) {
         if ($attribute->getBackend()->getType() == 'datetime') {
             if (array_key_exists($attrKey, $productData) && $productData[$attrKey] != '') {
                 $dateFieldFilters[$attrKey] = $this->getDateTimeFilter();
             }
         }
     }
     $inputFilter = new \Zend_Filter_Input($dateFieldFilters, [], $productData);
     $productData = $inputFilter->getUnescaped();
     if (isset($productData['options'])) {
         $productOptions = $productData['options'];
         unset($productData['options']);
     } else {
         $productOptions = [];
     }
     $product->addData($productData);
     if ($wasLockedMedia) {
         $product->lockAttribute('media');
     }
     if ($this->storeManager->hasSingleStore() && empty($product->getWebsiteIds())) {
         $product->setWebsiteIds([$this->storeManager->getStore(true)->getWebsite()->getId()]);
     }
     /**
      * Check "Use Default Value" checkboxes values
      */
     $useDefaults = (array) $this->request->getPost('use_default', []);
     foreach ($useDefaults as $attributeCode => $useDefaultState) {
         if ($useDefaultState) {
             $product->setData($attributeCode, null);
         }
     }
     $product = $this->setProductLinks($product);
     /**
      * Initialize product options
      */
     if ($productOptions && !$product->getOptionsReadonly()) {
         // mark custom options that should to fall back to default value
         $options = $this->mergeProductOptions($productOptions, $this->request->getPost('options_use_default'));
         $customOptions = [];
         foreach ($options as $customOptionData) {
             if (empty($customOptionData['is_delete'])) {
                 if (isset($customOptionData['values'])) {
                     $customOptionData['values'] = array_filter($customOptionData['values'], function ($valueData) {
                         return empty($valueData['is_delete']);
                     });
                 }
                 $customOption = $this->getCustomOptionFactory()->create(['data' => $customOptionData]);
                 $customOption->setProductSku($product->getSku());
                 $customOption->setOptionId(null);
                 $customOptions[] = $customOption;
             }
         }
         $product->setOptions($customOptions);
     }
     $product->setCanSaveCustomOptions(!empty($productData['affect_product_custom_options']) && !$product->getOptionsReadonly());
     return $product;
 }
 public function deleteuserAction()
 {
     $this->_helper->viewRenderer->setNoRender();
     $this->_helper->getHelper("layout")->disableLayout();
     $this->getFileUploadScript();
     $aInputFilters = array("*" => array(new Zend_Filter_StringTrim()));
     $aInputValidators = array("id" => array(new Zend_Validate_Digits()));
     $bJson = false;
     $oInput = new Zend_Filter_Input($aInputFilters, $aInputValidators, $_POST);
     $nId = $oInput->getUnescaped("id");
     $oModelUser = new Admin_Model_User();
     if ($oModelUser->deleteRow($nId)) {
         $bJson = true;
     }
     header("Content-type: application/json");
     echo Zend_Json::encode($bJson);
     exit;
 }
Exemple #13
0
 /**
  * @group ZF-3004
  */
 public function testInsertingNullDoesNotGetEscapedWithDefaultEscapeMethod()
 {
     $input = new Zend_Filter_Input(null, null, array('test' => null));
     $input->process();
     $this->assertFalse($input->hasMissing(), 'Expected hasMissing() to return false');
     $this->assertFalse($input->hasInvalid(), 'Expected hasInvalid() to return false');
     $this->assertFalse($input->hasUnknown(), 'Expected hasUnknown() to return false');
     $this->assertTrue($input->hasValid(), 'Expected hasValid() to return true');
     $this->assertNull($input->getUnescaped('test'), 'getUnescaped of test fails to return null');
     $this->assertNull($input->getEscaped('test'), 'getEscaped of test fails to return null');
     $this->assertNull($input->test, 'magic get of test fails to return null');
 }
 /**
  * Filtering posted data. Converting localized data if needed
  *
  * @param array $data
  * @return array
  */
 public function filter($data)
 {
     $inputFilter = new \Zend_Filter_Input(['custom_theme_from' => $this->dateFilter, 'custom_theme_to' => $this->dateFilter], [], $data);
     $data = $inputFilter->getUnescaped();
     return $data;
 }
Exemple #15
0
 /**
  * Initialize product before saving
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return \Magento\Catalog\Model\Product
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 public function initialize(\Magento\Catalog\Model\Product $product)
 {
     $productData = $this->request->getPost('product');
     unset($productData['custom_attributes']);
     unset($productData['extension_attributes']);
     if ($productData) {
         $stockData = isset($productData['stock_data']) ? $productData['stock_data'] : [];
         $productData['stock_data'] = $this->stockFilter->filter($stockData);
     }
     foreach (['category_ids', 'website_ids'] as $field) {
         if (!isset($productData[$field])) {
             $productData[$field] = [];
         }
     }
     $wasLockedMedia = false;
     if ($product->isLockedAttribute('media')) {
         $product->unlockAttribute('media');
         $wasLockedMedia = true;
     }
     $dateFieldFilters = [];
     $attributes = $product->getAttributes();
     foreach ($attributes as $attrKey => $attribute) {
         if ($attribute->getBackend()->getType() == 'datetime') {
             if (array_key_exists($attrKey, $productData) && $productData[$attrKey] != '') {
                 $dateFieldFilters[$attrKey] = $this->dateFilter;
             }
         }
     }
     $inputFilter = new \Zend_Filter_Input($dateFieldFilters, [], $productData);
     $productData = $inputFilter->getUnescaped();
     $product->addData($productData);
     if ($wasLockedMedia) {
         $product->lockAttribute('media');
     }
     if ($this->storeManager->hasSingleStore()) {
         $product->setWebsiteIds([$this->storeManager->getStore(true)->getWebsite()->getId()]);
     }
     /**
      * Check "Use Default Value" checkboxes values
      */
     $useDefaults = $this->request->getPost('use_default');
     if ($useDefaults) {
         foreach ($useDefaults as $attributeCode) {
             $product->setData($attributeCode, false);
         }
     }
     $links = $this->request->getPost('links');
     $links = is_array($links) ? $links : [];
     $linkTypes = ['related', 'upsell', 'crosssell'];
     foreach ($linkTypes as $type) {
         if (isset($links[$type])) {
             $links[$type] = $this->jsHelper->decodeGridSerializedInput($links[$type]);
         }
     }
     $product = $this->productLinks->initializeLinks($product, $links);
     $productLinks = $product->getProductLinks();
     $linkTypes = ['related' => $product->getRelatedReadonly(), 'upsell' => $product->getUpsellReadonly(), 'crosssell' => $product->getCrosssellReadonly()];
     foreach ($linkTypes as $linkType => $readonly) {
         if (isset($links[$linkType]) && !$readonly) {
             foreach ($links[$linkType] as $linkId => $linkData) {
                 $linkProduct = $this->productRepository->getById($linkId);
                 $link = $this->productLinkFactory->create();
                 $link->setSku($product->getSku())->setLinkedProductSku($linkProduct->getSku())->setLinkType($linkType)->setPosition(isset($linkData['position']) ? (int) $linkData['position'] : 0);
                 $productLinks[] = $link;
             }
         }
     }
     $product->setProductLinks($productLinks);
     /**
      * Initialize product options
      */
     if (isset($productData['options']) && !$product->getOptionsReadonly()) {
         // mark custom options that should to fall back to default value
         $options = $this->mergeProductOptions($productData['options'], $this->request->getPost('options_use_default'));
         $customOptions = [];
         foreach ($options as $customOptionData) {
             if (!(bool) $customOptionData['is_delete']) {
                 $customOption = $this->customOptionFactory->create(['data' => $customOptionData]);
                 $customOption->setProductSku($product->getSku());
                 $customOption->setOptionId(null);
                 $customOptions[] = $customOption;
             }
         }
         $product->setOptions($customOptions);
     }
     $product->setCanSaveCustomOptions((bool) $this->request->getPost('affect_product_custom_options') && !$product->getOptionsReadonly());
     return $product;
 }
Exemple #16
0
 /**
  * Validate product
  *
  * @return void
  */
 public function execute()
 {
     $response = new \Magento\Framework\Object();
     $response->setError(false);
     try {
         $productData = $this->getRequest()->getPost('product');
         if ($productData && !isset($productData['stock_data']['use_config_manage_stock'])) {
             $productData['stock_data']['use_config_manage_stock'] = 0;
         }
         /* @var $product \Magento\Catalog\Model\Product */
         $product = $this->_objectManager->create('Magento\\Catalog\\Model\\Product');
         $product->setData('_edit_mode', true);
         $storeId = $this->getRequest()->getParam('store');
         if ($storeId) {
             $product->setStoreId($storeId);
         }
         $setId = $this->getRequest()->getParam('set');
         if ($setId) {
             $product->setAttributeSetId($setId);
         }
         $typeId = $this->getRequest()->getParam('type');
         if ($typeId) {
             $product->setTypeId($typeId);
         }
         $productId = $this->getRequest()->getParam('id');
         if ($productId) {
             $product->load($productId);
         }
         $dateFieldFilters = array();
         $attributes = $product->getAttributes();
         foreach ($attributes as $attrKey => $attribute) {
             if ($attribute->getBackend()->getType() == 'datetime') {
                 if (array_key_exists($attrKey, $productData) && $productData[$attrKey] != '') {
                     $dateFieldFilters[$attrKey] = $this->_dateFilter;
                 }
             }
         }
         $inputFilter = new \Zend_Filter_Input($dateFieldFilters, array(), $productData);
         $productData = $inputFilter->getUnescaped();
         $product->addData($productData);
         /* set restrictions for date ranges */
         $resource = $product->getResource();
         $resource->getAttribute('special_from_date')->setMaxValue($product->getSpecialToDate());
         $resource->getAttribute('news_from_date')->setMaxValue($product->getNewsToDate());
         $resource->getAttribute('custom_design_from')->setMaxValue($product->getCustomDesignTo());
         $this->productValidator->validate($product, $this->getRequest(), $response);
     } catch (\Magento\Eav\Model\Entity\Attribute\Exception $e) {
         $response->setError(true);
         $response->setAttribute($e->getAttributeCode());
         $response->setMessage($e->getMessage());
     } catch (\Magento\Framework\Model\Exception $e) {
         $response->setError(true);
         $response->setMessage($e->getMessage());
     } catch (\Exception $e) {
         $this->messageManager->addError($e->getMessage());
         $this->_view->getLayout()->initMessages();
         $response->setError(true);
         $response->setHtmlMessage($this->_view->getLayout()->getMessagesBlock()->getGroupedHtml());
     }
     $this->getResponse()->representJson($response->toJson());
 }
Exemple #17
0
 /**
  * Datetime data preprocessing
  *
  * @param \Magento\Catalog\Model\Category $category
  * @param array $postData
  *
  * @return array
  */
 protected function dateTimePreprocessing($category, $postData)
 {
     $dateFieldFilters = [];
     $attributes = $category->getAttributes();
     foreach ($attributes as $attrKey => $attribute) {
         if ($attribute->getBackend()->getType() == 'datetime') {
             if (array_key_exists($attrKey, $postData) && $postData[$attrKey] != '') {
                 $dateFieldFilters[$attrKey] = $this->getDateTimeFilter();
             }
         }
     }
     $inputFilter = new \Zend_Filter_Input($dateFieldFilters, [], $postData);
     return $inputFilter->getUnescaped();
 }
Exemple #18
0
 /**
  * @param $data
  * @return mixed
  */
 public function filterData($data)
 {
     $inputFilter = new \Zend_Filter_Input(['dop' => $this->dateFilter], [], $data);
     $data = $inputFilter->getUnescaped();
     return $data;
 }
 public function testGetUnescapedAllFields()
 {
     $data = array('field1' => 'ab&c');
     $input = new Zend_Filter_Input(null, null, $data);
     $this->assertFalse($input->hasMissing(), 'Expected hasMissing() to return false');
     $this->assertFalse($input->hasInvalid(), 'Expected hasInvalid() to return false');
     $this->assertFalse($input->hasUnknown(), 'Expected hasUnknown() to return false');
     $this->assertTrue($input->hasValid(), 'Expected hasValid() to return true');
     $this->assertEquals(array('field1' => 'ab&c'), $input->getUnescaped());
 }
 public function loaddataordersnewAction()
 {
     $this->_helper->viewRenderer->setNoRender();
     $this->_helper->getHelper("layout")->disableLayout();
     $aInputFilters = array("*" => array(new Zend_Filter_StringTrim()));
     $aInputValidators = array("num_row_per_page" => array(new Zend_Validate_Digits()), "curr_page" => array(new Zend_Validate_Digits()), "sort_column" => array(new AppCms2_Validate_SpecialAlpha()), "sort_method" => array(new Zend_Validate_Alpha()), "filter_order_status_id" => array(new Zend_Validate_Digits()), "filter_call_id" => array("allowEmpty" => true), "filter_journal_title" => array("allowEmpty" => true), "filter_amount" => array("allowEmpty" => true), "filter_id" => array(new Zend_Validate_Digits()));
     $oInput = new Zend_Filter_Input($aInputFilters, $aInputValidators, $_POST);
     $nNumRowPerPage = $oInput->getUnescaped("num_row_per_page");
     $nCurrPage = $oInput->getUnescaped("curr_page");
     $sSortColumn = $oInput->getUnescaped("sort_column");
     $sSortMethod = $oInput->getUnescaped("sort_method");
     $aFilter = array("order_status_id" => $oInput->getEscaped("filter_order_status_id") != NULL ? $oInput->getUnescaped("filter_order_status_id") : NULL, "call_id" => $oInput->getEscaped("filter_call_id") != NULL ? $oInput->getUnescaped("filter_call_id") : NULL, "journal_title" => $oInput->getEscaped("filter_journal_title") != NULL ? $oInput->getUnescaped("filter_journal_title") : NULL, "amount" => $oInput->getEscaped("filter_amount") != NULL ? (double) $oInput->getUnescaped("filter_amount") * 100 : NULL, "id" => $oInput->getUnescaped("filter_id"));
     foreach ($aFilter as $sKey => $sValue) {
         if (!isset($sValue)) {
             unset($aFilter[$sKey]);
         }
     }
     $oModelVOrderJournal = new User_Model_VOrderJournal();
     $oRowset = $oModelVOrderJournal->getUserOrders(null, $aFilter, $nNumRowPerPage, ($nCurrPage - 1) * $nNumRowPerPage, $sSortColumn . " " . $sSortMethod);
     $nNumRows = $oModelVOrderJournal->getUserOrders(null, $aFilter)->count();
     $aRowset = $oRowset->toArray();
     foreach ($aRowset as $nKey => $aValue) {
         $oOrderRelationships = $oModelVOrderJournal->getOrderRelationships($aValue["id"], $aValue["item_id"]);
         $aRowset[$nKey]["relationships_count"] = $oOrderRelationships->count();
         $aRowset[$nKey]["relationships"] = $oOrderRelationships->toArray();
     }
     $aJson = array("rowset" => $aRowset, "num_rows" => $nNumRows);
     header("Content-type: application/json");
     echo Zend_Json::encode($aJson);
     exit;
 }
Exemple #21
0
 /**
  * Filter the form input according to some criteria.
  *
  * @todo Move part of these filter inside save().
  *
  * @param array $post
  * @return array Filtered post data.
  */
 protected function filterPostData($post)
 {
     // Remove superfluous whitespace.
     $options = array('inputNamespace' => 'Omeka_Filter');
     $filters = array('uri' => array('StripTags', 'StringTrim'), 'records_for_files' => 'Boolean');
     $filter = new Zend_Filter_Input($filters, null, $post, $options);
     $post = $filter->getUnescaped();
     // Avoid some notices with missed values.
     $basePost = array('uri' => '', 'item_type_id' => 0);
     $post = array_merge($basePost, $post);
     $post['uri'] = rtrim(trim($post['uri']), '/.');
     // Unset immutable or specific properties from $_POST.
     $immutable = array('id', 'identifier', 'parameters', 'status', 'messages', 'owner_id', 'added', 'modified');
     foreach ($immutable as $value) {
         unset($post[$value]);
     }
     // This filter move all parameters inside 'parameters' of the folder.
     $parameters = $post;
     // Property level.
     unset($parameters['uri']);
     unset($parameters['item_type_id']);
     // Not properties.
     unset($parameters['csrf_token']);
     unset($parameters['submit']);
     // Set default parameters if needed.
     $defaults = array('unreferenced_files' => 'by_file', 'exclude_extensions' => '', 'allow_no_extension' => false, 'element_delimiter' => ArchiveFolder_Mapping_Table::DEFAULT_ELEMENT_DELIMITER, 'empty_value' => ArchiveFolder_Mapping_Table::DEFAULT_EMPTY_VALUE, 'extra_parameters' => array(), 'records_for_files' => true, 'item_type_name' => '', 'identifier_field' => ArchiveFolder_Importer::DEFAULT_IDFIELD, 'action' => ArchiveFolder_Importer::DEFAULT_ACTION);
     $parameters = array_merge($defaults, $parameters);
     // Manage some exceptions.
     // The repository identifier is kept for future evolutions and for the
     // compatibility with the plugin OAI-PMH Static Repository.
     // Remove the web dir when possible.
     if (strpos($post['uri'], WEB_DIR) === 0) {
         $repositoryIdentifierBase = substr($post['uri'], strlen(WEB_DIR));
     } elseif (parse_url($post['uri'], PHP_URL_HOST)) {
         $repositoryIdentifierBase = parse_url($post['uri'], PHP_URL_PATH);
     } else {
         $repositoryIdentifierBase = $post['uri'];
     }
     $repositoryIdentifierBase .= '-' . date('Ymd-His') . '-' . rtrim(strtok(substr(microtime(), 2), ' '), '0');
     $parameters['repository_identifier'] = $this->_keepAlphanumericOnly($repositoryIdentifierBase);
     $parameters['item_type_name'] = $this->_getItemTypeName($post['item_type_id']);
     $parameters['extra_parameters'] = $this->_getExtraParameters($parameters['extra_parameters']);
     if (empty($parameters['unreferenced_files'])) {
         $parameters['unreferenced_files'] = $defaults['unreferenced_files'];
     }
     // Other parameters are not changed, so save them.
     $this->setParameters($parameters);
     $post['identifier'] = $parameters['repository_identifier'];
     return $post;
 }
 /**
  * Workaround to add post data to a record via setArray().
  *
  * @see CSVImport_Builder_Item::_setPostDataViaSetArray()
  *
  * @param Record $record
  * @param array $post Post data.
  */
 private function _setPostDataViaSetArray($record, $post)
 {
     // Some default type have a special filter.
     switch (get_class($record)) {
         case 'Item':
             $options = array('inputNamespace' => 'Omeka_Filter');
             $filters = array(Builder_Item::ITEM_TYPE_ID => 'ForeignKey', Builder_Item::COLLECTION_ID => 'ForeignKey', Builder_Item::IS_PUBLIC => 'Boolean', Builder_Item::IS_FEATURED => 'Boolean');
             $filter = new Zend_Filter_Input($filters, null, $post, $options);
             $post = $filter->getUnescaped();
             break;
         case 'File':
             $immutable = array('id', 'modified', 'added', 'authentication', 'filename', 'original_filename', 'mime_type', 'type_os', 'item_id');
             foreach ($immutable as $value) {
                 unset($post[$value]);
             }
             break;
         case 'Collection':
             $options = array('inputNamespace' => 'Omeka_Filter');
             // User form input does not allow HTML tags or superfluous whitespace
             $filters = array(Builder_Collection::IS_PUBLIC => 'Boolean', Builder_Collection::IS_FEATURED => 'Boolean');
             $filter = new Zend_Filter_Input($filters, null, $post, $options);
             $post = $filter->getUnescaped();
             break;
         default:
             return;
     }
     // Avoid an issue when the post is null.
     if (empty($post)) {
         return;
     }
     if (!isset($post['Elements'])) {
         $post['Elements'] = array();
     }
     // Default used in Omeka_Record_Builder_AbstractBuilder::setPostData().
     $post = new ArrayObject($post);
     if (array_key_exists('id', $post)) {
         unset($post['id']);
     }
     $record->setArray(array('_postData' => $post));
 }
Exemple #23
0
 /**
  * Filtering posted data. Converting localized data if needed
  *
  * @param array $data
  * @return array|null
  */
 protected function _filterPostData($data)
 {
     $inputFilter = new \Zend_Filter_Input(array('date_from' => $this->dateFilter, 'date_to' => $this->dateFilter), array(), $data);
     $data = $inputFilter->getUnescaped();
     return $data;
 }
Exemple #24
0
 /**
  * zendInputFilter() - strips tags from input and optionally returns escaped output
  * @param array $input - array of user input
  * @param $escaped - will additionally run an html entities filter if set to true
  * @return array
  */
 public static function zendInputFilter($input, $escaped = false)
 {
     if ($input) {
         $output = new Zend_Filter_Input(array('*' => 'StripTags'), array(), $input);
         //strips tags from all input
         $escaped = $output->getEscaped();
         // will be automatically run through an HTML-entities-filter
         // or
         $unescaped = $output->getUnescaped();
         // the values as they come out of the filter-chain.
         if ($escaped == true) {
             return $escaped;
         } else {
             return $unescaped;
         }
     } else {
         //Logger::log("No input received ".__METHOD__, Logger::DEBUG);
         return $input;
     }
 }
Exemple #25
0
 /**
  * Filter the POST data from the form.
  *
  * Converts public/featured flags to booleans.
  * 
  * @param array $post
  * @return array
  */
 protected function filterPostData($post)
 {
     $options = array('inputNamespace' => 'Omeka_Filter');
     // User form input does not allow HTML tags or superfluous whitespace
     $filters = array('public' => 'Boolean', 'featured' => 'Boolean');
     $filter = new Zend_Filter_Input($filters, null, $post, $options);
     $post = $filter->getUnescaped();
     return $post;
 }
 /**
  * Save changes to an existing news article, or save a new article in the database. If a new article the function will return the ID.
  *
  * @return int
  */
 private function _saveNewsArticle()
 {
     // First of all we need to validate and sanitise the input from the form
     $requiredText = new Zend_Validate();
     $requiredText->addValidator(new Zend_Validate_NotEmpty());
     // $requiredText->addValidator(new Zend_Validate_Alnum(array('allowWhiteSpace' => true)));
     $filters = array('id' => 'Digits', 'newsTitle' => 'StringTrim', 'newsDate' => 'StringTrim', 'categoryList' => 'StringTrim');
     $validators = array('id' => array('allowEmpty' => true), 'newsTitle' => $requiredText, 'newsContent' => array('allowEmpty' => true), 'newsDate' => 'NotEmpty', 'categoryList' => array('allowEmpty' => true));
     $input = new Zend_Filter_Input($filters, $validators, $_POST);
     if ($input->isValid()) {
         // Data is all valid, formatted and sanitized so we can save it in the database
         $newsArticle = new Datasource_Cms_News();
         if (!$input->id) {
             // This is a new article so we need to create a new ID
             $newsID = $newsArticle->addNew($input->newsTitle, $input->newsDate, $input->getUnescaped('newsContent'));
         } else {
             // This is an existing article so we can just update the data
             $newsArticle->saveChanges($input->id, $input->newsTitle, $input->newsDate, $input->getUnescaped('newsContent'));
             $newsID = $input->id;
         }
         // Now we need to link the page to the categories selected
         $categoryList = $input->categoryList;
         $newsArticle->saveCategories($newsID, $categoryList);
         // Changes saved - so send them back with a nice success message
         $this->_helper->getHelper('FlashMessenger')->addMessage(array('saved' => true));
         $this->_helper->getHelper('Redirector')->goToUrl('/cms-admin/news/edit?id=' . $newsID);
     } else {
         // Invalid data in form
         print_r($_POST);
         print_r($input->getErrors());
         print_r($input->getInvalid());
     }
 }
Exemple #27
0
 /**
  * Filter post data from form submissions.  
  * 
  * @param array Dirty post data
  * @return array Clean post data
  */
 protected function filterPostData($post)
 {
     $options = array('inputNamespace' => 'Omeka_Filter');
     $filters = array('item_type_id' => 'ForeignKey', 'collection_id' => 'ForeignKey', 'public' => 'Boolean', 'featured' => 'Boolean');
     $filter = new Zend_Filter_Input($filters, null, $post, $options);
     $post = $filter->getUnescaped();
     $bootstrap = Zend_Registry::get('bootstrap');
     $acl = $bootstrap->getResource('Acl');
     $currentUser = $bootstrap->getResource('CurrentUser');
     // check permissions to make public and make featured
     if (!$acl->isAllowed($currentUser, 'Items', 'makePublic')) {
         unset($post['public']);
     }
     if (!$acl->isAllowed($currentUser, 'Items', 'makeFeatured')) {
         unset($post['featured']);
     }
     return $post;
 }
 public function translateAction()
 {
     $this->_helper->viewRenderer->setNoRender();
     $this->_helper->getHelper("layout")->disableLayout();
     $aInputFilters = array("*" => array(new Zend_Filter_StringTrim()));
     $aInputValidators = array("text" => array("allowEmpty" => true));
     $oInput = new Zend_Filter_Input($aInputFilters, $aInputValidators, $_POST);
     $aInputText = $oInput->getUnescaped("text");
     if (count($aInputText)) {
         $aOutputText = array();
         foreach ($aInputText as $sKey => $sValue) {
             $aOutputText["text"][$sKey] = $this->view->translate($sValue);
         }
         header("Content-type: application/json");
         echo Zend_Json::encode($aOutputText);
     }
     exit;
 }
Exemple #29
0
 public function execute()
 {
     if ($this->getRequest()->getPostValue()) {
         try {
             $model = $this->_objectManager->create('Emizentech\\ShopByBrand\\Model\\Items');
             $data = $this->getRequest()->getPostValue();
             $inputFilter = new \Zend_Filter_Input([], [], $data);
             $data = $inputFilter->getUnescaped();
             $id = $this->getRequest()->getParam('id');
             if ($id) {
                 $model->load($id);
                 if ($id != $model->getId()) {
                     throw new \Magento\Framework\Exception\LocalizedException(__('The wrong item is specified.'));
                 }
             }
             try {
                 $uploader = $this->_objectManager->create('Magento\\MediaStorage\\Model\\File\\Uploader', ['fileId' => 'logo']);
                 $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                 /** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapter */
                 $imageAdapter = $this->_objectManager->get('Magento\\Framework\\Image\\AdapterFactory')->create();
                 $uploader->setAllowRenameFiles(true);
                 $uploader->setFilesDispersion(true);
                 /** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
                 $mediaDirectory = $this->_objectManager->get('Magento\\Framework\\Filesystem')->getDirectoryRead(DirectoryList::MEDIA);
                 $result = $uploader->save($mediaDirectory->getAbsolutePath('brand'));
                 if ($result['error'] == 0) {
                     $data['logo'] = 'brand' . $result['file'];
                 }
             } catch (\Exception $e) {
                 //unset($data['image']);
             }
             if (isset($data['logo']['delete']) && $data['logo']['delete'] == '1') {
                 $data['logo'] = '';
             } else {
                 if (isset($data['logo']['value'])) {
                     $data['logo'] = $data['logo']['value'];
                 }
             }
             $model->setData($data);
             $session = $this->_objectManager->get('Magento\\Backend\\Model\\Session');
             $session->setPageData($model->getData());
             $model->save();
             $this->messageManager->addSuccess(__('You saved the item.'));
             $session->setPageData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('emizentech_shopbybrand/*/edit', ['id' => $model->getId()]);
                 return;
             }
             $this->_redirect('emizentech_shopbybrand/*/');
             return;
         } catch (\Magento\Framework\Exception\LocalizedException $e) {
             $this->messageManager->addError($e->getMessage());
             $id = (int) $this->getRequest()->getParam('id');
             if (!empty($id)) {
                 $this->_redirect('emizentech_shopbybrand/*/edit', ['id' => $id]);
             } else {
                 $this->_redirect('emizentech_shopbybrand/*/new');
             }
             return;
         } catch (\Exception $e) {
             $this->messageManager->addError(__('Something went wrong while saving the item data. Please review the error log.'));
             $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e);
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setPageData($data);
             $this->_redirect('emizentech_shopbybrand/*/edit', ['id' => $this->getRequest()->getParam('id')]);
             return;
         }
     }
     $this->_redirect('emizentech_shopbybrand/*/');
 }
Exemple #30
0
 /**
  * Promo quote save action
  *
  * @return void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.NPathComplexity)
  */
 public function execute()
 {
     if ($this->getRequest()->getPostValue()) {
         try {
             /** @var $model \Magento\SalesRule\Model\Rule */
             $model = $this->_objectManager->create('Magento\\SalesRule\\Model\\Rule');
             $this->_eventManager->dispatch('adminhtml_controller_salesrule_prepare_save', ['request' => $this->getRequest()]);
             $data = $this->getRequest()->getPostValue();
             $inputFilter = new \Zend_Filter_Input(['from_date' => $this->_dateFilter, 'to_date' => $this->_dateFilter], [], $data);
             $data = $inputFilter->getUnescaped();
             $id = $this->getRequest()->getParam('rule_id');
             if ($id) {
                 $model->load($id);
                 if ($id != $model->getId()) {
                     throw new \Magento\Framework\Exception\LocalizedException(__('The wrong rule is specified.'));
                 }
             }
             $session = $this->_objectManager->get('Magento\\Backend\\Model\\Session');
             $validateResult = $model->validateData(new \Magento\Framework\DataObject($data));
             if ($validateResult !== true) {
                 foreach ($validateResult as $errorMessage) {
                     $this->messageManager->addError($errorMessage);
                 }
                 $session->setPageData($data);
                 $this->_redirect('sales_rule/*/edit', ['id' => $model->getId()]);
                 return;
             }
             if (isset($data['simple_action']) && $data['simple_action'] == 'by_percent' && isset($data['discount_amount'])) {
                 $data['discount_amount'] = min(100, $data['discount_amount']);
             }
             if (isset($data['rule']['conditions'])) {
                 $data['conditions'] = $data['rule']['conditions'];
             }
             if (isset($data['rule']['actions'])) {
                 $data['actions'] = $data['rule']['actions'];
             }
             unset($data['rule']);
             $model->loadPost($data);
             $useAutoGeneration = (int) (!empty($data['use_auto_generation']));
             $model->setUseAutoGeneration($useAutoGeneration);
             $session->setPageData($model->getData());
             $model->save();
             $this->messageManager->addSuccess(__('You saved the rule.'));
             $session->setPageData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('sales_rule/*/edit', ['id' => $model->getId()]);
                 return;
             }
             $this->_redirect('sales_rule/*/');
             return;
         } catch (\Magento\Framework\Exception\LocalizedException $e) {
             $this->messageManager->addError($e->getMessage());
             $id = (int) $this->getRequest()->getParam('rule_id');
             if (!empty($id)) {
                 $this->_redirect('sales_rule/*/edit', ['id' => $id]);
             } else {
                 $this->_redirect('sales_rule/*/new');
             }
             return;
         } catch (\Exception $e) {
             $this->messageManager->addError(__('Something went wrong while saving the rule data. Please review the error log.'));
             $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e);
             $this->_objectManager->get('Magento\\Backend\\Model\\Session')->setPageData($data);
             $this->_redirect('sales_rule/*/edit', ['id' => $this->getRequest()->getParam('rule_id')]);
             return;
         }
     }
     $this->_redirect('sales_rule/*/');
 }