/** * Login post action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { if ($this->_getSession()->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/*/'); return $resultRedirect; } if ($this->getRequest()->isPost()) { $login = $this->getRequest()->getPost('login'); if (!empty($login['username']) && !empty($login['password'])) { try { $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']); $this->_getSession()->setCustomerDataAsLoggedIn($customer); $this->_getSession()->regenerateId(); } catch (EmailNotConfirmedException $e) { $value = $this->customerUrl->getEmailConfirmationUrl($login['username']); $message = __('This account is not confirmed.' . ' <a href="%1">Click here</a> to resend confirmation email.', $value); $this->messageManager->addError($message); $this->_getSession()->setUsername($login['username']); } catch (AuthenticationException $e) { $message = __('Invalid login or password.'); $this->messageManager->addError($message); $this->_getSession()->setUsername($login['username']); } catch (\Exception $e) { $this->messageManager->addError(__('There was an error validating the login and password.')); } } else { $this->messageManager->addError(__('Login and password are required.')); } } return $this->accountRedirect->getRedirect(); }
/** * Save newsletter subscription preference action * * @return void|null */ public function executeInternal() { if (!$this->formKeyValidator->validate($this->getRequest())) { return $this->_redirect('customer/account/'); } $customerId = $this->_customerSession->getCustomerId(); if ($customerId === null) { $this->messageManager->addError(__('Something went wrong while saving your subscription.')); } else { try { $customer = $this->customerRepository->getById($customerId); $storeId = $this->storeManager->getStore()->getId(); $customer->setStoreId($storeId); $this->customerRepository->save($customer); if ((bool) $this->getRequest()->getParam('is_subscribed', false)) { $this->subscriberFactory->create()->subscribeCustomerById($customerId); $this->messageManager->addSuccess(__('We saved the subscription.')); } else { $this->subscriberFactory->create()->unsubscribeCustomerById($customerId); $this->messageManager->addSuccess(__('We removed the subscription.')); } } catch (\Exception $e) { $this->messageManager->addError(__('Something went wrong while saving your subscription.')); } } $this->_redirect('customer/account/'); }
/** * Add cart item to wishlist and remove from cart * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/'); } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } try { $itemId = (int) $this->getRequest()->getParam('item'); $item = $this->cart->getQuote()->getItemById($itemId); if (!$item) { throw new LocalizedException(__('The requested cart item doesn\'t exist.')); } $productId = $item->getProductId(); $buyRequest = $item->getBuyRequest(); $wishlist->addNewItem($productId, $buyRequest); $this->cart->getQuote()->removeItem($itemId); $this->cart->save(); $this->wishlistHelper->calculate(); $wishlist->save(); $this->messageManager->addSuccessMessage(__("%1 has been moved to your wish list.", $this->escaper->escapeHtml($item->getProduct()->getName()))); } catch (LocalizedException $e) { $this->messageManager->addErrorMessage($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __('We can\'t move the item to the wish list.')); } return $resultRedirect->setUrl($this->cartHelper->getCartUrl()); }
/** * Change customer password action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->formKeyValidator->validate($this->getRequest())) { $resultRedirect->setPath('*/*/edit'); return $resultRedirect; } if ($this->getRequest()->isPost()) { $customerId = $this->_getSession()->getCustomerId(); $customer = $this->customerExtractor->extract('customer_account_edit', $this->_request); $customer->setId($customerId); if ($customer->getAddresses() == null) { $customer->setAddresses($this->customerRepository->getById($customerId)->getAddresses()); } if ($this->getRequest()->getParam('change_password')) { $currPass = $this->getRequest()->getPost('current_password'); $newPass = $this->getRequest()->getPost('password'); $confPass = $this->getRequest()->getPost('password_confirmation'); if (strlen($newPass)) { if ($newPass == $confPass) { try { $customerEmail = $this->customerRepository->getById($customerId)->getEmail(); $this->customerAccountManagement->changePassword($customerEmail, $currPass, $newPass); } catch (AuthenticationException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('Something went wrong while changing the password.')); } } else { $this->messageManager->addError(__('Confirm your new password.')); } } else { $this->messageManager->addError(__('Please enter new password.')); } } try { $this->customerRepository->save($customer); } catch (AuthenticationException $e) { $this->messageManager->addError($e->getMessage()); } catch (InputException $e) { $this->messageManager->addException($e, __('Invalid input')); } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t save the customer.') . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>'); } if ($this->messageManager->getMessages()->getCount() > 0) { $this->_getSession()->setCustomerFormData($this->getRequest()->getPostValue()); $resultRedirect->setPath('*/*/edit'); return $resultRedirect; } $this->messageManager->addSuccess(__('You saved the account information.')); $resultRedirect->setPath('customer/account'); return $resultRedirect; } $resultRedirect->setPath('*/*/edit'); return $resultRedirect; }
/** * Overview action * * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { if (!$this->formKeyValidator->validate($this->getRequest())) { $this->_forward('backToAddresses'); return; } if (!$this->_validateMinimumAmount()) { return; } try { $agreementsValidator = $this->_objectManager->get('Magento\\Checkout\\Model\\Agreements\\AgreementsValidator'); if (!$agreementsValidator->isValid(array_keys($this->getRequest()->getPost('agreement', [])))) { $this->messageManager->addError(__('Please agree to all Terms and Conditions before placing the order.')); $this->_redirect('*/*/billing'); return; } $payment = $this->getRequest()->getPost('payment'); $paymentInstance = $this->_getCheckout()->getQuote()->getPayment(); if (isset($payment['cc_number'])) { $paymentInstance->setCcNumber($payment['cc_number']); } if (isset($payment['cc_cid'])) { $paymentInstance->setCcCid($payment['cc_cid']); } $this->_getCheckout()->createOrders(); $this->_getState()->setActiveStep(State::STEP_SUCCESS); $this->_getState()->setCompleteStep(State::STEP_OVERVIEW); $this->_getCheckout()->getCheckoutSession()->clearQuote(); $this->_getCheckout()->getCheckoutSession()->setDisplaySuccess(true); $this->_redirect('*/*/success'); } catch (PaymentException $e) { $message = $e->getMessage(); if (!empty($message)) { $this->messageManager->addError($message); } $this->_redirect('*/*/billing'); } catch (\Magento\Checkout\Exception $e) { $this->_objectManager->get('Magento\\Checkout\\Helper\\Data')->sendPaymentFailedEmail($this->_getCheckout()->getQuote(), $e->getMessage(), 'multi-shipping'); $this->_getCheckout()->getCheckoutSession()->clearQuote(); $this->messageManager->addError($e->getMessage()); $this->_redirect('*/cart'); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->_objectManager->get('Magento\\Checkout\\Helper\\Data')->sendPaymentFailedEmail($this->_getCheckout()->getQuote(), $e->getMessage(), 'multi-shipping'); $this->messageManager->addError($e->getMessage()); $this->_redirect('*/*/billing'); } catch (\Exception $e) { $this->logger->critical($e); try { $this->_objectManager->get('Magento\\Checkout\\Helper\\Data')->sendPaymentFailedEmail($this->_getCheckout()->getQuote(), $e->getMessage(), 'multi-shipping'); } catch (\Exception $e) { $this->logger->error($e->getMessage()); } $this->messageManager->addError(__('Order place error')); $this->_redirect('*/*/billing'); } }
/** * Adding new item * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/'); } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } $session = $this->_customerSession; $requestParams = $this->getRequest()->getParams(); if ($session->getBeforeWishlistRequest()) { $requestParams = $session->getBeforeWishlistRequest(); $session->unsBeforeWishlistRequest(); } $productId = isset($requestParams['product']) ? (int) $requestParams['product'] : null; if (!$productId) { $resultRedirect->setPath('*/'); return $resultRedirect; } try { $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { $product = null; } if (!$product || !$product->isVisibleInCatalog()) { $this->messageManager->addErrorMessage(__('We can\'t specify a product.')); $resultRedirect->setPath('*/'); return $resultRedirect; } try { $buyRequest = new \Magento\Framework\DataObject($requestParams); $result = $wishlist->addNewItem($product, $buyRequest); if (is_string($result)) { throw new \Magento\Framework\Exception\LocalizedException(__($result)); } $wishlist->save(); $this->_eventManager->dispatch('wishlist_add_product', ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]); $referer = $session->getBeforeWishlistUrl(); if ($referer) { $session->setBeforeWishlistUrl(null); } else { $referer = $this->_redirect->getRefererUrl(); } $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $this->messageManager->addComplexSuccessMessage('addProductSuccessMessage', ['product_name' => $product->getName(), 'referer' => $referer]); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addErrorMessage(__('We can\'t add the item to Wish List right now: %1.', $e->getMessage())); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __('We can\'t add the item to Wish List right now.')); } $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; }
/** * Add all items from wishlist to shopping cart * * @return void */ public function execute() { if (!$this->formKeyValidator->validate($this->getRequest())) { $this->_forward('noroute'); return; } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { $this->_forward('noroute'); return; } $redirectUrl = $this->itemCarrier->moveAllToCart($wishlist, $this->getRequest()->getParam('qty')); $this->getResponse()->setRedirect($redirectUrl); }
/** * Action to accept new configuration for a wishlist item * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/'); } $productId = (int) $this->getRequest()->getParam('product'); if (!$productId) { $resultRedirect->setPath('*/'); return $resultRedirect; } try { $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { $product = null; } if (!$product || !$product->isVisibleInCatalog()) { $this->messageManager->addError(__('We can\'t specify a product.')); $resultRedirect->setPath('*/'); return $resultRedirect; } try { $id = (int) $this->getRequest()->getParam('id'); /* @var \Magento\Wishlist\Model\Item */ $item = $this->_objectManager->create('Magento\\Wishlist\\Model\\Item'); $item->load($id); $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId()); if (!$wishlist) { $resultRedirect->setPath('*/'); return $resultRedirect; } $buyRequest = new \Magento\Framework\DataObject($this->getRequest()->getParams()); $wishlist->updateItem($id, $buyRequest)->save(); $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $this->_eventManager->dispatch('wishlist_update_item', ['wishlist' => $wishlist, 'product' => $product, 'item' => $wishlist->getItem($id)]); $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $message = __('%1 has been updated in your Wish List.', $product->getName()); $this->messageManager->addSuccess($message); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addError(__('We can\'t update your Wish List right now.')); $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); } $resultRedirect->setPath('*/*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; }
/** * Process not logged in user data * * @param \Magento\Framework\App\RequestInterface $request * @return void */ protected function _processNotLoggedInUser(\Magento\Framework\App\RequestInterface $request) { $isRedirectNeeded = false; if ($request->getPost('login')) { if ($this->formKeyValidator->validate($request)) { if ($this->_performLogin($request)) { $isRedirectNeeded = $this->_redirectIfNeededAfterLogin($request); } } else { $this->_actionFlag->set('', \Magento\Framework\App\ActionInterface::FLAG_NO_DISPATCH, true); $this->_response->setRedirect($this->_url->getCurrentUrl()); $this->messageManager->addError(__('Invalid Form Key. Please refresh the page.')); $isRedirectNeeded = true; } } if (!$isRedirectNeeded && !$request->isForwarded()) { if ($request->getParam('isIframe')) { $request->setForwarded(true)->setRouteName('adminhtml')->setControllerName('auth')->setActionName('deniedIframe')->setDispatched(false); } elseif ($request->getParam('isAjax')) { $request->setForwarded(true)->setRouteName('adminhtml')->setControllerName('auth')->setActionName('deniedJson')->setDispatched(false); } else { $request->setForwarded(true)->setRouteName('adminhtml')->setControllerName('auth')->setActionName('login')->setDispatched(false); } } }
/** * Check url keys. If non valid - redirect * * @return bool */ public function _processUrlKeys() { $_isValidFormKey = true; $_isValidSecretKey = true; $_keyErrorMsg = ''; if ($this->_auth->isLoggedIn()) { if ($this->getRequest()->isPost()) { $_isValidFormKey = $this->_formKeyValidator->validate($this->getRequest()); $_keyErrorMsg = __('Invalid Form Key. Please refresh the page.'); } elseif ($this->_backendUrl->useSecretKey()) { $_isValidSecretKey = $this->_validateSecretKey(); $_keyErrorMsg = __('You entered an invalid Secret Key. Please refresh the page.'); } } if (!$_isValidFormKey || !$_isValidSecretKey) { $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); $this->_actionFlag->set('', self::FLAG_NO_POST_DISPATCH, true); if ($this->getRequest()->getQuery('isAjax', false) || $this->getRequest()->getQuery('ajax', false)) { $this->getResponse()->representJson($this->_objectManager->get('Magento\\Framework\\Json\\Helper\\Data')->jsonEncode(['error' => true, 'message' => $_keyErrorMsg])); } else { $this->_redirect($this->_backendUrl->getStartupPageUrl()); } return false; } return true; }
/** * Login post action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $resultRedirect->setPath('*/*/'); return $resultRedirect; } if ($this->getRequest()->isPost()) { $login = $this->getRequest()->getPost('login'); if (!empty($login['username']) && !empty($login['password'])) { try { $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']); $this->session->setCustomerDataAsLoggedIn($customer); $this->session->regenerateId(); $redirectUrl = $this->accountRedirect->getRedirectCookie(); if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) { $this->accountRedirect->clearRedirectCookie(); $resultRedirect = $this->resultRedirectFactory->create(); // URL is checked to be internal in $this->_redirect->success() $resultRedirect->setUrl($this->_redirect->success($redirectUrl)); return $resultRedirect; } } catch (EmailNotConfirmedException $e) { $value = $this->customerUrl->getEmailConfirmationUrl($login['username']); $message = __('This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.', $value); $this->messageManager->addError($message); $this->session->setUsername($login['username']); } catch (UserLockedException $e) { $message = __('The account is locked. Please wait and try again or contact %1.', $this->getScopeConfig()->getValue('contact/email/recipient_email')); $this->messageManager->addError($message); $this->session->setUsername($login['username']); } catch (AuthenticationException $e) { $message = __('Invalid login or password.'); $this->messageManager->addError($message); $this->session->setUsername($login['username']); } catch (\Exception $e) { // PA DSS violation: throwing or logging an exception here can disclose customer password $this->messageManager->addError(__('An unspecified error occurred. Please contact us for assistance.')); } } else { $this->messageManager->addError(__('A login and a password are required.')); } } return $this->accountRedirect->getRedirect(); }
/** * Add all items from wishlist to shopping cart * * @return \Magento\Framework\Controller\ResultInterface */ public function execute() { /** @var \Magento\Framework\Controller\Result\Forward $resultForward */ $resultForward = $this->resultFactory->create(ResultFactory::TYPE_FORWARD); if (!$this->formKeyValidator->validate($this->getRequest())) { $resultForward->forward('noroute'); return $resultForward; } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { $resultForward->forward('noroute'); return $resultForward; } /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $redirectUrl = $this->itemCarrier->moveAllToCart($wishlist, $this->getRequest()->getParam('qty')); $resultRedirect->setUrl($redirectUrl); return $resultRedirect; }
/** * Dispatch request * * @return ResultInterface|ResponseInterface * @throws NotFoundException */ public function execute() { $request = $this->_request; if (!$request instanceof Http) { return $this->createErrorResponse(self::WRONG_REQUEST); } if (!$this->fkValidator->validate($request)) { return $this->createErrorResponse(self::WRONG_REQUEST); } $paymentToken = $this->getPaymentToken($request); if ($paymentToken === null) { return $this->createErrorResponse(self::WRONG_TOKEN); } try { $this->tokenRepository->delete($paymentToken); } catch (\Exception $e) { return $this->createErrorResponse(self::ACTION_EXCEPTION); } return $this->createSuccessMessage(); }
/** * Change customer password action * * @return \Magento\Framework\Controller\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function executeInternal() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/edit'); } if ($this->getRequest()->isPost()) { $customerId = $this->session->getCustomerId(); $currentCustomer = $this->customerRepository->getById($customerId); // Prepare new customer data $customer = $this->customerExtractor->extract('customer_account_edit', $this->_request); $customer->setId($customerId); if ($customer->getAddresses() == null) { $customer->setAddresses($currentCustomer->getAddresses()); } // Change customer password if ($this->getRequest()->getParam('change_password')) { $this->changeCustomerPassword($currentCustomer->getEmail()); } try { $this->customerRepository->save($customer); } catch (AuthenticationException $e) { $this->messageManager->addError($e->getMessage()); } catch (InputException $e) { $this->messageManager->addException($e, __('Invalid input')); } catch (\Exception $e) { $message = __('We can\'t save the customer.') . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>'; $this->messageManager->addException($e, $message); } if ($this->messageManager->getMessages()->getCount() > 0) { $this->session->setCustomerFormData($this->getRequest()->getPostValue()); return $resultRedirect->setPath('*/*/edit'); } $this->messageManager->addSuccess(__('You saved the account information.')); return $resultRedirect->setPath('customer/account'); } return $resultRedirect->setPath('*/*/edit'); }
/** * Remove item * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/'); } $id = (int) $this->getRequest()->getParam('item'); $item = $this->_objectManager->create('Magento\\Wishlist\\Model\\Item')->load($id); if (!$item->getId()) { throw new NotFoundException(__('Page not found.')); } $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId()); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } try { $item->delete(); $wishlist->save(); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError(__('We can\'t delete the item from Wish List right now because of an error: %1.', $e->getMessage())); } catch (\Exception $e) { $this->messageManager->addError(__('We can\'t delete the item from the Wish List right now.')); } $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $request = $this->getRequest(); $refererUrl = (string) $request->getServer('HTTP_REFERER'); $url = (string) $request->getParam(\Magento\Framework\App\Response\RedirectInterface::PARAM_NAME_REFERER_URL); if ($url) { $refererUrl = $url; } if ($request->getParam(\Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED) && $refererUrl) { $redirectUrl = $refererUrl; } else { $redirectUrl = $this->_redirect->getRedirectUrl($this->_url->getUrl('*/*')); } $resultRedirect->setUrl($redirectUrl); return $resultRedirect; }
/** * Change customer email or password action * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/edit'); } if ($this->getRequest()->isPost()) { $currentCustomerDataObject = $this->getCurrentCustomerDataObject(); $customerCandidateDataObject = $this->populateNewCustomerDataObject($this->_request, $currentCustomerDataObject); try { // whether a customer enabled change email option $this->changeEmail($currentCustomerDataObject); // whether a customer enabled change password option $isPasswordChanged = $this->changePassword($currentCustomerDataObject); $this->customerRepository->save($customerCandidateDataObject); $this->getEmailNotification()->sendNotificationEmailsIfRequired($currentCustomerDataObject, $customerCandidateDataObject, $isPasswordChanged); $this->dispatchSuccessEvent($customerCandidateDataObject); $this->messageManager->addSuccess(__('You saved the account information.')); return $resultRedirect->setPath('customer/account'); } catch (InvalidEmailOrPasswordException $e) { $this->messageManager->addError($e->getMessage()); } catch (UserLockedException $e) { $this->session->logout(); $this->session->start(); $this->messageManager->addError($e->getMessage()); return $resultRedirect->setPath('customer/account/login'); } catch (InputException $e) { $this->messageManager->addError($e->getMessage()); foreach ($e->getErrors() as $error) { $this->messageManager->addError($error->getMessage()); } } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t save the customer.')); } $this->session->setCustomerFormData($this->getRequest()->getPostValue()); return $resultRedirect->setPath('*/*/edit'); } return $resultRedirect->setPath('*/*/edit'); }
/** * Share wishlist * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->_formKeyValidator->validate($this->getRequest())) { $resultRedirect->setPath('*/*/'); return $resultRedirect; } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } $sharingLimit = $this->_wishlistConfig->getSharingEmailLimit(); $textLimit = $this->_wishlistConfig->getSharingTextLimit(); $emailsLeft = $sharingLimit - $wishlist->getShared(); $emails = $this->getRequest()->getPost('emails'); $emails = empty($emails) ? $emails : explode(',', $emails); $error = false; $message = (string) $this->getRequest()->getPost('message'); if (strlen($message) > $textLimit) { $error = __('Message length must not exceed %1 symbols', $textLimit); } else { $message = nl2br(htmlspecialchars($message)); if (empty($emails)) { $error = __('Please enter an email address.'); } else { if (count($emails) > $emailsLeft) { $error = __('This wish list can be shared %1 more times.', $emailsLeft); } else { foreach ($emails as $index => $email) { $email = trim($email); if (!\Zend_Validate::is($email, 'EmailAddress')) { $error = __('Please input a valid email address.'); break; } $emails[$index] = $email; } } } } if ($error) { $this->messageManager->addError($error); $this->wishlistSession->setSharingForm($this->getRequest()->getPostValue()); $resultRedirect->setPath('*/*/share'); return $resultRedirect; } /** @var \Magento\Framework\View\Result\Layout $resultLayout */ $resultLayout = $this->resultFactory->create(ResultFactory::TYPE_LAYOUT); $this->addLayoutHandles($resultLayout); $this->inlineTranslation->suspend(); $sent = 0; try { $customer = $this->_customerSession->getCustomerDataObject(); $customerName = $this->_customerHelperView->getCustomerName($customer); $message .= $this->getRssLink($wishlist->getId(), $resultLayout); $emails = array_unique($emails); $sharingCode = $wishlist->getSharingCode(); try { foreach ($emails as $email) { $transport = $this->_transportBuilder->setTemplateIdentifier($this->scopeConfig->getValue('wishlist/email/email_template', \Magento\Store\Model\ScopeInterface::SCOPE_STORE))->setTemplateOptions(['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $this->storeManager->getStore()->getStoreId()])->setTemplateVars(['customer' => $customer, 'customerName' => $customerName, 'salable' => $wishlist->isSalable() ? 'yes' : '', 'items' => $this->getWishlistItems($resultLayout), 'viewOnSiteLink' => $this->_url->getUrl('*/shared/index', ['code' => $sharingCode]), 'message' => $message, 'store' => $this->storeManager->getStore()])->setFrom($this->scopeConfig->getValue('wishlist/email/email_identity', \Magento\Store\Model\ScopeInterface::SCOPE_STORE))->addTo($email)->getTransport(); $transport->sendMessage(); $sent++; } } catch (\Exception $e) { $wishlist->setShared($wishlist->getShared() + $sent); $wishlist->save(); throw $e; } $wishlist->setShared($wishlist->getShared() + $sent); $wishlist->save(); $this->inlineTranslation->resume(); $this->_eventManager->dispatch('wishlist_share', ['wishlist' => $wishlist]); $this->messageManager->addSuccess(__('Your wish list has been shared.')); $resultRedirect->setPath('*/*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; } catch (\Exception $e) { $this->inlineTranslation->resume(); $this->messageManager->addError($e->getMessage()); $this->wishlistSession->setSharingForm($this->getRequest()->getPostValue()); $resultRedirect->setPath('*/*/share'); return $resultRedirect; } }
/** * Update wishlist item comments * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->_formKeyValidator->validate($this->getRequest())) { $resultRedirect->setPath('*/*/'); return $resultRedirect; } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } $post = $this->getRequest()->getPostValue(); if ($post && isset($post['description']) && is_array($post['description'])) { $updatedItems = 0; foreach ($post['description'] as $itemId => $description) { $item = $this->_objectManager->create('Magento\\Wishlist\\Model\\Item')->load($itemId); if ($item->getWishlistId() != $wishlist->getId()) { continue; } // Extract new values $description = (string) $description; if ($description == $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->defaultCommentString()) { $description = ''; } elseif (!strlen($description)) { $description = $item->getDescription(); } $qty = null; if (isset($post['qty'][$itemId])) { $qty = $this->quantityProcessor->process($post['qty'][$itemId]); } if ($qty === null) { $qty = $item->getQty(); if (!$qty) { $qty = 1; } } elseif (0 == $qty) { try { $item->delete(); } catch (\Exception $e) { $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); $this->messageManager->addError(__('Can\'t delete item from wishlist')); } } // Check that we need to save if ($item->getDescription() == $description && $item->getQty() == $qty) { continue; } try { $item->setDescription($description)->setQty($qty)->save(); $updatedItems++; } catch (\Exception $e) { $this->messageManager->addError(__('Can\'t save description %1', $this->_objectManager->get('Magento\\Framework\\Escaper')->escapeHtml($description))); } } // save wishlist model for setting date of last update if ($updatedItems) { try { $wishlist->save(); $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); } catch (\Exception $e) { $this->messageManager->addError(__('Can\'t update wish list')); } } if (isset($post['save_and_share'])) { $resultRedirect->setPath('*/*/share', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; } } $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; }
/** * @param string $formKey * @param bool $expected * @dataProvider validateDataProvider */ public function testValidate($formKey, $expected) { $this->_requestMock->expects($this->once())->method('getParam')->with('form_key', null)->will($this->returnValue($formKey)); $this->_formKeyMock->expects($this->once())->method('getFormKey')->will($this->returnValue('formKey')); $this->assertEquals($expected, $this->_model->validate($this->_requestMock)); }
/** * @return \Magento\Framework\App\ResponseInterface */ public function execute() { if (!$this->formKeyValidator->validate($this->getRequest()) or !$this->customerSession->getConnectorContactId()) { return $this->_redirect('customer/account/'); } //params $additionalSubscriptions = $this->getRequest()->getParam('additional_subscriptions'); $paramDataFields = $this->getRequest()->getParam('data_fields'); $customerId = $this->customerSession->getConnectorContactId(); $customerEmail = $this->customerSession->getCustomer()->getEmail(); //client $website = $this->customerSession->getCustomer()->getStore()->getWebsite(); //if enabled if ($this->helper->isEnabled($website)) { $client = $this->helper->getWebsiteApiClient($website); $client->setApiUsername($this->helper->getApiUsername($website))->setApiPassword($this->helper->getApiPassword($website)); $contact = $client->getContactById($customerId); if (isset($contact->id)) { //contact address books $bookError = false; $addressBooks = $client->getContactAddressBooks($contact->id); $subscriberAddressBook = $this->helper->getSubscriberAddressBook($website); $processedAddressBooks = []; if (is_array($addressBooks)) { foreach ($addressBooks as $addressBook) { if ($subscriberAddressBook != $addressBook->id) { $processedAddressBooks[$addressBook->id] = $addressBook->name; } } } if (isset($additionalSubscriptions)) { foreach ($additionalSubscriptions as $additionalSubscription) { if (!isset($processedAddressBooks[$additionalSubscription])) { $bookResponse = $client->postAddressBookContacts($additionalSubscription, $contact); if (isset($bookResponse->message)) { $bookError = true; } } } foreach ($processedAddressBooks as $bookId => $name) { if (!in_array($bookId, $additionalSubscriptions)) { $bookResponse = $client->deleteAddressBookContact($bookId, $contact->id); if (isset($bookResponse->message)) { $bookError = true; } } } } else { foreach ($processedAddressBooks as $bookId => $name) { $bookResponse = $client->deleteAddressBookContact($bookId, $contact->id); if (isset($bookResponse->message)) { $bookError = true; } } } //contact data fields $data = []; $dataFields = $client->getDataFields(); $processedFields = []; foreach ($dataFields as $dataField) { $processedFields[$dataField->name] = $dataField->type; } foreach ($paramDataFields as $key => $value) { if (isset($processedFields[$key]) && $value) { if ($processedFields[$key] == 'Numeric') { $paramDataFields[$key] = (int) $value; } if ($processedFields[$key] == 'String') { $paramDataFields[$key] = (string) $value; } if ($processedFields[$key] == 'Date') { $paramDataFields[$key] = $this->localeDate->date($value)->format(\Zend_Date::ISO_8601); } $data[] = ['Key' => $key, 'Value' => $paramDataFields[$key]]; } } $contactResponse = $client->updateContactDatafieldsByEmail($customerEmail, $data); if (isset($contactResponse->message) && $bookError) { $this->messageManager->addErrorMessage(__('An error occurred while saving your subscription preferences.')); } else { $this->messageManager->addSuccessMessage(__('The subscription preferences has been saved.')); } } else { $this->messageManager->addErrorMessage(__('An error occurred while saving your subscription preferences.')); } } $this->_redirect('customer/account/'); }
/** * Add wishlist item to shopping cart and remove from wishlist * * If Product has required options - item removed from wishlist and redirect * to product view page with message about needed defined required options * * @return \Magento\Framework\Controller\ResultInterface * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/*/'); } $itemId = (int) $this->getRequest()->getParam('item'); /* @var $item \Magento\Wishlist\Model\Item */ $item = $this->itemFactory->create()->load($itemId); if (!$item->getId()) { $resultRedirect->setPath('*/*'); return $resultRedirect; } $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId()); if (!$wishlist) { $resultRedirect->setPath('*/*'); return $resultRedirect; } // Set qty $qty = $this->getRequest()->getParam('qty'); if (is_array($qty)) { if (isset($qty[$itemId])) { $qty = $qty[$itemId]; } else { $qty = 1; } } $qty = $this->quantityProcessor->process($qty); if ($qty) { $item->setQty($qty); } $redirectUrl = $this->_url->getUrl('*/*'); $configureUrl = $this->_url->getUrl('*/*/configure/', ['id' => $item->getId(), 'product_id' => $item->getProductId()]); try { /** @var \Magento\Wishlist\Model\ResourceModel\Item\Option\Collection $options */ $options = $this->optionFactory->create()->getCollection()->addItemFilter([$itemId]); $item->setOptions($options->getOptionsByItem($itemId)); $buyRequest = $this->productHelper->addParamsToBuyRequest($this->getRequest()->getParams(), ['current_config' => $item->getBuyRequest()]); $item->mergeBuyRequest($buyRequest); $item->addToCart($this->cart, true); $this->cart->save()->getQuote()->collectTotals(); $wishlist->save(); if (!$this->cart->getQuote()->getHasError()) { $message = __('You added %1 to your shopping cart.', $this->escaper->escapeHtml($item->getProduct()->getName())); $this->messageManager->addSuccess($message); } if ($this->cartHelper->getShouldRedirectToCart()) { $redirectUrl = $this->cartHelper->getCartUrl(); } else { $refererUrl = $this->_redirect->getRefererUrl(); if ($refererUrl && $refererUrl != $configureUrl) { $redirectUrl = $refererUrl; } } } catch (ProductException $e) { $this->messageManager->addError(__('This product(s) is out of stock.')); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addNotice($e->getMessage()); $redirectUrl = $configureUrl; } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t add the item to the cart right now.')); } $this->helper->calculate(); if ($this->getRequest()->isAjax()) { /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); $resultJson->setData(['backUrl' => $redirectUrl]); return $resultJson; } $resultRedirect->setUrl($redirectUrl); return $resultRedirect; }