Repository navigation
Expand file tree
/
Copy pathBlogController.cs
More file actions
474 lines (398 loc) · 18.6 KB
/
Copy pathBlogController.cs
File metadata and controls
474 lines (398 loc) · 18.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web.Mvc;
using System.Web.Routing;
using SmartStore.Core;
using SmartStore.Core.Caching;
using SmartStore.Core.Domain.Blogs;
using SmartStore.Core.Domain.Customers;
using SmartStore.Core.Domain.Localization;
using SmartStore.Core.Domain.Media;
using SmartStore.Core.Logging;
using SmartStore.Services.Blogs;
using SmartStore.Services.Common;
using SmartStore.Services.Customers;
using SmartStore.Services.Helpers;
using SmartStore.Services.Localization;
using SmartStore.Services.Media;
using SmartStore.Services.Messages;
using SmartStore.Services.Seo;
using SmartStore.Services.Stores;
using SmartStore.Utilities;
using SmartStore.Web.Framework.Controllers;
using SmartStore.Web.Framework.Filters;
using SmartStore.Web.Framework.Modelling;
using SmartStore.Web.Framework.Security;
using SmartStore.Web.Framework.UI.Captcha;
using SmartStore.Web.Infrastructure.Cache;
using SmartStore.Web.Models.Blogs;
namespace SmartStore.Web.Controllers
{
[RequireHttpsByConfigAttribute(SslRequirement.No)]
public partial class BlogController : PublicControllerBase
{
#region Fields
private readonly IBlogService _blogService;
private readonly IWorkContext _workContext;
private readonly IStoreContext _storeContext;
private readonly IPictureService _pictureService;
private readonly ILocalizationService _localizationService;
private readonly ICustomerContentService _customerContentService;
private readonly IDateTimeHelper _dateTimeHelper;
private readonly IWorkflowMessageService _workflowMessageService;
private readonly IWebHelper _webHelper;
private readonly ICacheManager _cacheManager;
private readonly ICustomerActivityService _customerActivityService;
private readonly IStoreMappingService _storeMappingService;
private readonly ILanguageService _languageService;
private readonly MediaSettings _mediaSettings;
private readonly BlogSettings _blogSettings;
private readonly LocalizationSettings _localizationSettings;
private readonly CustomerSettings _customerSettings;
private readonly CaptchaSettings _captchaSettings;
#endregion
#region Constructors
public BlogController(IBlogService blogService,
IWorkContext workContext,
IStoreContext storeContext,
IPictureService pictureService,
ILocalizationService localizationService,
ICustomerContentService customerContentService,
IDateTimeHelper dateTimeHelper,
IWorkflowMessageService workflowMessageService,
IWebHelper webHelper,
ICacheManager cacheManager,
ICustomerActivityService customerActivityService,
IStoreMappingService storeMappingService,
ILanguageService languageService,
MediaSettings mediaSettings,
BlogSettings blogSettings,
LocalizationSettings localizationSettings,
CustomerSettings customerSettings,
CaptchaSettings captchaSettings)
{
this._blogService = blogService;
this._workContext = workContext;
this._storeContext = storeContext;
this._pictureService = pictureService;
this._localizationService = localizationService;
this._customerContentService = customerContentService;
this._dateTimeHelper = dateTimeHelper;
this._workflowMessageService = workflowMessageService;
this._webHelper = webHelper;
this._cacheManager = cacheManager;
this._customerActivityService = customerActivityService;
this._storeMappingService = storeMappingService;
this._languageService = languageService;
this._mediaSettings = mediaSettings;
this._blogSettings = blogSettings;
this._localizationSettings = localizationSettings;
this._customerSettings = customerSettings;
this._captchaSettings = captchaSettings;
}
#endregion
#region Utilities
[NonAction]
protected void PrepareBlogPostModel(BlogPostModel model, BlogPost blogPost, bool prepareComments)
{
if (blogPost == null)
throw new ArgumentNullException("blogPost");
if (model == null)
throw new ArgumentNullException("model");
model.Id = blogPost.Id;
model.MetaTitle = blogPost.MetaTitle;
model.MetaDescription = blogPost.MetaDescription;
model.MetaKeywords = blogPost.MetaKeywords;
model.SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false);
model.Title = blogPost.Title;
model.Body = blogPost.Body;
model.AllowComments = blogPost.AllowComments;
model.AvatarPictureSize = _mediaSettings.AvatarPictureSize;
model.CreatedOn = _dateTimeHelper.ConvertToUserTime(blogPost.CreatedOnUtc, DateTimeKind.Utc);
model.Tags = blogPost.ParseTags().ToList();
model.NumberOfComments = blogPost.ApprovedCommentCount;
model.AddNewComment.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage;
model.AllowCustomersToUploadAvatars = _customerSettings.AllowCustomersToUploadAvatars;
if (prepareComments)
{
var blogComments = blogPost.BlogComments.Where(pr => pr.IsApproved).OrderBy(pr => pr.CreatedOnUtc);
foreach (var bc in blogComments)
{
var commentModel = new BlogCommentModel()
{
Id = bc.Id,
CustomerId = bc.CustomerId,
CustomerName = bc.Customer.FormatUserName(),
CommentText = bc.CommentText,
CreatedOn = _dateTimeHelper.ConvertToUserTime(bc.CreatedOnUtc, DateTimeKind.Utc),
AllowViewingProfiles = _customerSettings.AllowViewingProfiles && bc.Customer != null && !bc.Customer.IsGuest()
};
if (_customerSettings.AllowCustomersToUploadAvatars)
{
var customer = bc.Customer;
string avatarUrl = _pictureService.GetPictureUrl(customer.GetAttribute<int>(SystemCustomerAttributeNames.AvatarPictureId), _mediaSettings.AvatarPictureSize, false);
if (String.IsNullOrEmpty(avatarUrl) && _customerSettings.DefaultAvatarEnabled)
avatarUrl = _pictureService.GetDefaultPictureUrl(_mediaSettings.AvatarPictureSize, PictureType.Avatar);
commentModel.CustomerAvatarUrl = avatarUrl;
}
model.Comments.Add(commentModel);
}
}
}
[NonAction]
protected BlogPostListModel PrepareBlogPostListModel(BlogPagingFilteringModel command)
{
if (command == null)
throw new ArgumentNullException("command");
var model = new BlogPostListModel();
model.PagingFilteringContext.Tag = command.Tag;
model.PagingFilteringContext.Month = command.Month;
model.WorkingLanguageId = _workContext.WorkingLanguage.Id;
if (command.PageSize <= 0)
command.PageSize = _blogSettings.PostsPageSize;
if (command.PageNumber <= 0)
command.PageNumber = 1;
DateTime? dateFrom = command.GetFromMonth();
DateTime? dateTo = command.GetToMonth();
IPagedList<BlogPost> blogPosts;
if (String.IsNullOrEmpty(command.Tag))
{
blogPosts = _blogService.GetAllBlogPosts(_storeContext.CurrentStore.Id,
_workContext.WorkingLanguage.Id,
dateFrom, dateTo, command.PageNumber - 1, command.PageSize);
}
else
{
blogPosts = _blogService.GetAllBlogPostsByTag(_storeContext.CurrentStore.Id,
_workContext.WorkingLanguage.Id,
command.Tag, command.PageNumber - 1, command.PageSize);
}
model.PagingFilteringContext.LoadPagedList(blogPosts);
model.BlogPosts = blogPosts
.Select(x =>
{
var blogPostModel = new BlogPostModel();
PrepareBlogPostModel(blogPostModel, x, false);
return blogPostModel;
})
.ToList();
return model;
}
#endregion
#region Methods
public ActionResult List(BlogPagingFilteringModel command)
{
if (!_blogSettings.Enabled)
return HttpNotFound();
var model = PrepareBlogPostListModel(command);
return View("List", model);
}
public ActionResult BlogByTag(BlogPagingFilteringModel command)
{
if (!_blogSettings.Enabled)
return HttpNotFound();
var model = PrepareBlogPostListModel(command);
return View("List", model);
}
public ActionResult BlogByMonth(BlogPagingFilteringModel command)
{
if (!_blogSettings.Enabled)
return HttpNotFound();
var model = PrepareBlogPostListModel(command);
return View("List", model);
}
[Compress]
public ActionResult ListRss(int languageId)
{
DateTime? maxAge = null;
var protocol = _webHelper.IsCurrentConnectionSecured() ? "https" : "http";
var selfLink = Url.RouteUrl("BlogRSS", new { languageId = languageId }, protocol);
var blogLink = Url.RouteUrl("Blog", null, protocol);
var title = "{0} - Blog".FormatInvariant(_storeContext.CurrentStore.Name);
if (_blogSettings.MaxAgeInDays > 0)
maxAge = DateTime.UtcNow.Subtract(new TimeSpan(_blogSettings.MaxAgeInDays, 0, 0, 0));
var language = _languageService.GetLanguageById(languageId);
var feed = new SmartSyndicationFeed(new Uri(blogLink), title);
feed.AddNamespaces(false);
feed.Init(selfLink, language);
if (!_blogSettings.Enabled)
return new RssActionResult { Feed = feed };
var items = new List<SyndicationItem>();
var blogPosts = _blogService.GetAllBlogPosts(_storeContext.CurrentStore.Id, languageId, null, null, 0, int.MaxValue, false, maxAge);
foreach (var blogPost in blogPosts)
{
var blogPostUrl = Url.RouteUrl("BlogPost", new { SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false) }, "http");
var item = feed.CreateItem(blogPost.Title, blogPost.Body, blogPostUrl, blogPost.CreatedOnUtc);
items.Add(item);
}
feed.Items = items;
return new RssActionResult { Feed = feed };
}
public ActionResult BlogPost(int blogPostId)
{
if (!_blogSettings.Enabled)
return HttpNotFound();
var blogPost = _blogService.GetBlogPostById(blogPostId);
if (blogPost == null ||
(blogPost.StartDateUtc.HasValue && blogPost.StartDateUtc.Value >= DateTime.UtcNow) ||
(blogPost.EndDateUtc.HasValue && blogPost.EndDateUtc.Value <= DateTime.UtcNow))
return HttpNotFound();
//Store mapping
if (!_storeMappingService.Authorize(blogPost))
return HttpNotFound();
var model = new BlogPostModel();
PrepareBlogPostModel(model, blogPost, true);
return View(model);
}
[HttpPost, ActionName("BlogPost")]
[FormValueRequired("add-comment")]
[CaptchaValidator]
public ActionResult BlogCommentAdd(int blogPostId, BlogPostModel model, bool captchaValid)
{
if (!_blogSettings.Enabled)
return HttpNotFound();
var blogPost = _blogService.GetBlogPostById(blogPostId);
if (blogPost == null || !blogPost.AllowComments)
return HttpNotFound();
if (_workContext.CurrentCustomer.IsGuest() && !_blogSettings.AllowNotRegisteredUsersToLeaveComments)
{
ModelState.AddModelError("", _localizationService.GetResource("Blog.Comments.OnlyRegisteredUsersLeaveComments"));
}
//validate CAPTCHA
if (_captchaSettings.Enabled && _captchaSettings.ShowOnBlogCommentPage && !captchaValid)
{
ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptcha"));
}
if (ModelState.IsValid)
{
var comment = new BlogComment()
{
BlogPostId = blogPost.Id,
CustomerId = _workContext.CurrentCustomer.Id,
IpAddress = _webHelper.GetCurrentIpAddress(),
CommentText = model.AddNewComment.CommentText,
IsApproved = true,
CreatedOnUtc = DateTime.UtcNow,
UpdatedOnUtc = DateTime.UtcNow,
};
_customerContentService.InsertCustomerContent(comment);
//update totals
_blogService.UpdateCommentTotals(blogPost);
//notify a store owner
if (_blogSettings.NotifyAboutNewBlogComments)
_workflowMessageService.SendBlogCommentNotificationMessage(comment, _localizationSettings.DefaultAdminLanguageId);
//activity log
_customerActivityService.InsertActivity("PublicStore.AddBlogComment", _localizationService.GetResource("ActivityLog.PublicStore.AddBlogComment"));
NotifySuccess(T("Blog.Comments.SuccessfullyAdded"));
var url = UrlHelper.GenerateUrl(
routeName: "BlogPost",
actionName: null,
controllerName: null,
protocol: null,
hostName: null,
fragment: "new-comment",
routeValues: new RouteValueDictionary(new { blogPostId = blogPost.Id, SeName = blogPost.GetSeName(blogPost.LanguageId, ensureTwoPublishedLanguages: false) }),
routeCollection: System.Web.Routing.RouteTable.Routes,
requestContext: this.ControllerContext.RequestContext,
includeImplicitMvcValues: true /*helps fill in the nulls above*/
);
return Redirect(url);
}
//If we got this far, something failed, redisplay form
PrepareBlogPostModel(model, blogPost, true);
return View(model);
}
[ChildActionOnly]
//[OutputCache(Duration = 120, VaryByCustom = "WorkingLanguage")]
public ActionResult BlogTags()
{
if (!_blogSettings.Enabled)
return Content("");
var cacheKey = string.Format(ModelCacheEventConsumer.BLOG_TAGS_MODEL_KEY, _workContext.WorkingLanguage.Id, _storeContext.CurrentStore.Id);
var cachedModel = _cacheManager.Get(cacheKey, () =>
{
var model = new BlogPostTagListModel();
//get tags
var tags = _blogService.GetAllBlogPostTags(_storeContext.CurrentStore.Id, _workContext.WorkingLanguage.Id)
.OrderByDescending(x => x.BlogPostCount)
.Take(_blogSettings.NumberOfTags)
.ToList();
//sorting
tags = tags.OrderBy(x => x.Name).ToList();
foreach (var tag in tags)
model.Tags.Add(new BlogPostTagModel()
{
Name = tag.Name,
BlogPostCount = tag.BlogPostCount
});
return model;
});
return PartialView(cachedModel);
}
[ChildActionOnly]
//[OutputCache(Duration = 120, VaryByCustom = "WorkingLanguage")]
public ActionResult BlogMonths()
{
if (!_blogSettings.Enabled)
return Content("");
var cacheKey = string.Format(ModelCacheEventConsumer.BLOG_MONTHS_MODEL_KEY, _workContext.WorkingLanguage.Id, _storeContext.CurrentStore.Id);
var cachedModel = _cacheManager.Get(cacheKey, () =>
{
var model = new List<BlogPostYearModel>();
var blogPosts = _blogService.GetAllBlogPosts(_storeContext.CurrentStore.Id,
_workContext.WorkingLanguage.Id, null, null, 0, int.MaxValue);
if (blogPosts.Count > 0)
{
var months = new SortedDictionary<DateTime, int>();
var first = blogPosts[blogPosts.Count - 1].CreatedOnUtc;
while (DateTime.SpecifyKind(first, DateTimeKind.Utc) <= DateTime.UtcNow.AddMonths(1))
{
var list = blogPosts.GetPostsByDate(new DateTime(first.Year, first.Month, 1), new DateTime(first.Year, first.Month, 1).AddMonths(1).AddSeconds(-1));
if (list.Count > 0)
{
var date = new DateTime(first.Year, first.Month, 1);
months.Add(date, list.Count);
}
first = first.AddMonths(1);
}
int current = 0;
foreach (var kvp in months)
{
var date = kvp.Key;
var blogPostCount = kvp.Value;
if (current == 0)
current = date.Year;
if (date.Year > current || model.Count == 0)
{
var yearModel = new BlogPostYearModel()
{
Year = date.Year
};
model.Add(yearModel);
}
model.Last().Months.Add(new BlogPostMonthModel()
{
Month = date.Month,
BlogPostCount = blogPostCount
});
current = date.Year;
}
}
return model;
});
return PartialView(cachedModel);
}
[ChildActionOnly]
public ActionResult RssHeaderLink()
{
if (!_blogSettings.Enabled || !_blogSettings.ShowHeaderRssUrl)
return Content("");
string link = string.Format("<link href=\"{0}\" rel=\"alternate\" type=\"application/rss+xml\" title=\"{1} - Blog\" />",
Url.RouteUrl("BlogRSS", new { languageId = _workContext.WorkingLanguage.Id }, _webHelper.IsCurrentConnectionSecured() ? "https" : "http"), _storeContext.CurrentStore.Name);
return Content(link);
}
#endregion
}
}