/** * @magentoConfigFixture current_store persistent/options/enabled 1 * @magentoConfigFixture current_store persistent/options/remember_enabled 1 * @magentoConfigFixture current_store persistent/options/remember_default 1 * @magentoAppArea frontend * @magentoAppIsolation enabled */ public function testEmulateWelcomeBlock() { $this->_customerSession->loginById(1); $httpContext = new \Magento\Framework\App\Http\Context(); $httpContext->setValue(Context::CONTEXT_AUTH, 1, 1); $block = $this->_objectManager->create('Magento\\Sales\\Block\\Reorder\\Sidebar', ['httpContext' => $httpContext]); $this->_observer->emulateWelcomeBlock($block); $customerName = $this->_escaper->escapeHtml($this->_customerViewHelper->getCustomerName($this->customerRepository->getById($this->_persistentSessionHelper->getSession()->getCustomerId()))); $translation = __('Welcome, %1!', $customerName); $this->assertStringMatchesFormat('%A' . $translation . '%A', $block->getWelcome()); $this->_customerSession->logout(); }
/** * 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)); } }
/** * Get data * * @param array $item * @return string */ protected function prepareItem(array $item) { $content = ''; $origStores = $item['store_id']; if (empty($origStores)) { return ''; } if (!is_array($origStores)) { $origStores = [$origStores]; } if (in_array(0, $origStores) && count($origStores) == 1) { return __('All Store Views'); } $data = $this->systemStore->getStoresStructure(false, $origStores); foreach ($data as $website) { $content .= $website['label'] . "<br/>"; foreach ($website['children'] as $group) { $content .= str_repeat(' ', 3) . $this->escaper->escapeHtml($group['label']) . "<br/>"; foreach ($group['children'] as $store) { $content .= str_repeat(' ', 6) . $this->escaper->escapeHtml($store['label']) . "<br/>"; } } } return $content; }
/** * Forgot customer password action * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultRedirectFactory->create(); $email = (string) $this->getRequest()->getPost('email'); if ($email) { if (!\Zend_Validate::is($email, 'EmailAddress')) { $this->_getSession()->setForgottenEmail($email); $this->messageManager->addError(__('Please correct the email address.')); $resultRedirect->setPath('*/*/forgotpassword'); return $resultRedirect; } try { $this->customerAccountManagement->initiatePasswordReset($email, AccountManagement::EMAIL_RESET); } catch (NoSuchEntityException $e) { // Do nothing, we don't want anyone to use this action to determine which email accounts are registered. } catch (\Exception $exception) { $this->messageManager->addException($exception, __('Unable to send password reset email.')); $resultRedirect->setPath('*/*/forgotpassword'); return $resultRedirect; } $email = $this->escaper->escapeHtml($email); // @codingStandardsIgnoreStart $this->messageManager->addSuccess(__('If there is an account associated with %1 you will receive an email with a link to reset your password.', $email)); // @codingStandardsIgnoreEnd $resultRedirect->setPath('*/*/'); return $resultRedirect; } else { $this->messageManager->addError(__('Please enter your email.')); $resultRedirect->setPath('*/*/forgotpassword'); return $resultRedirect; } }
/** * Register form key in session from cookie value * * @param \Magento\Framework\Event\Observer $observer * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute(\Magento\Framework\Event\Observer $observer) { if ($this->cookieFormKey->get()) { $this->updateCookieFormKey($this->cookieFormKey->get()); $this->sessionFormKey->set($this->escaper->escapeHtml($this->cookieFormKey->get())); } }
/** * Add shared wishlist item to shopping cart * * If Product has required options - redirect * to product view page with message about needed defined required options * * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { $itemId = (int) $this->getRequest()->getParam('item'); /* @var $item Item */ $item = $this->itemFactory->create()->load($itemId); $redirectUrl = $this->_redirect->getRefererUrl(); try { /** @var OptionCollection $options */ $options = $this->optionFactory->create()->getCollection()->addItemFilter([$itemId]); $item->setOptions($options->getOptionsByItem($itemId)); $item->addToCart($this->cart); $this->cart->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(); } } catch (ProductException $e) { $this->messageManager->addError(__('This product(s) is out of stock.')); } catch (LocalizedException $e) { $this->messageManager->addNotice($e->getMessage()); $redirectUrl = $item->getProductUrl(); } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t add the item to the cart right now.')); } /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $resultRedirect->setUrl($redirectUrl); return $resultRedirect; }
/** * get toooltip title * * @param bool $escaped * @return string */ public function getTitle($escaped = true) { if ($escaped) { return $this->escaper->escapeHtml($this->title); } return $this->title; }
/** * Generate current options * * @return void */ protected function generateCurrentOptions() { $websiteCollection = $this->systemStore->getWebsiteCollection(); $groupCollection = $this->systemStore->getGroupCollection(); $storeCollection = $this->systemStore->getStoreCollection(); /** @var \Magento\Store\Model\Website $website */ foreach ($websiteCollection as $website) { $groups = []; /** @var \Magento\Store\Model\Group $group */ foreach ($groupCollection as $group) { if ($group->getWebsiteId() == $website->getId()) { $stores = []; /** @var \Magento\Store\Model\Store $store */ foreach ($storeCollection as $store) { if ($store->getGroupId() == $group->getId()) { $name = $this->escaper->escapeHtml($store->getName()); $stores[$name]['label'] = str_repeat(' ', 8) . $name; $stores[$name]['value'] = $store->getId(); } } if (!empty($stores)) { $name = $this->escaper->escapeHtml($group->getName()); $groups[$name]['label'] = str_repeat(' ', 4) . $name; $groups[$name]['value'] = array_values($stores); } } } if (!empty($groups)) { $name = $this->escaper->escapeHtml($website->getName()); $this->currentOptions[$name]['label'] = $name; $this->currentOptions[$name]['value'] = array_values($groups); } } }
/** * Emulate 'welcome' block with persistent data * * @param \Magento\Framework\View\Element\AbstractBlock $block * @return $this */ public function emulateWelcomeBlock($block) { $escapedName = $this->_escaper->escapeHtml($this->_customerViewHelper->getCustomerName($this->customerRepository->getById($this->_persistentSession->getSession()->getCustomerId())), null); $this->_applyAccountLinksPersistentData(); $welcomeMessage = __('Welcome, %1!', $escapedName) . ' ' . $this->_layout->getBlock('header.additional')->toHtml(); $block->setWelcome($welcomeMessage); return $this; }
/** * Prepare Data Source * * @param array $dataSource * @return array */ public function prepareDataSource(array $dataSource) { if (isset($dataSource['data']['items'])) { foreach ($dataSource['data']['items'] as &$item) { $item[$this->getData('name')] = $this->escaper->escapeHtml(str_replace("\n", '<br/>', $item[$this->getData('name')])); } } return $dataSource; }
/** * {@inheritdoc} */ public function process($jsLayout) { $agreementConfiguration = []; $agreementsList = $this->checkoutAgreementsRepository->getList(); foreach ($agreementsList as $agreement) { $agreementConfiguration[] = ['content' => $agreement->getIsHtml() ? $agreement->getContent() : nl2br($this->escaper->escapeHtml($agreement->getContent())), 'height' => $agreement->getContentHeight(), 'checkboxText' => $agreement->getCheckboxText()]; } $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children']['before-place-order']['children']['checkout-agreements-modal']['config']['agreementConfiguration'] = $agreementConfiguration; return $jsLayout; }
/** * Returns agreements config * * @return array */ protected function getAgreementsConfig() { $agreementConfiguration = []; $isAgreementsEnabled = $this->scopeConfiguration->isSetFlag(AgreementsProvider::PATH_ENABLED, ScopeInterface::SCOPE_STORE); $agreementsList = $this->checkoutAgreementsRepository->getList(); $agreementConfiguration['isEnabled'] = (bool) ($isAgreementsEnabled && count($agreementsList) > 0); foreach ($agreementsList as $agreement) { $agreementConfiguration['agreements'][] = ['content' => $agreement->getIsHtml() ? $agreement->getContent() : nl2br($this->escaper->escapeHtml($agreement->getContent())), 'checkboxText' => $agreement->getCheckboxText(), 'mode' => $agreement->getMode(), 'agreementId' => $agreement->getAgreementId()]; } return $agreementConfiguration; }
/** * {@inheritdoc} */ public function process($jsLayout) { $form = []; $agreementsList = $this->checkoutAgreementsRepository->getList(); foreach ($agreementsList as $agreement) { $name = $agreement->getAgreementId(); $form[$name] = ['component' => 'Magento_Ui/js/form/element/abstract', 'config' => ['customScope' => 'checkoutAgreements', 'customEntry' => 'checkoutAgreements.' . $name, 'template' => 'Magento_CheckoutAgreements/form/element/agreement'], 'agreementConfiguration' => ['content' => $agreement->getIsHtml() ? $agreement->getContent() : nl2br($this->escaper->escapeHtml($agreement->getContent())), 'height' => $agreement->getContentHeight(), 'checkboxText' => $agreement->getCheckboxText()], 'dataScope' => $name, 'provider' => 'checkoutProvider', 'validation' => ['checked' => true], 'customEntry' => null, 'visible' => true]; } $result['components']['checkout']['children']['steps']['children']['review']['children']['beforePlaceOrder']['children']['checkoutAgreements']['children'] = $form; return array_merge_recursive($jsLayout, $result); }
/** * Unserialize and clear name prefix or suffix options * * @param string $options * @return array|bool */ protected function _prepareNamePrefixSuffixOptions($options) { $options = trim($options); if (empty($options)) { return false; } $result = []; $options = explode(';', $options); foreach ($options as $value) { $value = $this->escaper->escapeHtml(trim($value)); $result[$value] = $value; } return $result; }
public function execute() { $params = $this->getRequest()->getParams(); /** @var \Magento\Checkout\Model\Cart $cart */ $cart = $this->cartFactory->create(); $successMessage = ''; $websiteId = $this->storeManager->getStore()->getWebsiteId(); foreach ($params as $key => $product) { if ($product && is_array($product)) { $productModel = $this->productFactory->create(); // loadByAttribute() return false if the product was not found. There is no need to check the ID, // but lets stay on the safe side for the future Magento releases /** @var \Magento\Catalog\Model\Product $productBySKU */ $productBySKU = $productModel->loadByAttribute('sku', $product['sku']); if (!$productBySKU || !($productId = $productBySKU->getId())) { continue; } $stockItem = $this->stockItemApiFactory->create(); /** @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item $stockItemResource */ $stockItemResource = $this->stockItemApiResourceFactory->create(); $stockItemResource->loadByProductId($stockItem, $productId, $websiteId); $qty = $stockItem->getQty(); try { if (!$cart->getQuote()->hasProductId($productId) && is_numeric($product['qty']) && $qty > $product['qty']) { $cart->addProduct($productBySKU, (int) $product['qty']); $successMessage .= __('%1 was added to your shopping cart.' . '</br>', $this->escaper->escapeHtml($productBySKU->getName())); } unset($params[$key]); } catch (\Exception $e) { $this->rejoinerHelper->log($e->getMessage()); } } } if (isset($params['coupon_code'])) { $cart->getQuote()->setCouponCode($params['coupon_code'])->collectTotals(); } try { $cart->getQuote()->save(); $cart->save(); } catch (\Exception $e) { $this->rejoinerHelper->log($e->getMessage()); } $this->checkoutSession->setCartWasUpdated(true); if ($successMessage) { $this->messageManager->addSuccess($successMessage); } $url = $this->_url->getUrl('checkout/cart/', ['updateCart' => true]); $this->getResponse()->setRedirect($url); }
/** * Get options * * @return array */ public function toOptionArray() { $currentOptions['']['label'] = '--'; $currentOptions['']['value'] = '--'; $currentOptions['All Store Views']['label'] = __('All Websites'); $currentOptions['All Store Views']['value'] = self::ALL_WEBSITES; $websiteCollection = $this->systemStore->getWebsiteCollection(); foreach ($websiteCollection as $website) { $name = $this->escaper->escapeHtml($website->getName()); $currentOptions[$name]['label'] = $name; $currentOptions[$name]['value'] = $website->getId(); } $this->options = array_values($currentOptions); return $currentOptions; }
/** * Get Links data * * @SuppressWarnings(PHPMD.NPathComplexity) * @return array */ public function getLinksData() { $linksData = []; if ($this->locator->getProduct()->getTypeId() !== Type::TYPE_DOWNLOADABLE) { return $linksData; } $links = $this->locator->getProduct()->getTypeInstance()->getLinks($this->locator->getProduct()); /** @var LinkInterface $link */ foreach ($links as $link) { $linkData = []; $linkData['link_id'] = $link->getId(); $linkData['title'] = $this->escaper->escapeHtml($link->getTitle()); $linkData['price'] = $this->getPriceValue($link->getPrice()); $linkData['number_of_downloads'] = $link->getNumberOfDownloads(); $linkData['is_shareable'] = $link->getIsShareable(); $linkData['link_url'] = $link->getLinkUrl(); $linkData['type'] = $link->getLinkType(); $linkData['sample']['url'] = $link->getSampleUrl(); $linkData['sample']['type'] = $link->getSampleType(); $linkData['sort_order'] = $link->getSortOrder(); $linkData['is_unlimited'] = $linkData['number_of_downloads'] ? '0' : '1'; if ($this->locator->getProduct()->getStoreId()) { $linkData['use_default_price'] = $link->getWebsitePrice() ? '0' : '1'; $linkData['use_default_title'] = $link->getStoreTitle() ? '0' : '1'; } $linkData = $this->addLinkFile($linkData, $link); $linkData = $this->addSampleFile($linkData, $link); $linksData[] = $linkData; } return $linksData; }
/** * Escape string preserving links * * @param string $data * @param null|array $allowedTags * @return string */ public function escapeHtmlWithLinks($data, $allowedTags = null) { if (!empty($data) && is_array($allowedTags) && in_array('a', $allowedTags)) { $links = []; $i = 1; $data = str_replace('%', '%%', $data); $regexp = "/<a\\s[^>]*href\\s*?=\\s*?([\"\\']??)([^\" >]*?)\\1[^>]*>(.*)<\\/a>/siU"; while (preg_match($regexp, $data, $matches)) { //Revert the sprintf escaping $url = str_replace('%%', '%', $matches[2]); $text = str_replace('%%', '%', $matches[3]); //Check for an valid url if ($url) { $urlScheme = strtolower(parse_url($url, PHP_URL_SCHEME)); if ($urlScheme !== 'http' && $urlScheme !== 'https') { $url = null; } } //Use hash tag as fallback if (!$url) { $url = '#'; } //Recreate a minimalistic secure a tag $links[] = sprintf('<a href="%s">%s</a>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8', false), $this->escaper->escapeHtml($text)); $data = str_replace($matches[0], '%' . $i . '$s', $data); ++$i; } $data = $this->escaper->escapeHtml($data, $allowedTags); return vsprintf($data, $links); } return $this->escaper->escapeHtml($data, $allowedTags); }
/** * Add cart item to wishlist and remove from cart * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function execute() { $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.')); } /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); return $resultRedirect->setUrl($this->cartHelper->getCartUrl()); }
/** * Renders CMS page * * @param Action $action * @param int $pageId * @param bool $renderLayout * @return bool */ protected function _renderPage(Action $action, $pageId = null, $renderLayout = true) { if (!is_null($pageId) && $pageId !== $this->_page->getId()) { $delimiterPosition = strrpos($pageId, '|'); if ($delimiterPosition) { $pageId = substr($pageId, 0, $delimiterPosition); } $this->_page->setStoreId($this->_storeManager->getStore()->getId()); if (!$this->_page->load($pageId)) { return false; } } if (!$this->_page->getId()) { return false; } $inRange = $this->_localeDate->isScopeDateInInterval(null, $this->_page->getCustomThemeFrom(), $this->_page->getCustomThemeTo()); if ($this->_page->getCustomTheme()) { if ($inRange) { $this->_design->setDesignTheme($this->_page->getCustomTheme()); } } $this->_view->getLayout()->getUpdate()->addHandle('default')->addHandle('cms_page_view'); $this->_view->addPageLayoutHandles(array('id' => $this->_page->getIdentifier())); $this->_view->addActionLayoutHandles(); if ($this->_page->getRootTemplate()) { if ($this->_page->getCustomRootTemplate() && $this->_page->getCustomRootTemplate() != 'empty' && $inRange) { $handle = $this->_page->getCustomRootTemplate(); } else { $handle = $this->_page->getRootTemplate(); } $this->_pageLayout->applyHandle($handle); } $this->_eventManager->dispatch('cms_page_render', array('page' => $this->_page, 'controller_action' => $action)); $this->_view->loadLayoutUpdates(); if ($this->_page->getCustomLayoutUpdateXml() && $inRange) { $layoutUpdate = $this->_page->getCustomLayoutUpdateXml(); } else { $layoutUpdate = $this->_page->getLayoutUpdateXml(); } if (!empty($layoutUpdate)) { $this->_view->getLayout()->getUpdate()->addUpdate($layoutUpdate); } $this->_view->generateLayoutXml()->generateLayoutBlocks(); $contentHeadingBlock = $this->_view->getLayout()->getBlock('page_content_heading'); if ($contentHeadingBlock) { $contentHeading = $this->_escaper->escapeHtml($this->_page->getContentHeading()); $contentHeadingBlock->setContentHeading($contentHeading); } if ($this->_page->getRootTemplate()) { $this->_pageLayout->applyTemplate($this->_page->getRootTemplate()); } /* @TODO: Move catalog and checkout storage types to appropriate modules */ $messageBlock = $this->_view->getLayout()->getMessagesBlock(); $messageBlock->addStorageType($this->messageManager->getDefaultGroup()); $messageBlock->addMessages($this->messageManager->getMessages(true)); if ($renderLayout) { $this->_view->renderLayout(); } return true; }
/** * Return formatted option value for quote option * * @param string $optionValue Prepared for cart option value * @return string */ public function getFormattedOptionValue($optionValue) { if ($this->_formattedOptionValue === null) { $this->_formattedOptionValue = $this->_escaper->escapeHtml($this->getEditableOptionValue($optionValue)); } return $this->_formattedOptionValue; }
/** * Generate layout update xml * * @param string $container * @param string $templatePath * @return string * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function generateLayoutUpdateXml($container, $templatePath = '') { $templateFilename = $this->_viewFileSystem->getTemplateFileName($templatePath, ['area' => $this->getArea(), 'themeId' => $this->getThemeId(), 'module' => \Magento\Framework\View\Element\AbstractBlock::extractModuleName($this->getType())]); if (!$this->getId() && !$this->isCompleteToCreate() || $templatePath && !is_readable($templateFilename)) { return ''; } $parameters = $this->getWidgetParameters(); $xml = '<body><referenceContainer name="' . $container . '">'; $template = ''; if (isset($parameters['template'])) { unset($parameters['template']); } if ($templatePath) { $template = ' template="' . $templatePath . '"'; } $hash = $this->mathRandom->getUniqueHash(); $xml .= '<block class="' . $this->getType() . '" name="' . $hash . '"' . $template . '>'; foreach ($parameters as $name => $value) { if ($name == 'conditions') { $name = 'conditions_encoded'; $value = $this->conditionsHelper->encode($value); } elseif (is_array($value)) { $value = implode(',', $value); } if ($name && strlen((string) $value)) { $xml .= '<action method="setData">' . '<argument name="name" xsi:type="string">' . $name . '</argument>' . '<argument name="value" xsi:type="string">' . $this->_escaper->escapeHtml($value) . '</argument>' . '</action>'; } } $xml .= '</block></referenceContainer></body>'; return $xml; }
/** * 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)); } }
/** * 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 ResponseInterface * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function execute() { $itemId = (int) $this->getRequest()->getParam('item'); /* @var $item \Magento\Wishlist\Model\Item */ $item = $this->itemFactory->create()->load($itemId); if (!$item->getId()) { return $this->_redirect('*/*'); } $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId()); if (!$wishlist) { return $this->_redirect('*/*'); } // 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\Resource\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->cart->getShouldRedirectToCart()) { $redirectUrl = $this->cart->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, __('Cannot add item to shopping cart')); } $this->helper->calculate(); return $this->getResponse()->setRedirect($redirectUrl); }
/** * @param AbstractElement $element * @return string * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function render(AbstractElement $element) { $countryId = false; $isRegionRequired = false; if ($country = $element->getForm()->getElement('country_id')) { $countryId = $country->getValue(); $isRegionRequired = $this->_directoryHelper->isRegionRequired($countryId); } $html = '<div class="field field-region ' . ($isRegionRequired ? 'required' : '') . '">' . "\n"; $regionCollection = false; if ($countryId) { if (!isset(self::$_regionCollections[$countryId])) { self::$_regionCollections[$countryId] = $this->_countryFactory->create()->setId($countryId)->getLoadedRegionCollection()->toOptionArray(); } $regionCollection = self::$_regionCollections[$countryId]; } $regionId = intval($element->getForm()->getElement('region_id')->getValue()); $htmlAttributes = $element->getHtmlAttributes(); foreach ($htmlAttributes as $key => $attribute) { if ('type' === $attribute) { unset($htmlAttributes[$key]); break; } } // Output two elements - for 'region' and for 'region_id'. // Two elements are needed later upon form post - to properly set data to address model, // otherwise old value can be left in region_id attribute and saved to DB. // Depending on country selected either 'region' (input text) or 'region_id' (selectbox) is visible to user $regionHtmlName = $element->getName(); $regionIdHtmlName = str_replace('region', 'region_id', $regionHtmlName); $regionHtmlId = $element->getHtmlId(); $regionIdHtmlId = str_replace('region', 'region_id', $regionHtmlId); if ($isRegionRequired) { $element->addClass('required-entry'); } if ($regionCollection && count($regionCollection) > 0) { $elementClass = $element->getClass(); $html .= '<label class="label" for="' . $regionIdHtmlId . '"><span>' . $element->getLabel() . '</span>' . '</label>'; $html .= '<div class="control">'; $html .= '<select id="' . $regionIdHtmlId . '" name="' . $regionIdHtmlName . '" ' . $element->serialize($htmlAttributes) . '>' . "\n"; foreach ($regionCollection as $region) { $selected = $regionId == $region['value'] ? ' selected="selected"' : ''; $regionVal = 0 == $region['value'] ? '' : (int) $region['value']; $html .= '<option value="' . $regionVal . '"' . $selected . '>' . $this->_escaper->escapeHtml(__($region['label'])) . '</option>'; } $html .= '</select>' . "\n"; $html .= '<input type="hidden" name="' . $regionHtmlName . '" id="' . $regionHtmlId . '" value=""/>'; $html .= '</div>'; $element->setClass($elementClass); } else { $html .= '<label class="label" for="' . $regionHtmlId . '"><span>' . $element->getLabel() . '</span></label>'; $html .= '<div class="control">'; $html .= '<input id="' . $regionHtmlId . '" name="' . $regionHtmlName . '" value="' . $element->getEscapedValue() . '" ' . $element->serialize($htmlAttributes) . "/>" . "\n"; $html .= '<input type="hidden" name="' . $regionIdHtmlName . '" id="' . $regionIdHtmlId . '" value=""/>'; $html .= '</div>' . "\n"; } $html .= '</div>' . "\n"; return $html; }
/** * Retrieve escaped and preformated gift message text for specified entity * * @param \Magento\Framework\Object $entity * @return string|null */ public function getEscapedGiftMessage(\Magento\Framework\Object $entity) { $message = $this->getGiftMessageForEntity($entity); if ($message) { return nl2br($this->_escaper->escapeHtml($message->getMessage())); } return null; }
/** * Return formatted option value ready to edit, ready to parse * * @param string $optionValue Prepared for cart option value * @return string */ public function getEditableOptionValue($optionValue) { try { $value = unserialize($optionValue); return sprintf('%s [%d]', $this->_escaper->escapeHtml($value['title']), $this->getConfigurationItemOption()->getId()); } catch (\Exception $e) { return $optionValue; } }
/** * Create customer account action * * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute() { if ($this->_getSession()->isLoggedIn() || !$this->isRegistrationAllowed()) { $this->_redirect('*/*/'); return; } if (!$this->getRequest()->isPost()) { $url = $this->_createUrl()->getUrl('*/*/create', array('_secure' => true)); $this->getResponse()->setRedirect($this->_redirect->error($url)); return; } $this->_session->regenerateId(); try { $customer = $this->customerExtractor->extract('customer_account_create', $this->_request); $address = $this->_extractAddress(); $addresses = is_null($address) ? array() : array($address); $password = $this->getRequest()->getParam('password'); $redirectUrl = $this->_getSession()->getBeforeAuthUrl(); $customerDetails = $this->_customerDetailsBuilder->setCustomer($customer)->setAddresses($addresses)->create(); $customer = $this->_customerAccountService->createCustomer($customerDetails, $password, $redirectUrl); if ($this->getRequest()->getParam('is_subscribed', false)) { $this->_subscriberFactory->create()->subscribeCustomerById($customer->getId()); } $this->_eventManager->dispatch('customer_register_success', array('account_controller' => $this, 'customer' => $customer)); $confirmationStatus = $this->_customerAccountService->getConfirmationStatus($customer->getId()); if ($confirmationStatus === CustomerAccountServiceInterface::ACCOUNT_CONFIRMATION_REQUIRED) { $email = $this->_customerHelperData->getEmailConfirmationUrl($customer->getEmail()); // @codingStandardsIgnoreStart $this->messageManager->addSuccess(__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please <a href="%1">click here</a>.', $email)); // @codingStandardsIgnoreEnd $url = $this->_createUrl()->getUrl('*/*/index', array('_secure' => true)); $this->getResponse()->setRedirect($this->_redirect->success($url)); } else { $this->_getSession()->setCustomerDataAsLoggedIn($customer); $url = $this->_welcomeCustomer($customer); $this->getResponse()->setRedirect($this->_redirect->success($url)); } return; } catch (StateException $e) { $url = $this->_createUrl()->getUrl('customer/account/forgotpassword'); // @codingStandardsIgnoreStart $message = __('There is already an account with this email address. If you are sure that it is your email address, <a href="%1">click here</a> to get your password and access your account.', $url); // @codingStandardsIgnoreEnd $this->messageManager->addError($message); } catch (InputException $e) { $this->messageManager->addError($this->escaper->escapeHtml($e->getMessage())); foreach ($e->getErrors() as $error) { $this->messageManager->addError($this->escaper->escapeHtml($error->getMessage())); } } catch (\Exception $e) { $this->messageManager->addException($e, __('Cannot save the customer.')); } $this->_getSession()->setCustomerFormData($this->getRequest()->getPost()); $defaultUrl = $this->_createUrl()->getUrl('*/*/create', array('_secure' => true)); $this->getResponse()->setRedirect($this->_redirect->error($defaultUrl)); }
public function getBackendCfg() { $cfg = []; $cfg['key'] = $this->_encryptor->decrypt($this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/main_options/backend_accesstoken', \Magento\Store\Model\ScopeInterface::SCOPE_STORE))); $cfg['enabled'] = $this->scopeConfig->isSetFlag('cc_uk/main_options/backend_enabled', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); $cfg['auto_search'] = $this->scopeConfig->isSetFlag('cc_uk/gfx_options/searchbar_auto_search', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); $cfg['clean_postsearch'] = $this->scopeConfig->isSetFlag('cc_uk/gfx_options/searchbar_clean_postsearch', \Magento\Store\Model\ScopeInterface::SCOPE_STORE); $cfg['searchbar_type'] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/gfx_options/searchbar_type', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $cfg['error_msg'] = []; $cfg['error_msg']["0001"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/error_msg_1', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $cfg['error_msg']["0002"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/error_msg_2', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $cfg['error_msg']["0003"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/error_msg_3', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $cfg['error_msg']["0004"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/error_msg_4', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $cfg['txt'] = []; $cfg['txt']["search_label"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/search_label', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $cfg['txt']["search_placeholder"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/search_placeholder', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); $cfg['txt']["search_buttontext"] = $this->_escaper->escapeHtml($this->scopeConfig->getValue('cc_uk/txt_options/search_buttontext', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)); return json_encode($cfg); }
/** * Add error message for invalid VAT ID * * @param Address $customerAddress * @return $this */ protected function addInvalidMessage($customerAddress) { $vatId = $this->escaper->escapeHtml($customerAddress->getVatId()); $message = [(string) __('The VAT ID entered (%1) is not a valid VAT ID.', $vatId)]; $customer = $customerAddress->getCustomer(); if (!$this->scopeConfig->isSetFlag(HelperAddress::XML_PATH_VIV_DISABLE_AUTO_ASSIGN_DEFAULT) && !$customer->getDisableAutoGroupChange()) { $message[] = (string) __('You will be charged tax.'); } $this->messageManager->addError(implode(' ', $message)); return $this; }