-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlogController.cfc
More file actions
1316 lines (1147 loc) · 40.9 KB
/
BlogController.cfc
File metadata and controls
1316 lines (1147 loc) · 40.9 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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Frontend blog page
component extends="app.Controllers.Controller" {
// Configuration function
function config() {
super.config();
verifies(
except = "index,create,store,show,update,destroy,loadCategories,loadStatuses,loadPostTypes,Categories,blogs,comment,feed,error,checkTitle,edit,update,AuthorProfileBlogs,blogSearch,commentsFeed,unpublish,myPosts",
params = "key",
paramsTypes = "integer",
handler = "index"
);
filters(through = "restrictAccess", only = "create,store,comment,edit,update,myPosts");
usesLayout("/layout");
}
// Function to list all blogs
public void function index() {
isEditor = hasEditorAccess();
}
public void function myPosts() {
var userId = getSignedInUserId();
var validStatuses = "all,draft,published,pending";
statusFilter = (StructKeyExists(params, "status") && ListFindNoCase(validStatuses, params.status))
? params.status
: "all";
// Expose statuses to view (controller methods aren't available in views)
statuses = blogStatuses();
var statusCountsQuery = model("Blog").findAll(
select = "statusId, COUNT(*) as cnt",
where = "createdBy = #userId# AND blog_posts.statusId <> #statuses.TRASH#",
group = "statusId",
returnAs = "query"
);
statusCounts = {"all" = 0, "draft" = 0, "published" = 0, "pending" = 0};
for (var row in statusCountsQuery) {
statusCounts.all += row.cnt;
if (row.statusId == statuses.DRAFT) statusCounts.draft = row.cnt;
else if (row.statusId == statuses.POSTED) statusCounts.published = row.cnt;
else if (row.statusId == statuses.PENDING_REVIEW) statusCounts.pending = row.cnt;
}
var where = "createdBy = #userId# AND blog_posts.statusId <> #statuses.TRASH#";
if (statusFilter == "draft") {
where &= " AND blog_posts.statusId = #statuses.DRAFT#";
} else if (statusFilter == "published") {
where &= " AND blog_posts.statusId = #statuses.POSTED#";
} else if (statusFilter == "pending") {
where &= " AND blog_posts.statusId = #statuses.PENDING_REVIEW#";
}
myBlogs = model("Blog").findAll(
select = "id, title, slug, statusId, createdAt, publishedAt, updatedAt",
where = where,
order = "updatedAt DESC"
);
}
public void function blogs() {
// Initialize default values and sanitize inputs
filterType = sanitizeParam(StructKeyExists(params, "filterType") ? params.filterType : "", "");
filterValue = sanitizeParam(StructKeyExists(params, "filterValue") ? params.filterValue : "", "");
page = StructKeyExists(params, "page") ? Max(1, Val(sanitizeParam(params.page, 1))) : 1;
perPage = StructKeyExists(params, "perPage") ? Max(1, Min(24, Val(sanitizeParam(params.perPage, 6)))) : 6;
isInfiniteScroll = StructKeyExists(params, "infiniteScroll") ? params.infiniteScroll : false;
userId = getSignedInUserId();
try {
var result = getBlogData(filterType, filterValue, page, perPage, isInfiniteScroll);
if (result.query.recordCount == 0) {
// Show fallback blogs
var fallback = getBlogData("", "", 1, perPage, isInfiniteScroll);
blogs = fallback.query;
isFallback = true;
} else {
blogs = result.query;
isFallback = false;
}
// Set template variables
hasMore = result.hasMore;
totalCount = result.totalCount;
// Set author info if filtering by author
if (StructKeyExists(result, "author")) {
author = result.author;
}
renderPartial(partial = "partials/blogList");
} catch (any e) {
handleBlogError(e, userId, page, perPage, isInfiniteScroll);
}
}
// Helper function to sanitize parameters
private string function sanitizeParam(param, defaultValue) {
if (!StructKeyExists(arguments, "param") || !Len(Trim(arguments.param))) {
return arguments.defaultValue;
}
return Trim(arguments.param);
}
// Main data retrieval logic
private struct function getBlogData(filterType, filterValue, page, perPage, isInfiniteScroll) {
var result = {};
// Handle special cases first
if (Len(arguments.filterType) && Len(arguments.filterValue)) {
// Normalize filter value (convert hyphens to dots)
arguments.filterValue = Replace(arguments.filterValue, "-", ".", "all");
// Handle date archive filtering (year/month)
if (IsNumeric(arguments.filterType) && IsNumeric(arguments.filterValue)) {
return getBlogsByMonthYear(
arguments.filterType,
arguments.filterValue,
arguments.page,
arguments.perPage,
arguments.isInfiniteScroll
);
}
// Handle content filtering
switch (LCase(arguments.filterType)) {
case "category":
return getBlogsByCategory(
arguments.filterValue,
arguments.page,
arguments.perPage,
arguments.isInfiniteScroll
);
case "tag":
return getAllByTag(arguments.filterValue, arguments.page, arguments.perPage, arguments.isInfiniteScroll);
case "author":
return getBlogsWithAuthorData(
arguments.filterValue,
arguments.page,
arguments.perPage,
arguments.isInfiniteScroll
);
default:
// Invalid filter type, fallback to all blogs
logInvalidFilter(arguments.filterType, arguments.filterValue);
return getAllBlogs(arguments.page, arguments.perPage, arguments.isInfiniteScroll);
}
}
// Default: return all blogs
return getAllBlogs(arguments.page, arguments.perPage, arguments.isInfiniteScroll);
}
// Optimized author blog retrieval with author data
private struct function getBlogsWithAuthorData(authorIdentifier, page, perPage, isInfiniteScroll) {
var authorId = getBlogAuthorId(arguments.authorIdentifier);
var result = getBlogsByAuthor(authorId, arguments.page, arguments.perPage, arguments.isInfiniteScroll);
// Get author statistics in a single optimized query if possible
var authorStats = getAuthorStatistics(authorId);
result.author = {
"id" = authorId,
"totalposts" = authorStats.totalPosts,
"totalcomments" = authorStats.totalComments
};
return result;
}
// author statistics retrieval
private struct function getAuthorStatistics(authorId) {
// Try to get both stats in one query if your database supports it
try {
return {
"totalPosts" = model("Blog").count(where = "createdBy = #arguments.authorId#"),
"totalComments" = model("Comment").count(where = "authorId = #arguments.authorId#")
};
} catch (any e) {
model("Log").log(
category = "wheels.blog",
level = "ERROR",
message = "Error retrieving author statistics",
details = {"error_message" = e.message, "author_id" = arguments.authorId, "ip_address" = cgi.REMOTE_ADDR},
userId = getSignedInUserId()
);
return {"totalPosts" = 0, "totalComments" = 0};
}
}
// Log invalid filter attempts
private void function logInvalidFilter(filterType, filterValue) {
model("Log").log(
category = "wheels.blog",
level = "WARN",
message = "Invalid filter type attempted",
details = {
"invalid_filter_type" = arguments.filterType,
"filter_value" = arguments.filterValue,
"ip_address" = cgi.REMOTE_ADDR
},
userId = getSignedInUserId()
);
}
// Centralized error handling
private void function handleBlogError(error, userId, page, perPage, isInfiniteScroll) {
// Log the error
model("Log").log(
category = "wheels.blog",
level = "ERROR",
message = "Error in blogs(): #arguments.error.message#",
details = {
"error_message" = arguments.error.message,
"error_detail" = arguments.error.detail ?: "",
"error_type" = arguments.error.type ?: "",
"stack_trace" = arguments.error.stackTrace ?: "",
"ip_address" = cgi.REMOTE_ADDR,
"timestamp" = Now()
},
userId = arguments.userId
);
// Provide fallback data
try {
var fallbackResult = getAllBlogs(1, arguments.perPage, arguments.isInfiniteScroll);
blogs = fallbackResult.query;
hasMore = fallbackResult.hasMore;
totalCount = fallbackResult.totalCount;
// Set error flag for template
hasError = true;
errorMessage = "We're experiencing some technical difficulties. Showing recent posts instead.";
} catch (any fallbackError) {
// If even fallback fails, create empty result
blogs = QueryNew(
"id,title,slug,createdby,publishedAt,fullName,username,profilePicture",
"integer,varchar,varchar,integer,date,varchar,varchar,varchar"
);
hasMore = false;
totalCount = 0;
hasError = true;
errorMessage = "Unable to load blog posts at this time. Please try again later.";
}
renderPartial(partial = "partials/blogList");
}
// Function to edit a blog post
public void function edit() {
try {
// Check if user is logged in
if (!hasEditorAccess()) {
redirectTo(route = "blog");
return;
}
// Get the blog post
blog = model("Blog").findByKey(key = params.id, include = "User,PostStatus");
// Check if blog exists
if (!IsObject(blog)) {
Throw("Blog not found", "BlogNotFound");
}
// Check if user has permission to edit this post
if (!hasEditorAccess() && blog.createdBy != session.userID) {
Throw("You don't have permission to edit this post", "UnauthorizedAccess");
}
// Get categories and tags for the form
categories = model("Category").findAll(order = "name ASC");
postTypes = model("PostType").findAll(order = "name ASC");
var blogCategories = model("BlogCategory").findAll(where = "blogId = #blog.id#");
var blogTags = model("BlogTag").findAll(where = "blogId = #blog.id#", include = "Tag");
// Prepare data for the view
var selectedCategories = [];
for (var cat in blogCategories) {
ArrayAppend(selectedCategories, Val(cat.categoryId));
}
var selectedTags = [];
for (var blogTag in blogTags) {
ArrayAppend(selectedTags, blogTag.name);
}
// Set view variables
blog.categories = selectedCategories;
blog.tags = ArrayToList(selectedTags, ",");
isEdit = true;
renderView(template = "create");
} catch (any e) {
// Log the error
model("Log").log(
category = "wheels.blog",
level = "ERROR",
message = "Error editing blog post: #e.message#",
details = {
"error" = e,
"blog_id" = StructKeyExists(params, "key") ? params.key : "",
"user_id" = getSignedInUserId(),
"ip_address" = cgi.REMOTE_ADDR
}
);
// Redirect with error message
redirectTo(route = "blog");
}
}
private function getBlogsByAuthor(
required authorId,
numeric page = 1,
numeric perPage = 6,
boolean isInfiniteScroll = false
) {
var result = {
query = model("Blog").findAll(
where = "blog_posts.statusId <> #blogStatuses().DRAFT# AND blog_posts.status = 'Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#' AND blog_posts.createdBy = #arguments.authorId#",
include = "User",
order = "publishedAt DESC",
page = arguments.page,
perPage = arguments.perPage
),
hasMore = false,
totalCount = 0
};
result.totalCount = model("Blog").count(
where = "blog_posts.statusId <> #blogStatuses().DRAFT# AND blog_posts.status = 'Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#' AND blog_posts.createdBy = #arguments.authorId#"
);
result.hasMore = (page * perPage) < result.totalCount;
if (result.query.recordCount == 0) {
redirectTo(route = "blog");
}
return result;
}
private function getBlogAuthorId(required authorParam) {
// Check if authorParam is numeric (ID) or string (username)
if (IsNumeric(authorParam)) {
return Val(authorParam);
} else {
// Lookup user by username
var user = model("user").findOne(where = "username = '#arguments.authorParam#'");
if (IsObject(user)) {
return user.id;
} else {
// User not found, redirect
redirectTo(route = "blog");
return false;
}
}
}
function blogSearch() {
param name="params.searchTerm" default="";
param name="params.page" default="1";
param name="params.perPage" default="6";
param name="params.infiniteScroll" default="false";
param name="params.isSearched" default="false";
searchTerm = params.searchTerm;
page = params.page;
perPage = params.perPage;
isInfiniteScroll = params.infiniteScroll;
if (Len(Trim(searchTerm))) {
var searchPattern = "%#searchTerm#%";
var query = model("blog").findAll(
where = "blog_posts.status ='Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#' AND (blog_posts.slug LIKE '#searchPattern#' OR blog_posts.title LIKE '#searchPattern#' OR blog_posts.content LIKE '#searchPattern#' OR fullname LIKE '#searchPattern#' OR email LIKE '#searchPattern#')",
include = "User, PostStatus, PostType",
order = "publishedAt DESC",
page = page,
perPage = perPage
);
if (isInfiniteScroll) {
totalCount = model("blog").count(
include = "User, PostStatus, PostType",
where = "blog_posts.status ='Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#' AND (blog_posts.slug LIKE '#searchPattern#' OR blog_posts.title LIKE '#searchPattern#' OR blog_posts.content LIKE '#searchPattern#' OR fullname LIKE '#searchPattern#' OR email LIKE '#searchPattern#')"
);
hasMore = (page * perPage) < totalCount;
isSearched = true;
query.addColumn("hasMore", "boolean");
query.addColumn("totalCount", "integer");
}
blogs = query;
if (blogs.recordCount == 0) {
isFallBack = true;
result = getAllBlogs(page, perPage, isInfiniteScroll);
blogs = result.query;
}
renderPartial(partial = "partials/blogList");
} else {
// return all publish blogs with pagination
result = getAllBlogs(page, perPage, isInfiniteScroll);
blogs = result.query;
hasMore = result.hasMore;
totalCount = result.totalCount;
renderPartial(partial = "partials/blogList");
}
}
// Function to load categories for the blog list
function categories() {
categorylist = model("Category").findAll(where = "isActive = 1", cache = 60);
renderPartial(partial = "partials/categorylist");
}
// Function to show the create blog form
function create() {
if (!hasEditorAccess()) {
redirectTo(route = "blog");
return;
}
categories = model("Category").findAll(order = "name ASC");
postTypes = model("PostType").findAll(order = "name ASC");
model("Log").log(
category = "wheels.blog",
level = "INFO",
message = "Blog creation form accessed",
details = {"ip_address" = cgi.REMOTE_ADDR},
userId = getSignedInUserId()
);
saveRedirectUrl(cgi.script_name & "?" & cgi.query_string);
isEdit = false;
}
// Function to store a new blog
public void function store() {
// Get request parameters
var blogModel = model("Blog");
try {
// Check if user has editor access
if (!hasEditorAccess()) {
Throw("You don't have permission to create a blog post", "UnauthorizedAccess");
}
model("Log").log(
category = "wheels.blog",
level = "INFO",
message = "New blog post creation attempted",
details = {"title" = params.title, "ip_address" = cgi.REMOTE_ADDR},
userId = getSignedInUserId()
);
params.coverImagePath = "";
var uploadPath = ExpandPath("/files/"); // Define the upload directory
if (!DirectoryExists(uploadPath)) {
DirectoryCreate(uploadPath);
}
// Handle file upload
if (StructKeyExists(params, "attachment") && IsDefined("params.attachment")) {
var uploadedFile = FileUpload(uploadPath, "attachment");
if (!StructIsEmpty(uploadedFile) && StructKeyExists(uploadedFile, "serverFile")) {
var originalFileName = uploadedFile.serverFile;
var fileExtension = LCase(ListLast(originalFileName, "."));
var allowedExtensions = "jpg,jpeg,png,gif,webp,pdf,doc,docx";
var allowedContentTypes = "image/jpeg,image/png,image/gif,image/webp,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document";
var maxFileSizeBytes = 10 * 1024 * 1024; // 10MB
// Validate file extension
if (!ListFindNoCase(allowedExtensions, fileExtension)) {
FileDelete(uploadedFile.serverDirectory & "/" & originalFileName);
Throw("Invalid file type. Allowed types: #allowedExtensions#", "InvalidFileType");
}
// Validate MIME content type
if (StructKeyExists(uploadedFile, "contentType") && StructKeyExists(uploadedFile, "contentSubType")) {
var detectedContentType = uploadedFile.contentType & "/" & uploadedFile.contentSubType;
if (!ListFindNoCase(allowedContentTypes, detectedContentType)) {
FileDelete(uploadedFile.serverDirectory & "/" & originalFileName);
Throw("Invalid file content type. The uploaded file does not match allowed types.", "InvalidContentType");
}
}
// Validate file size
if (uploadedFile.fileSize > maxFileSizeBytes) {
FileDelete(uploadedFile.serverDirectory & "/" & originalFileName);
Throw("File size exceeds the 10MB limit.", "FileTooLarge");
}
var uniqueFileName = CreateUUID() & "." & fileExtension;
// Rename file to unique name
var newFilePath = uploadPath & "/" & uniqueFileName;
FileMove(uploadedFile.serverDirectory & "/" & originalFileName, newFilePath);
// Store the relative file path
params.coverImagePath = "/files/" & uniqueFileName;
}
}
response = saveBlog(params);
saveTags(params, response.blogId);
saveCategories(params, response.blogId);
model("Log").log(
category = "wheels.blog",
level = "INFO",
message = "New blog post created successfully",
details = {"blog_id" = response.blogId, "title" = params.title, "ip_address" = cgi.REMOTE_ADDR},
userId = getSignedInUserId()
);
renderText(response.message);
} catch (any e) {
model("Log").log(
category = "wheels.blog",
level = "ERROR",
message = "Failed to save blog post",
details = {
"error_message" = e.message,
"error_detail" = e.detail,
"error_type" = e.type,
"title" = params.title,
"ip_address" = cgi.REMOTE_ADDR
},
userId = getSignedInUserId()
);
// Handle error
redirectTo(action = "error", errorMessage = "Failed to save blog post.");
}
}
// Function to show a specific blog
function show() {
try {
blogModel = model("Blog");
// Get the blog by its slug
blog = getBlogBySlug(params.slug);
// If no blog is found, throw an error to be caught
if (!StructKeyExists(blog, "id")) {
Throw("Blog not found");
}
// Process embeds in content
blog.content = embedAndAutoLink(blog.content);
// Set blog post data for layout meta tags (avoids DB query in view)
request.blogPostForMeta = blog;
// Get other necessary data
tags = getTagsByBlogid(blog.id);
categories = getCategoriesByBlogid(blog.id);
attachments = getAttachmentsByBlogid(blog.id);
comments = getAllCommentsByBlogid(blog.id);
allBlogComments = model("Comment").findAll(
include = "User",
where = "isPublished = 1 AND blogid = #blog.id#",
order = "commentParentId, createdAt",
cache = 5
);
// Track reading history
if (StructKeyExists(session, "userID")) {
history = model("ReadingHistory").findOne(
where = "userId = #session.userID# AND blogId = #blog.id#",
includeSoftDeletes = true
);
if (IsObject(history)) {
if (history.deletedAt != "") {
history.update(lastReadAt = Now(), deletedAt = "");
} else {
history.update(lastReadAt = Now());
}
} else {
history = model("ReadingHistory").create(userId = session.userID, blogId = blog.id, lastReadAt = Now());
}
// Check if bookmarked
isBookmarked = model("Bookmark").exists(where = "userId = #session.userID# AND blogId = #blog.id#");
} else {
isBookmarked = false;
}
} catch (any e) {
model("Log").log(
category = "wheels.blog",
level = "ERROR",
message = "Blog post not found",
details = {
"error_message" = e.message,
"error_detail" = e.detail,
"slug" = params.slug,
"ip_address" = cgi.REMOTE_ADDR
},
userId = getSignedInUserId()
);
redirectTo(action = "index");
return;
}
}
// Function to update an existing blog
public function update() {
var blogId = params.id;
result = {success = false, message = "", blogId = blogId};
try {
model("Log").log(
category = "wheels.blog",
level = "INFO",
message = "Blog post update attempted",
details = {"blog_id" = blogId, "title" = params.title, "ip_address" = cgi.REMOTE_ADDR},
userId = getSignedInUserId()
);
params.isDraft = IsNumeric(params.isDraft) ? params.isDraft : 0;
// Allow title change and check uniqueness
if (StructKeyExists(params, "title")) {
var existingBlog = model("Blog").findFirst(where = "title = '#params.title#' AND id != #blogId#");
if (IsObject(existingBlog)) {
result.success = false;
result.message = "A blog post with this title already exists.";
model("Log").log(
category = "wheels.blog",
level = "DEBUG",
message = "[UPDATE] Duplicate title found",
details = {"blog_id" = blogId, "title" = params.title},
userId = getSignedInUserId()
);
renderWith(data = result, hideDebugInformation = true, layout = '/responseLayout');
return;
}
}
transaction {
result = updateBlog(params, blogId);
if (!result.success) {
Throw(type = "BlogUpdateFailed", message = result.message);
}
deleteBlogTags(blogId);
deleteBlogCategories(blogId);
if (StructKeyExists(params, "postTags") && Len(Trim(params.postTags))) {
params.tags = params.postTags;
saveTags(params, blogId);
}
if (StructKeyExists(params, "categoryId") && Len(Trim(params.categoryId))) {
saveCategories(params, blogId);
}
}
model("Log").log(
category = "wheels.blog",
level = "INFO",
message = "Blog post updated successfully",
details = {"blog_id" = blogId, "title" = params.title, "ip_address" = cgi.REMOTE_ADDR},
userId = getSignedInUserId()
);
result.success = true;
if (!StructKeyExists(result, "message") || !Len(result.message)) {
result.message = "Blog post updated successfully.";
}
// Add redirectUrl to show page
result.redirectUrl = urlFor(action = "show", slug = params.slug);
} catch (any e) {
model("Log").log(
category = "wheels.blog",
level = "ERROR",
message = "Failed to update blog post",
details = {
"blog_id" = blogId,
"error_message" = e.message,
"error_detail" = e.detail,
"error_type" = e.type,
"title" = params.title,
"ip_address" = cgi.REMOTE_ADDR
},
userId = getSignedInUserId()
);
result.success = false;
result.message = "Failed to update blog post.";
}
renderWith(data = result, hideDebugInformation = true, layout = '/responseLayout');
return;
}
// function to check title is unique
function checkTitle() {
try {
model("Log").log(
category = "wheels.blog",
level = "DEBUG",
message = "Title uniqueness check",
details = {
"title" = form.title,
"id" = StructKeyExists(form, "id") ? form.id : 0,
"ip_address" = cgi.REMOTE_ADDR
},
userId = getSignedInUserId()
);
if (StructKeyExists(form, "title")) {
var whereClause = "title = '#form.title#'";
if (StructKeyExists(form, "id") && IsNumeric(form.id) && form.id > 0) {
whereClause &= " AND id != #form.id#";
}
var blogModel = model("Blog").findAll(where = whereClause);
if (blogModel.recordCount != 0) {
renderText('<span class="text-danger">A blog already exists with this title!</span><input type="hidden" id="titleExists" value="1">');
} else {
renderText('<span class="text-success">Title is available</span><input type="hidden" id="titleExists" value="0">');
}
}
} catch (any e) {
model("Log").log(
category = "wheels.blog",
level = "ERROR",
message = "Error checking title uniqueness",
details = {
"error_message" = e.message,
"error_detail" = e.detail,
"title" = form.title,
"id" = StructKeyExists(form, "id") ? form.id : 0,
"ip_address" = cgi.REMOTE_ADDR
},
userId = getSignedInUserId()
);
// Handle error
renderText('<span class="text-danger">Error checking title. Please try again.</span>');
}
}
// Function to delete a blog
function destroy() {
var blogModel = model("Blog"); // Get model instance
try {
model("Log").log(
category = "wheels.blog",
level = "INFO",
message = "Blog post deletion attempted",
details = {"blog_id" = params.id, "ip_address" = cgi.REMOTE_ADDR},
userId = getSignedInUserId()
);
var message = deleteBlog(params.id);
model("Log").log(
category = "wheels.blog",
level = "INFO",
message = "Blog post deleted successfully",
details = {"blog_id" = params.id, "ip_address" = cgi.REMOTE_ADDR},
userId = getSignedInUserId()
);
redirectTo(action = "index", success = "#message#");
} catch (any e) {
model("Log").log(
category = "wheels.blog",
level = "ERROR",
message = "Failed to delete blog post",
details = {
"error_message" = e.message,
"error_detail" = e.detail,
"blog_id" = params.id,
"ip_address" = cgi.REMOTE_ADDR
},
userId = getSignedInUserId()
);
// Handle error
redirectTo(action = "index", errorMessage = "Failed to delete blog post.");
}
}
// Function to load categories for the dropdown
function loadCategories() {
categories = model("Category").getAll();
renderPartial(partial = "partials/categories");
}
// Function to load statuses for the dropdown
function loadStatuses() {
statuses = model("PostStatus").getAll();
renderPartial(partial = "partials/statuses");
}
// Function to load post types for the dropdown
function loadPostTypes() {
postTypes = model("PostType").getAll();
renderPartial(partial = "partials/postTypes");
}
function error() {
renderPartial(partial = "partials/_error");
}
public function feed() {
// Fetch all blogs
blogPosts = model("Blog").findAll(
where = "blog_posts.status = 'Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#'",
include = "User",
order = "publishedAt DESC",
cache = 10
);
// Render the feed view
renderPartial(partial = "partials/feed");
}
public function commentsFeed() {
// Get recent comments with related blog post
comments = model("Comment").findAll(
where = "isPublished = 1",
include = "Blog",
order = "createdAt DESC",
limit = 20,
returnAs = "structs"
);
// Collect unique authorIds
authorIds = [];
for (key in comments) {
comment = comments[key];
if (IsStruct(comment) and StructKeyExists(comment, "authorId")) {
if (!ArrayContains(authorIds, comment.authorId)) {
ArrayAppend(authorIds, comment.authorId);
}
}
}
// Fetch all related users at once
var authorIdList = ArrayToList(authorIds);
authors = model("User").findAll(where = "id IN (#authorIdList#)", returnAs = "structs");
// Map authors by ID for quick lookup
authorMap = {};
for (key in authors) {
author = authors[key];
authorMap[author.id] = author;
}
renderPartial(partial = "partials/commentsFeed", locals = {comments = comments, authorMap = authorMap});
}
// Business Logic
private function getAllBlogs(numeric page = 1, numeric perPage = 6, boolean isInfiniteScroll = false) {
var result = {
query = model("Blog").findAll(
where = "blog_posts.statusId <> #blogStatuses().DRAFT# AND blog_posts.status = 'Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#'",
include = "User",
order = "publishedAt DESC",
page = arguments.page,
perPage = arguments.perPage,
cache = 5
),
hasMore = false,
totalCount = 0
};
result.totalCount = model("Blog").count(
where = "blog_posts.statusId <> #blogStatuses().DRAFT# AND blog_posts.status = 'Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#'",
cache = 5
);
result.hasMore = (page * perPage) < result.totalCount;
return result;
}
private function getBlogsByMonthYear(
required numeric year,
required string month,
numeric page = 1,
numeric perPage = 6,
boolean isInfiniteScroll = false
) {
// Create start and end date for the selected month
var startdate = "#year#-#NumberFormat(month, '00')#-01 00:00:00";
var enddate = "#year#-#NumberFormat(month, '00')#-#DaysInMonth('#year#-#NumberFormat(month, '00')#-01')# 23:59:59";
var result = {
query = model("Blog").findAll(
where = "blog_posts.published_at BETWEEN '#startdate#' AND '#enddate#' AND blog_posts.status='Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#'",
order = "publishedAt DESC",
include = "User",
returnAs = "query",
page = arguments.page,
perPage = arguments.perPage
),
hasMore = false,
totalCount = 0
};
result.totalCount = model("Blog").count(
where = "blog_posts.published_at BETWEEN '#startdate#' AND '#enddate#' AND blog_posts.status='Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#'"
);
result.hasMore = (page * perPage) < result.totalCount;
return result;
}
// Fetch Blogs by Category
public function getBlogsByCategory(
required string categoryName,
numeric page = 1,
numeric perPage = 6,
boolean isInfiniteScroll = false
) {
// Get category ID from name
var category = model("Category").findOne(where = "name = '#arguments.categoryName#'");
if (!IsObject(category)) return {query = QueryNew(""), hasMore = false, totalCount = 0};
var blogCategoryQuery = model("BlogCategory").findAll(where = "categoryId = #category.id#", returnAs = "query");
if (blogCategoryQuery.recordCount == 0) return {query = QueryNew(""), hasMore = false, totalCount = 0};
var blogIds = blogCategoryQuery.columnData("blogId");
var blogIdList = ArrayToList(blogIds);
var result = {
query = model("Blog").findAll(
where = "blog_posts.id IN (#blogIdList#) AND categoryId = #category.id# AND blog_posts.status ='Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#'",
order = "publishedAt DESC",
include = "User,BlogCategory",
returnAs = "query",
page = arguments.page,
perPage = arguments.perPage
),
hasMore = false,
totalCount = 0
};
result.totalCount = model("Blog").count(
where = "blog_posts.id IN (#blogIdList#) AND categoryId = #category.id# AND blog_posts.status ='Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#'",
include = "User,BlogCategory"
);
result.hasMore = (page * perPage) < result.totalCount;
return result;
}
// Fetch Blogs by Tag
private function getAllByTag(
required string tag,
numeric page = 1,
numeric perPage = 6,
boolean isInfiniteScroll = false
) {
// First, find the tag by name
var targetTag = model("Tag").findOne(where = "name = '#arguments.tag#'");
if (!IsObject(targetTag)) {
return {query = QueryNew(""), hasMore = false, totalCount = 0};
}
// Get all blog_ids associated with this tag
var blogTags = model("BlogTag").findAll(where = "tagId = #targetTag.id#", returnAs = "query");
if (blogTags.recordCount == 0) {
return {query = QueryNew(""), hasMore = false, totalCount = 0};
}
var blogIds = ValueList(blogTags.blogId);
var result = {
query = model("Blog").findAll(
where = "blog_posts.id IN (#blogIds#) AND blog_posts.status ='Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#'",
order = "publishedAt DESC",
include = "User",
returnAs = "query",
page = arguments.page,
perPage = arguments.perPage
),
hasMore = false,
totalCount = 0
};
result.totalCount = model("Blog").count(
where = "blog_posts.id IN (#blogIds#) AND blog_posts.status ='Approved' AND blog_posts.publishedAt IS NOT NULL AND blog_posts.publishedAt <= '#Now()#'"
);
result.hasMore = (page * perPage) < result.totalCount;
return result;
}
private function getBlogById(required numeric id) {
return model("Blog").findOne(where = "blog_posts.id = #arguments.id#", include = "User, PostStatus");
}
private function saveBlog(required struct blogData) {
var response = {"message" = "", "blogId" = 0};
// Generate slug