private void PrepareProductReviewModel(ProductReviewModel model, ProductReview productReview, bool excludeProperties, bool formatReviewText) { Guard.NotNull(model, nameof(model)); Guard.NotNull(productReview, nameof(productReview)); model.Id = productReview.Id; model.ProductId = productReview.ProductId; model.ProductName = productReview.Product.Name; model.ProductTypeName = productReview.Product.GetProductTypeLabel(_localizationService); model.ProductTypeLabelHint = productReview.Product.ProductTypeLabelHint; model.CustomerId = productReview.CustomerId; model.CustomerName = productReview.Customer.GetDisplayName(T); model.IpAddress = productReview.IpAddress; model.Rating = productReview.Rating; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(productReview.CreatedOnUtc, DateTimeKind.Utc); if (!excludeProperties) { model.Title = productReview.Title; model.IsApproved = productReview.IsApproved; model.ReviewText = formatReviewText ? HtmlUtils.ConvertPlainTextToHtml(productReview.ReviewText.HtmlEncode()) : productReview.ReviewText; } }
public ActionResult Comments(int?filterByNewsItemId, GridCommand command) { var gridModel = new GridModel <NewsCommentModel>(); if (_permissionService.Authorize(StandardPermissionProvider.ManageNews)) { IList <NewsComment> comments; if (filterByNewsItemId.HasValue) { //filter comments by news item var newsItem = _newsService.GetNewsById(filterByNewsItemId.Value); comments = newsItem.NewsComments.OrderBy(bc => bc.CreatedOnUtc).ToList(); } else { //load all news comments comments = _customerContentService.GetAllCustomerContent <NewsComment>(0, null); } gridModel.Data = comments.PagedForCommand(command).Select(newsComment => { var commentModel = new NewsCommentModel(); var customer = _customerService.GetCustomerById(newsComment.CustomerId); commentModel.Id = newsComment.Id; commentModel.NewsItemId = newsComment.NewsItemId; commentModel.NewsItemTitle = newsComment.NewsItem.Title; commentModel.CustomerId = newsComment.CustomerId; commentModel.IpAddress = newsComment.IpAddress; commentModel.CreatedOn = _dateTimeHelper.ConvertToUserTime(newsComment.CreatedOnUtc, DateTimeKind.Utc); commentModel.CommentTitle = newsComment.CommentTitle; commentModel.CommentText = HtmlUtils.ConvertPlainTextToHtml(newsComment.CommentText.HtmlEncode()); if (customer == null) { commentModel.CustomerName = "".NaIfEmpty(); } else { commentModel.CustomerName = customer.GetFullName(); } return(commentModel); }); gridModel.Total = comments.Count; } else { gridModel.Data = Enumerable.Empty <NewsCommentModel>(); NotifyAccessDenied(); } return(new JsonResult { Data = gridModel }); }
public ActionResult Comments(int?filterByBlogPostId, GridCommand command) { var model = new GridModel <BlogCommentModel>(); if (_permissionService.Authorize(StandardPermissionProvider.ManageBlog)) { IList <BlogComment> comments; if (filterByBlogPostId.HasValue) { //filter comments by blog var blogPost = _blogService.GetBlogPostById(filterByBlogPostId.Value); comments = blogPost.BlogComments.OrderBy(bc => bc.CreatedOnUtc).ToList(); } else { //load all blog comments comments = _customerContentService.GetAllCustomerContent <BlogComment>(0, null); } model.Data = comments.PagedForCommand(command).Select(blogComment => { var commentModel = new BlogCommentModel(); var customer = _customerService.GetCustomerById(blogComment.CustomerId); commentModel.Id = blogComment.Id; commentModel.BlogPostId = blogComment.BlogPostId; commentModel.BlogPostTitle = blogComment.BlogPost.Title; commentModel.CustomerId = blogComment.CustomerId; commentModel.IpAddress = blogComment.IpAddress; commentModel.CreatedOn = _dateTimeHelper.ConvertToUserTime(blogComment.CreatedOnUtc, DateTimeKind.Utc); commentModel.Comment = HtmlUtils.ConvertPlainTextToHtml(blogComment.CommentText.HtmlEncode()); if (customer == null) { commentModel.CustomerName = "".NaIfEmpty(); } else { commentModel.CustomerName = customer.GetFullName(); } return(commentModel); }); model.Total = comments.Count; } else { model.Data = Enumerable.Empty <BlogCommentModel>(); NotifyAccessDenied(); } return(new JsonResult { Data = model }); }
/// <summary> /// Formats the forum signature text /// </summary> /// <param name="text">Text</param> /// <returns>Formatted text</returns> public static string FormatForumSignatureText(this string text) { if (text.IsEmpty()) { return(string.Empty); } return(HtmlUtils.ConvertPlainTextToHtml(text.HtmlEncode())); }
// Ajax. public ActionResult ConfirmOrder(string formData) { string redirectUrl = null; var messages = new List <string>(); var success = false; try { var store = Services.StoreContext.CurrentStore; var customer = Services.WorkContext.CurrentCustomer; var processPaymentRequest = (_httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest) ?? new ProcessPaymentRequest(); processPaymentRequest.StoreId = store.Id; processPaymentRequest.CustomerId = customer.Id; processPaymentRequest.PaymentMethodSystemName = AmazonPayPlugin.SystemName; // We must check here if an order can be placed to avoid creating unauthorized Amazon payment objects. var warnings = _orderProcessingService.GetOrderPlacementWarnings(processPaymentRequest); if (!warnings.Any()) { if (_orderProcessingService.IsMinimumOrderPlacementIntervalValid(customer, store)) { if (_apiService.ConfirmOrderReference()) { success = true; var state = _httpContext.GetAmazonPayState(Services.Localization); state.FormData = formData.EmptyNull(); } else { _httpContext.Session["AmazonPayFailedPaymentReason"] = "PaymentMethodNotAllowed"; redirectUrl = Url.Action("PaymentMethod", "Checkout", new { area = "" }); } } else { messages.Add(T("Checkout.MinOrderPlacementInterval")); } } else { messages.AddRange(warnings.Select(x => HtmlUtils.ConvertPlainTextToHtml(x))); } } catch (Exception ex) { messages.Add(ex.Message); Logger.Error(ex); } return(Json(new { success, redirectUrl, messages })); }
/// <summary> /// Formats the order note text /// </summary> /// <param name="orderNote">Order note</param> /// <returns>Formatted text</returns> public static string FormatOrderNoteText(this OrderNote orderNote) { Guard.NotNull(orderNote, nameof(orderNote)); if (orderNote.Note.IsEmpty()) { return(string.Empty); } return(HtmlUtils.ConvertPlainTextToHtml(orderNote.Note)); }
public ActionResult LicenseResetStatusCheck(string systemName) { // Reset state for current store. var result = LicenseChecker.ResetState(systemName); LicenseCheckerResult subShopResult = null; var model = new LicenseLabelModel { IsLicensable = true, LicenseUrl = Url.Action("LicensePlugin", new { systemName = systemName }), LicenseState = result.State, TruncatedLicenseKey = result.TruncatedLicenseKey, RemainingDemoUsageDays = result.RemainingDemoDays }; // Reset state for all other stores. if (result.Success) { var currentStoreId = Services.StoreContext.CurrentStore.Id; var allStores = Services.StoreService.GetAllStores(); foreach (var store in allStores.Where(x => x.Id != currentStoreId && x.Url.HasValue())) { subShopResult = LicenseChecker.ResetState(systemName, store.Url); if (!subShopResult.Success) { result = subShopResult; break; } } } // Notify about result. if (result.Success) { NotifySuccess(T("Admin.Common.TaskSuccessfullyProcessed")); } else { var message = HtmlUtils.ConvertPlainTextToHtml(result.ToString()); if (result.IsFailureWarning) { NotifyWarning(message); } else { NotifyError(message); } } return(PartialView("Partials/LicenseLabel", model)); }
public ActionResult Comments(int?filterByNewsItemId, GridCommand command) { IPagedList <NewsComment> comments; if (filterByNewsItemId.HasValue) { // Filter comments by news item. var query = _customerContentService.GetAllCustomerContent <NewsComment>(0, null).SourceQuery; query = query.Where(x => x.NewsItemId == filterByNewsItemId.Value); comments = new PagedList <NewsComment>(query, command.Page - 1, command.PageSize); } else { // Load all news comments. comments = _customerContentService.GetAllCustomerContent <NewsComment>(0, null, null, null, command.Page - 1, command.PageSize); } var customerIds = comments.Select(x => x.CustomerId).Distinct().ToArray(); var customers = _customerService.GetCustomersByIds(customerIds).ToDictionarySafe(x => x.Id); var model = new GridModel <NewsCommentModel> { Total = comments.TotalCount }; model.Data = comments.Select(newsComment => { customers.TryGetValue(newsComment.CustomerId, out var customer); var commentModel = new NewsCommentModel { Id = newsComment.Id, NewsItemId = newsComment.NewsItemId, NewsItemTitle = newsComment.NewsItem.GetLocalized(x => x.Title), CustomerId = newsComment.CustomerId, IpAddress = newsComment.IpAddress, CreatedOn = _dateTimeHelper.ConvertToUserTime(newsComment.CreatedOnUtc, DateTimeKind.Utc), CommentTitle = newsComment.CommentTitle, CommentText = HtmlUtils.ConvertPlainTextToHtml(newsComment.CommentText.HtmlEncode()), CustomerName = customer.GetDisplayName(T) }; return(commentModel); }); return(new JsonResult { Data = model }); }
public async Task <IActionResult> AskQuestionSend(ProductAskQuestionModel model, string captchaError) { if (!_catalogSettings.AskQuestionEnabled) { return(NotFound()); } var product = await _db.Products.FindByIdAsync(model.Id, false); if (product == null || product.IsSystemProduct || !product.Published) { return(NotFound()); } if (_captchaSettings.ShowOnAskQuestionPage && captchaError.HasValue()) { ModelState.AddModelError("", captchaError); } if (ModelState.IsValid) { var msg = await _messageFactory.Value.SendProductQuestionMessageAsync( Services.WorkContext.CurrentCustomer, product, model.SenderEmail, model.SenderName, model.SenderPhone, HtmlUtils.ConvertPlainTextToHtml(model.Question.HtmlEncode()), HtmlUtils.ConvertPlainTextToHtml(model.SelectedAttributes.HtmlEncode()), model.ProductUrl, model.IsQuoteRequest); if (msg?.Email?.Id != null) { TempData.Remove("AskQuestionAttributeSelection-" + product.Id); NotifySuccess(T("Products.AskQuestion.Sent")); return(RedirectToRoute("Product", new { SeName = await product.GetActiveSlugAsync() })); } else { ModelState.AddModelError("", T("Common.Error.SendMail")); } } // If we got this far something failed. Redisplay form. model = await PrepareAskQuestionModelAsync(product); return(View(model)); }
/// <summary> /// Formats the private message text /// </summary> /// <param name="message">Private message</param> /// <returns>Formatted text</returns> public static string FormatPrivateMessageText(this PrivateMessage message) { Guard.NotNull(message, nameof(message)); var text = message.Text; if (text.IsEmpty()) { return(string.Empty); } text = HtmlUtils.ConvertPlainTextToHtml(text.HtmlEncode()); return(BBCodeHelper.ToHtml(text)); }
public ActionResult AskQuestionSend(ProductAskQuestionModel model, string captchaError) { var product = _productService.GetProductById(model.Id); if (product == null || product.Deleted || product.IsSystemProduct || !product.Published || !_catalogSettings.AskQuestionEnabled) { return(HttpNotFound()); } if (_captchaSettings.ShowOnAskQuestionPage && captchaError.HasValue()) { ModelState.AddModelError("", captchaError); } model.ProductUrl = _services.StoreContext.CurrentStore.Url + model.ProductUrl.Substring(1); if (ModelState.IsValid) { var msg = Services.MessageFactory.SendProductQuestionMessage( _services.WorkContext.CurrentCustomer, product, model.SenderEmail, model.SenderName, model.SenderPhone, HtmlUtils.ConvertPlainTextToHtml(model.Question.HtmlEncode()), HtmlUtils.ConvertPlainTextToHtml(model.SelectedAttributes.HtmlEncode()), model.ProductUrl, model.IsQuoteRequest); if (msg?.Email?.Id != null) { NotifySuccess(T("Products.AskQuestion.Sent"), true); return(RedirectToRoute("Product", new { SeName = product.GetSeName() })); } else { ModelState.AddModelError("", T("Common.Error.SendMail")); } } // If we got this far, something failed, redisplay form. var customer = _services.WorkContext.CurrentCustomer; model.Id = product.Id; model.ProductName = product.GetLocalized(x => x.Name); model.ProductSeName = product.GetSeName(); model.DisplayCaptcha = _captchaSettings.CanDisplayCaptcha && _captchaSettings.ShowOnAskQuestionPage; return(View(model)); }
public async Task <IActionResult> EmailAFriendSend(ProductEmailAFriendModel model, int id, string captchaError) { var product = await _db.Products.FindByIdAsync(id, false); if (product == null || product.IsSystemProduct || !product.Published || !_catalogSettings.EmailAFriendEnabled) { return(NotFound()); } if (_captchaSettings.ShowOnEmailProductToFriendPage && captchaError.HasValue()) { ModelState.AddModelError("", captchaError); } var customer = Services.WorkContext.CurrentCustomer; // Check whether the current customer is guest and is allowed to email a friend. if (customer.IsGuest() && !_catalogSettings.AllowAnonymousUsersToEmailAFriend) { ModelState.AddModelError("", T("Products.EmailAFriend.OnlyRegisteredUsers")); } if (ModelState.IsValid) { //email await _messageFactory.Value.SendShareProductMessageAsync( customer, product, model.YourEmailAddress, model.FriendEmail, HtmlUtils.ConvertPlainTextToHtml(model.PersonalMessage.HtmlEncode())); NotifySuccess(T("Products.EmailAFriend.SuccessfullySent")); return(RedirectToRoute("Product", new { SeName = await product.GetActiveSlugAsync() })); } // If we got this far something failed. Redisplay form. model = await PrepareEmailAFriendModelAsync(product); return(View(model)); }
private void PrepareProductReviewModel(ProductReviewModel model, ProductReview productReview, bool excludeProperties, bool formatReviewText) { if (model == null) { throw new ArgumentNullException("model"); } if (productReview == null) { throw new ArgumentNullException("productReview"); } model.Id = productReview.Id; model.ProductId = productReview.ProductId; model.ProductName = productReview.Product.Name; model.ProductTypeName = productReview.Product.GetProductTypeLabel(_localizationService); model.ProductTypeLabelHint = productReview.Product.ProductTypeLabelHint; model.CustomerId = productReview.CustomerId; model.CustomerName = productReview.Customer.GetFullName(); model.IpAddress = productReview.IpAddress; model.Rating = productReview.Rating; model.CreatedOn = _dateTimeHelper.ConvertToUserTime(productReview.CreatedOnUtc, DateTimeKind.Utc); if (string.IsNullOrWhiteSpace(model.CustomerName) && !productReview.Customer.IsRegistered()) { model.CustomerName = _localizationService.GetResource("Admin.Customers.Guest"); } if (!excludeProperties) { model.Title = productReview.Title; if (formatReviewText) { model.ReviewText = HtmlUtils.ConvertPlainTextToHtml(productReview.ReviewText.HtmlEncode()); } else { model.ReviewText = productReview.ReviewText; } model.IsApproved = productReview.IsApproved; } }
/// <summary> /// Formats the forum post text /// </summary> /// <param name="post">Forum post</param> /// <returns>Formatted text</returns> public static string FormatPostText(this ForumPost post) { Guard.NotNull(post, nameof(post)); var text = post.Text; if (text.IsEmpty()) { return(string.Empty); } text = HtmlUtils.ConvertPlainTextToHtml(text.HtmlEncode()); if (EngineContext.Current.Resolve <ForumSettings>().ForumEditor == EditorType.BBCodeEditor) { text = BBCodeHelper.ToHtml(text); } return(text); }
public virtual string FormatAddress(Address address, bool newLineToBr = false) { Guard.NotNull(address, nameof(address)); var messageContext = new MessageContext { Language = _services.WorkContext.WorkingLanguage, Store = _services.StoreContext.CurrentStore, Model = new TemplateModel() }; _messageModelProvider.AddModelPart(address, messageContext, "Address"); var model = messageContext.Model["Address"]; var result = FormatAddress(model, address?.Country?.AddressFormat, messageContext.FormatProvider); if (newLineToBr) { result = HtmlUtils.ConvertPlainTextToHtml(result); } return(result); }
public ActionResult ConfirmOrder(FormCollection form) { //validation var storeId = _storeContext.CurrentStore.Id; var customer = _workContext.CurrentCustomer; var cart = customer.GetCartItems(ShoppingCartType.ShoppingCart, storeId); if (cart.Count == 0) { return(RedirectToRoute("ShoppingCart")); } if ((customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed)) { return(new HttpUnauthorizedResult()); } var model = new CheckoutConfirmModel(); PlaceOrderResult placeOrderResult = null; PostProcessPaymentRequest postProcessPaymentRequest = null; try { var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest; if (processPaymentRequest == null) { //Check whether payment workflow is required if (IsPaymentWorkflowRequired(cart)) { return(RedirectToAction("PaymentMethod")); } processPaymentRequest = new ProcessPaymentRequest(); } //prevent 2 orders being placed within an X seconds time frame if (!IsMinimumOrderPlacementIntervalValid(customer)) { throw new Exception(T("Checkout.MinOrderPlacementInterval")); } //place order processPaymentRequest.StoreId = storeId; processPaymentRequest.CustomerId = customer.Id; processPaymentRequest.PaymentMethodSystemName = customer.GetAttribute <string>(SystemCustomerAttributeNames.SelectedPaymentMethod, _genericAttributeService, storeId); var placeOrderExtraData = new Dictionary <string, string>(); placeOrderExtraData["CustomerComment"] = form["customercommenthidden"]; placeOrderExtraData["SubscribeToNewsLetter"] = form["SubscribeToNewsLetterHidden"]; placeOrderExtraData["AcceptThirdPartyEmailHandOver"] = form["AcceptThirdPartyEmailHandOverHidden"]; placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest, placeOrderExtraData); if (!placeOrderResult.Success) { model.Warnings.AddRange(placeOrderResult.Errors.Select(x => HtmlUtils.ConvertPlainTextToHtml(x))); } } catch (Exception exception) { Logger.Warn(exception, exception.Message); if (!model.Warnings.Any(x => x == exception.Message)) { model.Warnings.Add(exception.Message); } } if (placeOrderResult == null || !placeOrderResult.Success || model.Warnings.Any()) { return(View(model)); } try { postProcessPaymentRequest = new PostProcessPaymentRequest { Order = placeOrderResult.PlacedOrder }; _paymentService.PostProcessPayment(postProcessPaymentRequest); } catch (Exception exception) { NotifyError(exception); } finally { _httpContext.Session["OrderPaymentInfo"] = null; _httpContext.RemoveCheckoutState(); } if (postProcessPaymentRequest != null && postProcessPaymentRequest.RedirectUrl.HasValue()) { return(Redirect(postProcessPaymentRequest.RedirectUrl)); } return(RedirectToAction("Completed")); }
/// <summary> /// Formats attributes /// </summary> /// <param name="attributes">Attributes</param> /// <param name="customer">Customer</param> /// <param name="serapator">Serapator</param> /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param> /// <param name="renderPrices">A value indicating whether to render prices</param> /// <param name="allowHyperlinks">A value indicating whether to HTML hyperink tags could be rendered (if required)</param> /// <returns>Attributes</returns> public string FormatAttributes(string attributes, Customer customer, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true, bool allowHyperlinks = true) { var result = new StringBuilder(); var caCollection = _checkoutAttributeParser.ParseCheckoutAttributes(attributes); if (caCollection.Count <= 0) { return(null); } for (int i = 0; i < caCollection.Count; i++) { var ca = caCollection[i]; var valuesStr = _checkoutAttributeParser.ParseValues(attributes, ca.Id); for (int j = 0; j < valuesStr.Count; j++) { string valueStr = valuesStr[j]; string caAttribute = ""; if (!ca.ShouldHaveValues()) { //no values if (ca.AttributeControlType == AttributeControlType.MultilineTextbox) { //multiline textbox string attributeName = ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage); //encode (if required) if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } caAttribute = string.Format("{0}: {1}", attributeName, HtmlUtils.ConvertPlainTextToHtml(valueStr.EmptyNull().Replace(":", "").HtmlEncode())); //we never encode multiline textbox input } else if (ca.AttributeControlType == AttributeControlType.FileUpload) { //file upload Guid downloadGuid; Guid.TryParse(valueStr, out downloadGuid); var download = _downloadService.GetDownloadByGuid(downloadGuid); if (download?.MediaFile != null) { //TODO add a method for getting URL (use routing because it handles all SEO friendly URLs) string attributeText = ""; var fileName = download.MediaFile.Name; //encode (if required) if (htmlEncode) { fileName = HttpUtility.HtmlEncode(fileName); } if (allowHyperlinks) { //hyperlinks are allowed var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid); attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName); } else { //hyperlinks aren't allowed attributeText = fileName; } string attributeName = ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage); //encode (if required) if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } caAttribute = string.Format("{0}: {1}", attributeName, attributeText); } } else { //other attributes (textbox, datepicker) caAttribute = string.Format("{0}: {1}", ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage), valueStr); //encode (if required) if (htmlEncode) { caAttribute = HttpUtility.HtmlEncode(caAttribute); } } } else { int caId = 0; if (int.TryParse(valueStr, out caId)) { var caValue = _checkoutAttributeService.GetCheckoutAttributeValueById(caId); if (caValue != null) { caAttribute = string.Format("{0}: {1}", ca.GetLocalized(a => a.Name, _workContext.WorkingLanguage), caValue.GetLocalized(a => a.Name, _workContext.WorkingLanguage)); if (renderPrices) { decimal priceAdjustmentBase = _taxService.GetCheckoutAttributePrice(caValue, customer); decimal priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency); if (priceAdjustmentBase > 0) { string priceAdjustmentStr = _priceFormatter.FormatPrice(priceAdjustment); caAttribute += string.Format(" [+{0}]", priceAdjustmentStr); } } } //encode (if required) if (htmlEncode) { caAttribute = HttpUtility.HtmlEncode(caAttribute); } } } if (!String.IsNullOrEmpty(caAttribute)) { if (i != 0 || j != 0) { result.Append(serapator); } result.Append(caAttribute); } } } return(result.ToString()); }
public async Task <string> FormatAttributesAsync( CheckoutAttributeSelection selection, Customer customer = null, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true, bool allowHyperlinks = true) { Guard.NotNull(selection, nameof(selection)); customer ??= _workContext.CurrentCustomer; using var psb = StringBuilderPool.Instance.Get(out var sb); var attributesList = await _checkoutAttributeMaterializer.MaterializeCheckoutAttributesAsync(selection); if (attributesList.IsNullOrEmpty()) { return(null); } var attributeValues = attributesList .Where(x => x.ShouldHaveValues()) .SelectMany(x => x.CheckoutAttributeValues); var language = _workContext.WorkingLanguage; for (var i = 0; i < attributesList.Count; i++) { var currentAttribute = attributesList[i]; var currentAttributeValues = selection.GetAttributeValues(currentAttribute.Id).ToList(); for (var j = 0; j < currentAttributeValues.Count; j++) { var currentValue = currentAttributeValues[j].ToString(); var attributeStr = string.Empty; if (!currentAttribute.ShouldHaveValues()) { if (currentAttribute.AttributeControlType is AttributeControlType.MultilineTextbox) { // Multiline textbox input gets never encoded var attributeName = currentAttribute.GetLocalized(a => a.Name, language).ToString(); if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } attributeStr = string.Format( "{0}: {1}", attributeName, HtmlUtils.ConvertPlainTextToHtml(currentValue.EmptyNull().Replace(":", "").HtmlEncode())); } else if (currentAttribute.AttributeControlType is AttributeControlType.FileUpload) { Guid.TryParse(currentValue, out var downloadGuid); var download = await _db.Downloads .Include(x => x.MediaFile) .Where(x => x.DownloadGuid == downloadGuid) .FirstOrDefaultAsync(); if (download?.MediaFile != null) { // TODO: (ms) (core) add a method for getting URL (use routing because it handles all SEO friendly URLs) ? //var genratedUrl = _mediaService.GetUrlAsync(download.MediaFileId, 0); var attributeText = string.Empty; var fileName = download.MediaFile.Name; if (htmlEncode) { fileName = HttpUtility.HtmlEncode(fileName); } if (allowHyperlinks) { var downloadLink = string.Format( "{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid); attributeText = string.Format( "<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName); } else { attributeText = fileName; } var attributeName = currentAttribute.GetLocalized(a => a.Name, language).ToString(); if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } attributeStr = string.Format("{0}: {1}", attributeName, attributeText); } } else { // Other attributes (textbox, datepicker...) attributeStr = string.Format( "{0}: {1}", currentAttribute.GetLocalized(a => a.Name, language), currentValue); if (htmlEncode) { attributeStr = HttpUtility.HtmlEncode(attributeStr); } } } else { if (int.TryParse(currentValue, out var id)) { var attributeValue = attributeValues.Where(x => x.Id == id).FirstOrDefault(); if (attributeValue != null) { attributeStr = string.Format( "{0}: {1}", currentAttribute.GetLocalized(x => x.Name, language), attributeValue.GetLocalized(x => x.Name, language)); if (renderPrices) { var priceAdjustment = await _taxService.GetCheckoutAttributePriceAsync(attributeValue, customer); var priceAdjustmentConverted = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustment, _workContext.WorkingCurrency); if (priceAdjustment > 0) { attributeStr += string.Format(" [+{0}]", _priceFormatter.FormatPrice(priceAdjustmentConverted)); } } } if (htmlEncode) { attributeStr = HttpUtility.HtmlEncode(attributeStr); } } } if (attributeStr.HasValue()) { if (i != 0 || j != 0) { sb.Append(serapator); } sb.Append(attributeStr); } } } return(sb.ToString()); }
/// <summary> /// Formats attributes. /// </summary> /// <param name="product">Product</param> /// <param name="attributes">Attributes</param> /// <param name="customer">Customer</param> /// <param name="separator">Separator</param> /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param> /// <param name="renderPrices">A value indicating whether to render prices</param> /// <param name="renderProductAttributes">A value indicating whether to render product attributes</param> /// <param name="renderGiftCardAttributes">A value indicating whether to render gift card attributes</param> /// <param name="allowHyperlinks">A value indicating whether to render HTML hyperlinks</param> /// <returns>Formatted attributes.</returns> public string FormatAttributes( Product product, string attributes, Customer customer, string separator = "<br />", bool htmlEncode = true, bool renderPrices = true, bool renderProductAttributes = true, bool renderGiftCardAttributes = true, bool allowHyperlinks = true) { var result = new StringBuilder(); // Attributes. if (renderProductAttributes) { var languageId = _workContext.WorkingLanguage.Id; var pvaCollection = _productAttributeParser.ParseProductVariantAttributes(attributes); for (var i = 0; i < pvaCollection.Count; ++i) { var pva = pvaCollection[i]; var valuesStr = _productAttributeParser.ParseValues(attributes, pva.Id); for (var j = 0; j < valuesStr.Count; ++j) { var valueStr = valuesStr[j]; var pvaAttribute = string.Empty; if (!pva.ShouldHaveValues()) { // No values. if (pva.AttributeControlType == AttributeControlType.MultilineTextbox) { // Multiline textbox. string attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, languageId); if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } pvaAttribute = string.Format("{0}: {1}", attributeName, HtmlUtils.ConvertPlainTextToHtml(valueStr.HtmlEncode())); // We never encode multiline textbox input. } else if (pva.AttributeControlType == AttributeControlType.FileUpload) { Guid.TryParse(valueStr, out var downloadGuid); var download = _downloadService.GetDownloadByGuid(downloadGuid); if (download?.MediaFile != null) { // TODO: add a method for getting URL (use routing because it handles all SEO friendly URLs). var attributeText = ""; var fileName = download.MediaFile.Name; if (htmlEncode) { fileName = HttpUtility.HtmlEncode(fileName); } if (allowHyperlinks) { var downloadLink = string.Format("{0}download/getfileupload/?downloadId={1}", _webHelper.GetStoreLocation(false), download.DownloadGuid); attributeText = string.Format("<a href=\"{0}\" class=\"fileuploadattribute\">{1}</a>", downloadLink, fileName); } else { attributeText = fileName; } string attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, languageId); if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } pvaAttribute = string.Format("{0}: {1}", attributeName, attributeText); } } else { // Other attributes (textbox, datepicker). pvaAttribute = string.Format("{0}: {1}", pva.ProductAttribute.GetLocalized(a => a.Name, languageId), valueStr); if (htmlEncode) { pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute); } } } else { // Attributes with values. if (int.TryParse(valueStr, out var pvaId)) { var pvaValue = _productAttributeService.GetProductVariantAttributeValueById(pvaId); if (pvaValue != null) { pvaAttribute = "{0}: {1}".FormatInvariant( pva.ProductAttribute.GetLocalized(a => a.Name, languageId), pvaValue.GetLocalized(a => a.Name, languageId)); if (renderPrices) { var attributeValuePriceAdjustment = _priceCalculationService.GetProductVariantAttributeValuePriceAdjustment(pvaValue, product, customer, null, 1); var priceAdjustmentBase = _taxService.GetProductPrice(product, attributeValuePriceAdjustment, customer, out var taxRate); var priceAdjustment = _currencyService.ConvertFromPrimaryStoreCurrency(priceAdjustmentBase, _workContext.WorkingCurrency); if (_shoppingCartSettings.ShowLinkedAttributeValueQuantity && pvaValue.ValueType == ProductVariantAttributeValueType.ProductLinkage && pvaValue.Quantity > 1) { pvaAttribute += string.Format(" × {0}", pvaValue.Quantity); } if (_catalogSettings.ShowVariantCombinationPriceAdjustment) { if (priceAdjustmentBase > 0) { pvaAttribute += " (+{0})".FormatInvariant(_priceFormatter.FormatPrice(priceAdjustment, true, false)); } else if (priceAdjustmentBase < decimal.Zero) { pvaAttribute += " (-{0})".FormatInvariant(_priceFormatter.FormatPrice(-priceAdjustment, true, false)); } } } } if (htmlEncode) { pvaAttribute = HttpUtility.HtmlEncode(pvaAttribute); } } } if (!string.IsNullOrEmpty(pvaAttribute)) { if (i != 0 || j != 0) { result.Append(separator); } result.Append(pvaAttribute); } } } } // Gift cards. if (renderGiftCardAttributes) { if (product.IsGiftCard) { _productAttributeParser.GetGiftCardAttribute(attributes, out var giftCardRecipientName, out var giftCardRecipientEmail, out var giftCardSenderName, out var giftCardSenderEmail, out var giftCardMessage); // Sender. var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ? string.Format(_localizationService.GetResource("GiftCardAttribute.From.Virtual"), giftCardSenderName, giftCardSenderEmail) : string.Format(_localizationService.GetResource("GiftCardAttribute.From.Physical"), giftCardSenderName); // Recipient. var giftCardFor = product.GiftCardType == GiftCardType.Virtual ? string.Format(_localizationService.GetResource("GiftCardAttribute.For.Virtual"), giftCardRecipientName, giftCardRecipientEmail) : string.Format(_localizationService.GetResource("GiftCardAttribute.For.Physical"), giftCardRecipientName); if (htmlEncode) { giftCardFrom = HttpUtility.HtmlEncode(giftCardFrom); giftCardFor = HttpUtility.HtmlEncode(giftCardFor); } if (!string.IsNullOrEmpty(result.ToString())) { result.Append(separator); } result.Append(giftCardFrom); result.Append(separator); result.Append(giftCardFor); } } return(result.ToString()); }
public virtual async Task <string> FormatAttributesAsync( ProductVariantAttributeSelection selection, Product product, Customer customer = null, string separator = "<br />", bool htmlEncode = true, bool includePrices = true, bool includeProductAttributes = true, bool includeGiftCardAttributes = true, bool includeHyperlinks = true, ProductBatchContext batchContext = null) { Guard.NotNull(selection, nameof(selection)); Guard.NotNull(product, nameof(product)); customer ??= _workContext.CurrentCustomer; using var pool = StringBuilderPool.Instance.Get(out var result); if (includeProductAttributes) { var languageId = _workContext.WorkingLanguage.Id; var attributes = await _productAttributeMaterializer.MaterializeProductVariantAttributesAsync(selection); var attributesDic = attributes.ToDictionary(x => x.Id); // Key: ProductVariantAttributeValue.Id, value: calculated attribute price adjustment. var priceAdjustments = includePrices && _catalogSettings.ShowVariantCombinationPriceAdjustment ? await _priceCalculationService.CalculateAttributePriceAdjustmentsAsync(product, selection, 1, _priceCalculationService.CreateDefaultOptions(false, customer, null, batchContext)) : new Dictionary <int, CalculatedPriceAdjustment>(); foreach (var kvp in selection.AttributesMap) { if (!attributesDic.TryGetValue(kvp.Key, out var pva)) { continue; } foreach (var value in kvp.Value) { var valueStr = value.ToString().EmptyNull(); var pvaAttribute = string.Empty; if (pva.IsListTypeAttribute()) { var pvaValue = pva.ProductVariantAttributeValues.FirstOrDefault(x => x.Id == valueStr.ToInt()); if (pvaValue != null) { pvaAttribute = "{0}: {1}".FormatInvariant( pva.ProductAttribute.GetLocalized(x => x.Name, languageId), pvaValue.GetLocalized(x => x.Name, languageId)); if (includePrices) { if (_shoppingCartSettings.ShowLinkedAttributeValueQuantity && pvaValue.ValueType == ProductVariantAttributeValueType.ProductLinkage && pvaValue.Quantity > 1) { pvaAttribute = pvaAttribute + " × " + pvaValue.Quantity; } if (priceAdjustments.TryGetValue(pvaValue.Id, out var adjustment)) { if (adjustment.Price > 0) { pvaAttribute += $" (+{adjustment.Price})"; } else if (adjustment.Price < 0) { pvaAttribute += $" (-{adjustment.Price * -1})"; } } } if (htmlEncode) { pvaAttribute = pvaAttribute.HtmlEncode(); } } } else if (pva.AttributeControlType == AttributeControlType.MultilineTextbox) { string attributeName = pva.ProductAttribute.GetLocalized(x => x.Name, languageId); pvaAttribute = "{0}: {1}".FormatInvariant( htmlEncode ? attributeName.HtmlEncode() : attributeName, HtmlUtils.ConvertPlainTextToHtml(valueStr.HtmlEncode())); } else if (pva.AttributeControlType == AttributeControlType.FileUpload) { if (Guid.TryParse(valueStr, out var downloadGuid) && downloadGuid != Guid.Empty) { var download = await _db.Downloads .AsNoTracking() .Include(x => x.MediaFile) .Where(x => x.DownloadGuid == downloadGuid) .FirstOrDefaultAsync(); if (download?.MediaFile != null) { var attributeText = string.Empty; var fileName = htmlEncode ? download.MediaFile.Name.HtmlEncode() : download.MediaFile.Name; if (includeHyperlinks) { // TODO: (core) add a method for getting URL (use routing because it handles all SEO friendly URLs). var downloadLink = _webHelper.GetStoreLocation(false) + "download/getfileupload/?downloadId=" + download.DownloadGuid; attributeText = $"<a href=\"{downloadLink}\" class=\"fileuploadattribute\">{fileName}</a>"; } else { attributeText = fileName; } string attributeName = pva.ProductAttribute.GetLocalized(a => a.Name, languageId); pvaAttribute = "{0}: {1}".FormatInvariant( htmlEncode ? attributeName.HtmlEncode() : attributeName, attributeText); } } } else { // TextBox, Datepicker pvaAttribute = "{0}: {1}".FormatInvariant(pva.ProductAttribute.GetLocalized(x => x.Name, languageId), valueStr); if (htmlEncode) { pvaAttribute = pvaAttribute.HtmlEncode(); } } result.Grow(pvaAttribute, separator); } } } if (includeGiftCardAttributes && product.IsGiftCard) { var gci = selection.GiftCardInfo; if (gci != null) { // Sender. var giftCardFrom = product.GiftCardType == GiftCardType.Virtual ? (await _localizationService.GetResourceAsync("GiftCardAttribute.From.Virtual")).FormatInvariant(gci.SenderName, gci.SenderEmail) : (await _localizationService.GetResourceAsync("GiftCardAttribute.From.Physical")).FormatInvariant(gci.SenderName); // Recipient. var giftCardFor = product.GiftCardType == GiftCardType.Virtual ? (await _localizationService.GetResourceAsync("GiftCardAttribute.For.Virtual")).FormatInvariant(gci.RecipientName, gci.RecipientEmail) : (await _localizationService.GetResourceAsync("GiftCardAttribute.For.Physical")).FormatInvariant(gci.RecipientName); if (htmlEncode) { giftCardFrom = giftCardFrom.HtmlEncode(); giftCardFor = giftCardFor.HtmlEncode(); } result.Grow(giftCardFrom, separator); result.Grow(giftCardFor, separator); } } return(result.ToString()); }
public async Task <string> FormatAttributesAsync( CheckoutAttributeSelection selection, Customer customer = null, string serapator = "<br />", bool htmlEncode = true, bool renderPrices = true, bool allowHyperlinks = true) { Guard.NotNull(selection, nameof(selection)); customer ??= _workContext.CurrentCustomer; using var psb = StringBuilderPool.Instance.Get(out var sb); var attributesList = await _checkoutAttributeMaterializer.MaterializeCheckoutAttributesAsync(selection); if (attributesList.IsNullOrEmpty()) { return(null); } var attributeValues = attributesList .Where(x => x.IsListTypeAttribute) .SelectMany(x => x.CheckoutAttributeValues); var language = _workContext.WorkingLanguage; for (var i = 0; i < attributesList.Count; i++) { var currentAttribute = attributesList[i]; var currentAttributeValues = selection.GetAttributeValues(currentAttribute.Id).ToList(); for (var j = 0; j < currentAttributeValues.Count; j++) { var currentValue = currentAttributeValues[j].ToString(); var attributeStr = string.Empty; if (!currentAttribute.IsListTypeAttribute) { if (currentAttribute.AttributeControlType is AttributeControlType.MultilineTextbox) { // Multiline textbox input gets never encoded var attributeName = currentAttribute.GetLocalized(a => a.Name, language).ToString(); if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } attributeStr = $"{attributeName}: {HtmlUtils.ConvertPlainTextToHtml(currentValue.EmptyNull().Replace(":", string.Empty).HtmlEncode())}"; } else if (currentAttribute.AttributeControlType is AttributeControlType.FileUpload) { Guid.TryParse(currentValue, out var downloadGuid); var download = await _db.Downloads .Include(x => x.MediaFile) .Where(x => x.DownloadGuid == downloadGuid) .FirstOrDefaultAsync(); if (download?.MediaFile != null) { // TODO: (ms) (core) add a method for getting URL (use routing because it handles all SEO friendly URLs) ? //var genratedUrl = _mediaService.GenerateFileDownloadUrl(download.MediaFileId, 0); var attributeText = string.Empty; var fileName = download.MediaFile.Name; if (htmlEncode) { fileName = HttpUtility.HtmlEncode(fileName); } if (allowHyperlinks) { var downloadLink = $"{_webHelper.GetStoreLocation()}download/getfileupload/?downloadId={download.DownloadGuid}"; attributeText = $"<a href='{downloadLink}' class='fileuploadattribute'>{fileName}</a>"; } else { attributeText = fileName; } var attributeName = currentAttribute.GetLocalized(a => a.Name, language).ToString(); if (htmlEncode) { attributeName = HttpUtility.HtmlEncode(attributeName); } attributeStr = $"{attributeName}: {attributeText}"; } } else { // Other attributes (textbox, datepicker...) attributeStr = $"{currentAttribute.GetLocalized(a => a.Name, language)}: {currentValue}"; if (htmlEncode) { attributeStr = HttpUtility.HtmlEncode(attributeStr); } } } else { if (int.TryParse(currentValue, out var id)) { var attributeValue = attributeValues.Where(x => x.Id == id).FirstOrDefault(); if (attributeValue != null) { attributeStr = $"{currentAttribute.GetLocalized(x => x.Name, language)}: {attributeValue.GetLocalized(x => x.Name, language)}"; if (renderPrices) { var adjustment = await _taxCalculator.CalculateCheckoutAttributeTaxAsync(attributeValue, customer : customer); if (adjustment.Price > 0m) { var convertedAdjustment = _currencyService.ConvertToWorkingCurrency(adjustment.Price); attributeStr += $" [+{_currencyService.ApplyTaxFormat(convertedAdjustment).ToString()}]"; } } } if (htmlEncode) { attributeStr = HttpUtility.HtmlEncode(attributeStr); } } } if (attributeStr.HasValue()) { if (i != 0 || j != 0) { sb.Append(serapator); } sb.Append(attributeStr); } } } return(sb.ToString()); }