/** * Register form key in session from cookie value * * @return void */ public function execute() { $formKeyFromCookie = $this->_formKey->get(); if ($formKeyFromCookie) { $this->_session->setData(\Magento\Framework\Data\Form\FormKey::FORM_KEY, $this->_escaper->escapeHtml($formKeyFromCookie)); } }
/** * Initiate a session for unregistered users. Send back the session id. * * @return void */ public function execute() { $this->session->start('frontend'); $this->session->setUserId(0); $this->session->setUserType(UserIdentifier::USER_TYPE_GUEST); $this->session->regenerateId(true); }
/** * @param \Magento\Framework\App\Helper\Context $context * @param \Magento\Customer\Model\Session $customerSession * @param CustomerViewHelper $customerViewHelper * @param \Magento\Framework\Session\Generic $testimonialSession */ public function __construct(\Magento\Framework\App\Helper\Context $context, \Magento\Customer\Model\Session $customerSession, CustomerViewHelper $customerViewHelper, \Magento\Framework\Session\Generic $testimonialSession) { $this->_customerSession = $customerSession; $this->_customerViewHelper = $customerViewHelper; $this->_data = $testimonialSession->getFormData(true); parent::__construct($context); }
/** * Saves payment information in quote * * @param Object $response * @return void */ public function savePaymentInQuote($response) { $quote = $this->quoteRepository->get($this->sessionTransparent->getQuoteId()); /** @var InfoInterface $payment */ $payment = $this->paymentManagement->get($quote->getId()); $payment->setAdditionalInformation('pnref', $response->getPnref()); $this->errorHandler->handle($payment, $response); $this->paymentManagement->set($quote->getId(), $payment); }
public function testExecute() { //Data $formKey = '<asdfaswqrwqe12>'; $escapedFormKey = 'asdfaswqrwqe12'; //Verification $this->_formKey->expects($this->once())->method('get')->will($this->returnValue($formKey)); $this->_escaper->expects($this->once())->method('escapeHtml')->with($formKey)->will($this->returnValue($escapedFormKey)); $this->_session->expects($this->once())->method('setData')->with(\Magento\Framework\Data\Form\FormKey::FORM_KEY, $escapedFormKey); $this->_model->execute(); }
/** * @param \Magento\Framework\Event\Observer $observer * @return $this */ public function bindLocale($observer) { $locale = $observer->getEvent()->getLocale(); if ($locale) { $choosedLocale = $this->_session->getLocale(); if ($choosedLocale) { $locale->setLocaleCode($choosedLocale); } } return $this; }
/** * Retrieve Entered Data by key * * @param string $key * @return string|null */ public function getEnteredData($key) { if ($this->_enteredData === null) { $this->_enteredData = $this->_wishlistSession->getData('sharing_form', true); } if (!$this->_enteredData || !isset($this->_enteredData[$key])) { return null; } else { return $this->escapeHtml($this->_enteredData[$key]); } }
/** * Send request to PayfloPro gateway for get Secure Token * * @return ResultInterface */ public function execute() { $this->sessionTransparent->setQuoteId($this->sessionManager->getQuote()->getId()); $token = $this->secureTokenService->requestToken($this->sessionManager->getQuote()); $result = []; $result[$this->transparent->getCode()]['fields'] = $token->getData(); $result['success'] = $token->getSecuretoken() ? true : false; if (!$result['success']) { $result['error'] = true; $result['error_messages'] = __('Secure Token Error. Try again.'); } return $this->resultJsonFactory->create()->setData($result); }
/** * Retrieve configuration form data object * * @return \Magento\Framework\Object */ public function getFormData() { $data = $this->getData('form_data'); if (is_null($data)) { $data = $this->_session->getConfigData(true); if (empty($data)) { $data = $this->_installerConfig->getFormData(); } else { $data = new \Magento\Framework\Object($data); } $this->setFormData($data); } return $data; }
public function testSavePaymentInQuote() { $quoteId = 1; $response = new DataObject(); $payment = $this->getMockBuilder('Magento\\Quote\\Model\\Quote\\Payment')->disableOriginalConstructor()->getMock(); $payment->expects($this->once())->method('setAdditionalInformation')->with('pnref'); $this->errorHandlerMock->expects($this->once())->method('handle')->with($payment, $response); $quote = $this->getMock('Magento\\Quote\\Api\\Data\\CartInterface', [], [], '', false); $quote->expects($this->exactly(2))->method('getId')->willReturn($quoteId); $this->sessionTransparent->expects($this->once())->method('getQuoteId')->willReturn($quoteId); $this->quoteRepository->expects($this->once())->method('get')->willReturn($quote); $this->paymentMethodManagementInterface->expects($this->once())->method('get')->willReturn($payment); $this->paymentMethodManagementInterface->expects($this->once())->method('set'); $this->model->savePaymentInQuote($response); }
/** * Check CAPTCHA on New Testmonial page * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { $formId = 'testimonial_new'; $captcha = $this->_helper->getCaptcha($formId); if ($captcha->isRequired()) { /** @var \Magento\Framework\App\Action\Action $controller */ $controller = $observer->getControllerAction(); if (!$captcha->isCorrect($this->captchaStringResolver->resolve($controller->getRequest(), $formId))) { $this->_testimonialSession->setFormData($controller->getRequest()->getPost()); $this->messageManager->addError(__('Incorrect CAPTCHA.')); $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true); $this->redirect->redirect($controller->getResponse(), $this->redirect->getRefererUrl()); } } }
/** * Login registered users and initiate a session. Send back the session id. * * Expects a POST. ex for JSON {"username":"******", "password":"******"} * * @return void */ public function execute() { $contentTypeHeaderValue = $this->getRequest()->getHeader('Content-Type'); $contentType = $this->getContentType($contentTypeHeaderValue); $loginData = null; try { $loginData = $this->deserializerFactory->get($contentType)->deserialize($this->getRequest()->getRawBody()); } catch (Exception $e) { $this->getResponse()->setHttpResponseCode($e->getCode()); return; } if (!$loginData || $this->getRequest()->getMethod() !== \Magento\Webapi\Model\Rest\Config::HTTP_METHOD_POST) { $this->getResponse()->setHttpResponseCode(HttpException::HTTP_BAD_REQUEST); return; } $customerData = null; try { $customerData = $this->customerAccountService->authenticate($loginData['username'], $loginData['password']); } catch (AuthenticationException $e) { $this->getResponse()->setHttpResponseCode(HttpException::HTTP_UNAUTHORIZED); return; } $this->session->start('frontend'); $this->session->setUserId($customerData->getId()); $this->session->setUserType(UserIdentifier::USER_TYPE_CUSTOMER); $this->session->regenerateId(true); }
/** * Set up before test * * @return void * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function setUp() { $this->_objectManager = new \Magento\TestFramework\Helper\ObjectManager($this); $this->_installerMock = $this->getMock('\\Magento\\Install\\Model\\Installer', array('isApplicationInstalled'), array(), '', false); $this->_installerMock->expects($this->any())->method('isApplicationInstalled')->will($this->returnValue(true)); $this->_blockMock = $this->getMock('\\Magento\\Install\\Block\\Locale', array(), array(), '', false); $this->_layoutMock = $this->getMock('\\Magento\\Framework\\View\\Layout', array('getBlock', 'initMessages', 'addBlock'), array(), '', false); $this->_layoutMock->expects($this->any())->method('initMessages')->withAnyParameters()->will($this->returnValue(true)); $this->_layoutMock->expects($this->any())->method('addBlock')->withAnyParameters()->will($this->returnValue(true)); $this->_viewMock = $this->getMockForAbstractClass('\\Magento\\Framework\\App\\ViewInterface', array(), '', false, false, true, array('getLayout')); $this->_viewMock->expects($this->any())->method('getLayout')->withAnyParameters()->will($this->returnValue($this->_layoutMock)); $this->_requestMock = $this->_getClearMock('\\Magento\\Framework\\App\\RequestInterface'); $this->_responseMock = $this->_getClearMock('\\Magento\\Framework\\App\\ResponseInterface'); $this->_actionFlagMock = $this->_getClearMock('\\Magento\\Framework\\App\\ActionFlag'); $this->_contextMock = $this->getMock('\\Magento\\Framework\\App\\Action\\Context', array('getView', 'getRequest', 'getResponse', 'getActionFlag'), array(), '', false); $this->_contextMock->expects($this->any())->method('getView')->will($this->returnValue($this->_viewMock)); $this->_contextMock->expects($this->any())->method('getRequest')->will($this->returnValue($this->_requestMock)); $this->_contextMock->expects($this->any())->method('getResponse')->will($this->returnValue($this->_responseMock)); $this->_contextMock->expects($this->any())->method('getActionFlag')->will($this->returnValue($this->_actionFlagMock)); $this->_blockContextMock = $this->getMock('\\Magento\\Framework\\View\\Element\\Template\\Context', array(), array(), '', false); $this->_wizardMock = $this->getMock('\\Magento\\Install\\Model\\Wizard', array('getStepByRequest'), array(), '', false); $this->_wizardMock->expects($this->any())->method('getStepByRequest')->withAnyParameters()->will($this->returnValue(false)); $this->_sessionMock = $this->getMock('\\Magento\\Framework\\Session\\Generic', array('getLocale'), array(), '', false); $this->_sessionMock->expects($this->any())->method('getLocale')->will($this->returnValue(self::LOCALE)); $this->_block = $this->_objectManager->getObject('Magento\\Install\\Block\\Locale', array('context' => $this->_blockContextMock, 'installer' => $this->_installerMock, 'installWizard' => $this->_wizardMock, 'session' => $this->_sessionMock, 'data' => array())); $this->_layoutMock->expects($this->any())->method('getBlock')->with('install.locale')->will($this->returnValue($this->_block)); $this->_controller = $this->_objectManager->getObject('Magento\\Install\\Controller\\Wizard\\Locale', array('context' => $this->_contextMock, 'configScope' => $this->_getClearMock('Magento\\Framework\\Config\\Scope'), 'installer' => $this->_getClearMock('Magento\\Install\\Model\\Installer'), 'wizard' => $this->_wizardMock, 'session' => $this->_sessionMock, 'dbUpdater' => $this->_getClearMock('Magento\\Framework\\Module\\UpdaterInterface'), 'storeManager' => $this->_getClearMock('Magento\\Store\\Model\\StoreManagerInterface'), 'appState' => $this->_getClearMock('Magento\\Framework\\App\\State'))); }
public function testGetSessionIdQueryParamCustom() { $oldSessionName = $this->session->getName(); $this->session->setName($this->customSessionName); $this->assertEquals($this->customSessionQueryParam, $this->model->getSessionIdQueryParam($this->session)); $this->session->setName($oldSessionName); }
public function testSessionUrlVarWithoutMatchedHostsAndBaseUrl() { $requestMock = $this->getRequestMock(); $model = $this->getUrlModel( [ 'session' => $this->sessionMock, 'request' => $requestMock, 'sidResolver' => $this->sidResolverMock, 'scopeResolver' => $this->scopeResolverMock, 'routeParamsResolverFactory' => $this->getRouteParamsResolverFactory(), ] ); $requestMock->expects($this->once())->method('getHttpHost')->will($this->returnValue('localhost')); $this->scopeMock->expects($this->once()) ->method('getBaseUrl') ->will($this->returnValue('http://example.com')); $this->scopeResolverMock->expects($this->any()) ->method('getScope') ->will($this->returnValue($this->scopeMock)); $this->sidResolverMock->expects($this->once())->method('getSessionIdQueryParam') ->will($this->returnValue('SID')); $this->sessionMock->expects($this->once())->method('getSessionId') ->will($this->returnValue('session-id')); $this->assertEquals( '<a href="http://example.com/?SID=session-id">www.example.com</a>', $model->sessionUrlVar('<a href="http://example.com/?___SID=U">www.example.com</a>') ); }
/** * Register form key in session from cookie value * * @param \Magento\Framework\Event\Observer $observer * @return void * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function registerFormKeyFromCookie(\Magento\Framework\Event\Observer $observer) { $formKeyFromCookie = $this->_formKey->get(); if ($formKeyFromCookie) { $this->_session->setData(\Magento\Framework\Data\Form\FormKey::FORM_KEY, $this->_escaper->escapeHtml($formKeyFromCookie)); } }
/** * Run test execute method * * @param array $result * @param array $resultExpectation * * @dataProvider executeDataProvider */ public function testExecute(array $result, array $resultExpectation) { $quoteId = 99; $quoteMock = $this->getMockBuilder('Magento\\Quote\\Model\\Quote')->disableOriginalConstructor()->getMock(); $tokenMock = $this->getMockBuilder('Magento\\Framework\\Object')->setMethods(['getData', 'getSecuretoken'])->disableOriginalConstructor()->getMock(); $jsonMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Json')->disableOriginalConstructor()->getMock(); $this->transparentMock->expects($this->once())->method('getCode')->willReturn('transparent'); $this->sessionManagerMock->expects($this->atLeastOnce())->method('getQuote')->willReturn($quoteMock); $quoteMock->expects($this->once())->method('getId')->willReturn($quoteId); $this->sessionTransparentMock->expects($this->once())->method('setQuoteId')->with($quoteId); $this->secureTokenServiceMock->expects($this->once())->method('requestToken')->with($quoteMock)->willReturn($tokenMock); $this->transparentMock->expects($this->once())->method('getCode')->willReturn('transparent'); $tokenMock->expects($this->once())->method('getData')->willReturn($result['transparent']['fields']); $tokenMock->expects($this->once())->method('getSecuretoken')->willReturn($result['success']); $this->resultJsonFactoryMock->expects($this->once())->method('create')->willReturn($jsonMock); $jsonMock->expects($this->once())->method('setData')->with($resultExpectation)->willReturnSelf(); $this->assertEquals($jsonMock, $this->controller->execute()); }
/** * Send request to PayfloPro gateway for get Secure Token * * @return ResultInterface */ public function executeInternal() { /** @var Quote $quote */ $quote = $this->sessionManager->getQuote(); if (!$quote or !$quote instanceof Quote) { return $this->getErrorResponse(); } $this->sessionTransparent->setQuoteId($quote->getId()); try { $token = $this->secureTokenService->requestToken($quote); if (!$token->getData('securetoken')) { throw new \LogicException(); } return $this->resultJsonFactory->create()->setData([$this->transparent->getCode() => ['fields' => $token->getData()], 'success' => true, 'error' => false]); } catch (\Exception $e) { return $this->getErrorResponse(); } }
public function testToHtmlCoreRegistryRatingData() { $this->registry->expects($this->any())->method('registry')->will($this->returnValue($this->rating)); $this->form->expects($this->at(7))->method('getElement')->will($this->returnValue($this->element)); $this->form->expects($this->at(13))->method('getElement')->will($this->returnValue($this->element)); $this->form->expects($this->at(16))->method('getElement')->will($this->returnValue($this->element)); $this->form->expects($this->at(17))->method('getElement')->will($this->returnValue($this->element)); $this->form->expects($this->any())->method('getElement')->will($this->returnValue(false)); $this->session->expects($this->any())->method('getRatingData')->will($this->returnValue(false)); $ratingCodes = ['rating_codes' => ['0' => 'rating_code']]; $this->rating->expects($this->any())->method('getRatingCodes')->will($this->returnValue($ratingCodes)); $this->block->toHtml(); }
public function testExecuteTokenRequestException() { $quoteId = 99; $resultExpectation = ['success' => false, 'error' => true, 'error_messages' => __('Your payment has been declined. Please try again.')]; $quoteMock = $this->getMockBuilder('Magento\\Quote\\Model\\Quote')->disableOriginalConstructor()->getMock(); $jsonMock = $this->getMockBuilder('Magento\\Framework\\Controller\\Result\\Json')->disableOriginalConstructor()->getMock(); $this->sessionManagerMock->expects($this->atLeastOnce())->method('getQuote')->willReturn($quoteMock); $quoteMock->expects($this->once())->method('getId')->willReturn($quoteId); $this->sessionTransparentMock->expects($this->once())->method('setQuoteId')->with($quoteId); $this->secureTokenServiceMock->expects($this->once())->method('requestToken')->with($quoteMock)->willThrowException(new \Exception()); $this->resultJsonFactoryMock->expects($this->once())->method('create')->willReturn($jsonMock); $jsonMock->expects($this->once())->method('setData')->with($resultExpectation)->willReturnSelf(); $this->assertEquals($jsonMock, $this->controller->execute()); }
public function testAfterGenerateXmlNoDepersonalize() { $expectedResult = $this->getMock('Magento\\Framework\\View\\Layout', [], [], '', false); $this->depersonalizeCheckerMock->expects($this->once())->method('checkIfDepersonalize')->willReturn(false); $this->visitorMock->expects($this->never())->method('setSkipRequestLogging'); $this->visitorMock->expects($this->never())->method('unsetData'); $this->sessionMock->expects($this->never())->method('clearStorage'); $this->customerSessionMock->expects($this->never())->method('clearStorage'); $this->customerSessionMock->expects($this->never())->method('setCustomerGroupId'); $this->customerMock->expects($this->never())->method('setGroupId'); $this->sessionMock->expects($this->never())->method('setData'); $this->customerSessionMock->expects($this->never())->method('setCustomer'); $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $expectedResult); $this->assertSame($expectedResult, $actualResult); }
/** * Dispatch request * * @param RequestInterface $request * @return \Magento\Framework\App\ResponseInterface */ public function dispatch(RequestInterface $request) { $allowGuest = $this->_objectManager->get('Magento\\Review\\Helper\\Data')->getIsGuestAllowToWrite(); if (!$request->isDispatched()) { return parent::dispatch($request); } if (!$allowGuest && $request->getActionName() == 'post' && $request->isPost()) { if (!$this->_customerSession->isLoggedIn()) { $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); $this->_customerSession->setBeforeAuthUrl($this->_url->getUrl('*/*/*', ['_current' => true])); $this->_reviewSession->setFormData($request->getPostValue())->setRedirectUrl($this->_redirect->getRefererUrl()); $this->getResponse()->setRedirect($this->_objectManager->get('Magento\\Customer\\Model\\Url')->getLoginUrl()); } } return parent::dispatch($request); }
/** * Authenticate controller action by login customer * * @param bool|null $loginUrl * @return bool */ public function authenticate($loginUrl = null) { if ($this->isLoggedIn()) { return true; } $this->setBeforeAuthUrl($this->_createUrl()->getUrl('*/*/*', ['_current' => true])); if (isset($loginUrl)) { $this->response->setRedirect($loginUrl); } else { $arguments = $this->_customerUrl->getLoginUrlParams(); if ($this->_session->getCookieShouldBeReceived() && $this->_createUrl()->getUseSession()) { $arguments += ['_query' => [$this->sidResolver->getSessionIdQueryParam($this->_session) => $this->_session->getSessionId()]]; } $this->response->setRedirect($this->_createUrl()->getUrl(\Magento\Customer\Model\Url::ROUTE_ACCOUNT_LOGIN, $arguments)); } return false; }
/** * Authenticate controller action by login customer * * @param \Magento\Framework\App\Action\Action $action * @param bool|null $loginUrl * @return bool */ public function authenticate(\Magento\Framework\App\Action\Action $action, $loginUrl = null) { if ($this->isLoggedIn()) { return true; } $this->setBeforeAuthUrl($this->_createUrl()->getUrl('*/*/*', array('_current' => true))); if (isset($loginUrl)) { $action->getResponse()->setRedirect($loginUrl); } else { $arguments = $this->_customerData->getLoginUrlParams(); if ($this->_session->getCookieShouldBeReceived() && $this->_createUrl()->getUseSession()) { $arguments += array('_query' => array($this->sidResolver->getSessionIdQueryParam($this->_session) => $this->_session->getSessionId())); } $action->getResponse()->setRedirect($this->_createUrl()->getUrl(\Magento\Customer\Helper\Data::ROUTE_ACCOUNT_LOGIN, $arguments)); } return false; }
/** * Test method afterGenerateXml with enabled module PageCache */ public function testAfterGenerateXmlPageCacheEnabled() { $expectedResult = $this->getMock('Magento\\Framework\\View\\Layout', array(), array(), '', false); $this->moduleManagerMock->expects($this->once())->method('isEnabled')->with('Magento_PageCache')->will($this->returnValue(true)); $this->cacheConfigMock->expects($this->once())->method('isEnabled')->will($this->returnValue(true)); $this->requestMock->expects($this->once())->method('isAjax')->will($this->returnValue(false)); $this->layoutMock->expects($this->once())->method('isCacheable')->will($this->returnValue(true)); $this->visitorMock->expects($this->once())->method('setSkipRequestLogging')->with($this->equalTo(true)); $this->visitorMock->expects($this->once())->method('unsetData'); $this->sessionMock->expects($this->once())->method('clearStorage'); $this->customerSessionMock->expects($this->once())->method('clearStorage'); $this->customerSessionMock->expects($this->once())->method('setCustomerGroupId')->with($this->equalTo(null)); $this->customerMock->expects($this->once())->method('setGroupId')->with($this->equalTo(null)); $this->sessionMock->expects($this->once())->method('setData')->with($this->equalTo(\Magento\Framework\Data\Form\FormKey::FORM_KEY), $this->equalTo(null)); $this->customerSessionMock->expects($this->once())->method('setCustomer')->with($this->equalTo($this->customerMock)); $actualResult = $this->plugin->afterGenerateXml($this->layoutMock, $expectedResult); $this->assertSame($expectedResult, $actualResult); }
/** * Save user testimonial * * @return void * @throws \Exception */ public function execute() { $post = $this->getRequest()->getPostValue(); if (!$post) { $this->_redirectReferer(); return; } try { $error = false; if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) { $error = true; } if (!\Zend_Validate::is(trim($post['message']), 'NotEmpty')) { $error = true; } if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) { $error = true; } if ($error) { throw new \Exception(); } $post['store_id'] = $this->_storeManager->getStore()->getId(); $post['status'] = $this->_configHelper->isAutoApprove() ? TestimonialsModel::STATUS_ENABLED : TestimonialsModel::STATUS_AWAITING_APPROVAL; $model = $this->_objectManager->create('Swissup\\Testimonials\\Model\\Data'); $model->setData($post); $imageName = $this->_uploadModel->uploadFileAndGetName('image', $this->_imageModel->getBaseDir(), $post, ['jpg', 'jpeg', 'gif', 'png', 'bmp']); $model->setImage($imageName); $this->_eventManager->dispatch('testimonials_save_new', ['item' => $model]); $model->save(); $this->messageManager->addSuccess(__($this->_configHelper->getSentMessage())); $this->_redirectReferer(); return; } catch (\Exception $e) { $this->messageManager->addError(__($e->getMessage())); $this->_testimonialSession->setFormData($post)->setRedirectUrl($this->_redirect->getRefererUrl()); $this->_redirectReferer(); return; } }
/** * Replace Session ID value in URL * * @param string $html * @return string */ public function sessionUrlVar($html) { return preg_replace_callback( '#(\?|&|&)___SID=([SU])(&|&)?#', // @codingStandardsIgnoreStart /** * Callback function for session replace * * @param array $match * @return string */ // @codingStandardsIgnoreEnd function ($match) { if ($this->useSessionIdForUrl($match[2] == 'S' ? true : false)) { return $match[1] . $this->_sidResolver->getSessionIdQueryParam($this->_session) . '=' . $this->_session->getSessionId() . (isset($match[3]) ? $match[3] : ''); } else { if ($match[1] == '?') { return isset($match[3]) ? '?' : ''; } elseif ($match[1] == '&' || $match[1] == '&') { return isset($match[3]) ? $match[3] : ''; } } }, $html ); }
/** * 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; } }
protected function tearDown() { $this->customerSession->setCustomerId(null); $this->coreSession->unsData('_form_key'); }
/** * Replace Session ID value in URL * * @param string $html * @return string */ public function sessionUrlVar($html) { return preg_replace_callback('#(\\?|&|&)___SID=([SU])(&|&)?#', function ($match) { if ($this->useSessionIdForUrl($match[2] == 'S' ? true : false)) { return $match[1] . $this->_sidResolver->getSessionIdQueryParam($this->_session) . '=' . $this->_session->getSessionId() . (isset($match[3]) ? $match[3] : ''); } else { if ($match[1] == '?') { return isset($match[3]) ? '?' : ''; } elseif ($match[1] == '&' || $match[1] == '&') { return isset($match[3]) ? $match[3] : ''; } } }, $html); }