forked from CyberShadow/DFeed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.d
2405 lines (2111 loc) · 81 KB
/
web.d
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
/* Copyright (C) 2011, 2012, 2013 Vladimir Panteleev <vladimir@thecybershadow.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
module web;
import std.file;
import std.string;
import std.conv;
import std.exception;
import std.array, std.algorithm;
import std.datetime;
import std.regex;
import std.stdio;
alias std.string.indexOf indexOf;
import ae.net.asockets;
import ae.net.http.caching;
import ae.net.http.responseex;
import ae.net.http.server;
import ae.net.ietf.headers;
import ae.sys.log;
import ae.sys.shutdown;
import ae.utils.array;
import ae.utils.feed;
import ae.utils.json;
import ae.utils.text;
import ae.utils.textout;
import ae.utils.time;
import captcha;
import common;
import database;
import cache;
import rfc850;
import user;
import posting;
version = MeasurePerformance;
class WebUI
{
Logger log;
version(MeasurePerformance) Logger perfLog;
HttpServer server;
string vhost;
User user;
string ip;
StringBuffer html;
string[string] banned;
this()
{
log = createLogger("Web");
version(MeasurePerformance) perfLog = createLogger("Performance");
loadBanList();
auto lines = readText("data/web.txt").splitLines();
auto port = to!ushort(lines[0]);
vhost = lines[1];
auto iface = lines.length > 2 ? lines[2] : null;
server = new HttpServer();
server.log = log;
server.handleRequest = &onRequest;
server.listen(port, iface);
addShutdownHandler({ server.close(); });
}
// ***********************************************************************
string staticPath(string path)
{
return "/static/" ~ text(timeLastModified("web/static" ~ path).stdTime) ~ path;
}
string optimizedPath(string base, string path)
{
auto origPath = base ~ path;
auto optiPath = base ~ path ~ "-opt";
if (exists(origPath) && exists(optiPath) && timeLastModified(optiPath) >= timeLastModified(origPath))
return path ~ "-opt";
else
return path;
}
HttpResponseEx serveFile(HttpResponseEx response, string path)
{
response.cacheForever();
return response.serveFile(optimizedPath("web/static/", path), "web/static/");
}
Cached!(string[string]) staticFilesCache;
string[string] getStaticFiles()
{
string[string] result;
foreach (string fn; dirEntries("web/static", SpanMode.depth))
if (isFile(fn))
{
auto path = fn["web/static".length..$].replace(`\`, `/`);
result[path] = staticPath(path);
}
return result;
}
// ***********************************************************************
enum JQUERY_URL = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
void onRequest(HttpRequest request, HttpServerConnection conn)
{
conn.sendResponse(handleRequest(request, conn));
}
HttpResponse handleRequest(HttpRequest request, HttpServerConnection conn)
{
StopWatch responseTime;
responseTime.start();
auto response = new HttpResponseEx();
ip = request.remoteHosts(conn.remoteAddress.toAddrString())[0];
user = getUser("Cookie" in request.headers ? request.headers["Cookie"] : null);
string[] cookies;
scope(success)
{
if (!cookies)
cookies = user.save();
foreach (cookie; cookies)
response.headers.add("Set-Cookie", cookie);
}
string title, breadcrumb1, breadcrumb2;
string bodyClass = "narrowdoc";
string returnPage = request.resource;
html.clear();
string[] tools, extraHeaders;
auto status = HttpStatusCode.OK;
// Redirect to canonical domain name
auto host = request.headers.get("Host", "");
host = request.headers.get("X-Forwarded-Host", host);
if (host != vhost && host != "localhost" && ip != "127.0.0.1")
return response.redirect("http://" ~ vhost ~ request.resource, HttpStatusCode.MovedPermanently);
auto splitViewHeaders = [
`<script src="` ~ JQUERY_URL ~ `"></script>`,
`<script src="` ~ staticPath("/js/dfeed-split.js") ~ `"></script>`,
];
auto canonicalHeader =
`<link rel="canonical" href="http://`~vhost~request.resource~`"/>`;
try
{
if (banCheck(ip, request))
return response.writeError(HttpStatusCode.Forbidden, "You're banned!");
auto pathStr = request.resource;
enforce(pathStr.startsWith('/'), "Invalid path");
string[string] parameters;
if (pathStr.indexOf('?') >= 0)
{
auto p = pathStr.indexOf('?');
parameters = decodeUrlParameters(pathStr[p+1..$]);
pathStr = pathStr[0..p];
}
auto path = pathStr[1..$].split("/");
if (!path.length) path = [""];
auto pathX = path[1..$].join("%2F"); // work around Apache bug
switch (path[0])
{
// Obsolete "/discussion/" prefix
case "discussion":
case "":
// Handle redirects from pnews
// Abort on redirect from URLs with unsupported features.
// Only search engines would be likely to hit these.
if ("path" in parameters || "mid" in parameters)
throw new NotFoundException("Legacy redirect - unsupported feature");
// Redirect to our URL scheme
string redirectGroup, redirectNum;
if ("group" in parameters)
redirectGroup = parameters["group"];
if ("art_group" in parameters)
redirectGroup = parameters["art_group"];
if ("artnum" in parameters)
redirectNum = parameters["artnum"];
if ("article_id" in parameters)
redirectNum = parameters["article_id"];
if (redirectGroup && redirectNum)
{
foreach (string id; query("SELECT `ID` FROM `Groups` WHERE `Group`=? AND `ArtNum`=?").iterate(redirectGroup, redirectNum))
return response.redirect(idToUrl(id), HttpStatusCode.MovedPermanently);
throw new NotFoundException("Legacy redirect - article not found");
}
else
if (redirectGroup)
return response.redirect("/group/" ~ redirectGroup, HttpStatusCode.MovedPermanently);
title = "Index";
breadcrumb1 = `<a href="/">Forum Index</a>`;
foreach (what; ["posts", "threads"])
extraHeaders ~= `<link rel="alternate" type="application/atom+xml" title="New `~what~`" href="/feed/`~what~`" />`;
discussionIndex();
break;
case "group":
{
enforce(path.length > 1, "No group specified");
string group = path[1];
int page = to!int(parameters.get("page", "1"));
string pageStr = page==1 ? "" : format(" (page %d)", page);
title = group ~ " index" ~ pageStr;
breadcrumb1 = `<a href="/group/`~encodeEntities(group)~`">` ~ encodeEntities(group) ~ `</a>` ~ pageStr;
auto viewMode = user.get("groupviewmode", "basic");
if (viewMode == "basic")
discussionGroup(group, page);
else
if (viewMode == "threaded")
discussionGroupThreaded(group, page);
else
{
discussionGroupSplit(group, page);
extraHeaders ~= splitViewHeaders;
}
//tools ~= viewModeTool(["basic", "threaded"], "group");
tools ~= viewModeTool(["basic", "threaded", "horizontal-split"], "group");
foreach (what; ["posts", "threads"])
extraHeaders ~= `<link rel="alternate" type="application/atom+xml" title="New `~what~` on `~encodeEntities(group)~`" href="/feed/`~what~`/`~encodeEntities(group)~`" />`;
break;
}
case "thread":
{
enforce(path.length > 1, "No thread specified");
int page = to!int(parameters.get("page", "1"));
string threadID = '<' ~ urlDecode(pathX) ~ '>';
auto firstPostUrl = idToUrl(getPostAtThreadIndex(threadID, getPageOffset(page, POSTS_PER_PAGE)));
auto viewMode = user.get("groupviewmode", "basic");
if (viewMode != "basic")
html.put(`<div class="forum-notice">Viewing thread in basic view mode – click a post's title to open it in `, encodeEntities(viewMode), ` view mode</div>`);
returnPage = firstPostUrl;
string pageStr = page==1 ? "" : format(" (page %d)", page);
string group, subject;
discussionThread(threadID, page, group, subject);
title = subject ~ pageStr;
breadcrumb1 = `<a href="/group/` ~encodeEntities(group)~`">` ~ encodeEntities(group ) ~ `</a>`;
breadcrumb2 = `<a href="/thread/`~encodeEntities(pathX)~`">` ~ encodeEntities(subject) ~ `</a>` ~ pageStr;
//tools ~= viewModeTool(["flat", "nested"], "thread");
tools ~= viewModeTool(["basic", "threaded", "horizontal-split"], "group");
extraHeaders ~= canonicalHeader; // Google confuses /post/ URLs with threads
break;
}
case "post":
enforce(path.length > 1, "No post specified");
if (user.get("groupviewmode", "basic") == "basic")
return response.redirect(resolvePostUrl('<' ~ urlDecode(pathX) ~ '>'));
else
if (user.get("groupviewmode", "basic") == "threaded")
{
string group, subject;
discussionSinglePost('<' ~ urlDecode(pathX) ~ '>', group, subject);
title = subject;
breadcrumb1 = `<a href="/group/` ~encodeEntities(group)~`">` ~ encodeEntities(group ) ~ `</a>`;
breadcrumb2 = `<a href="/thread/`~encodeEntities(pathX)~`">` ~ encodeEntities(subject) ~ `</a> (view single post)`;
tools ~= viewModeTool(["basic", "threaded", "horizontal-split"], "group");
break;
}
else
{
string group;
int page;
discussionGroupSplitFromPost('<' ~ urlDecode(pathX) ~ '>', group, page);
string pageStr = page==1 ? "" : format(" (page %d)", page);
title = group ~ " index" ~ pageStr;
breadcrumb1 = `<a href="/group/`~encodeEntities(group)~`">` ~ encodeEntities(group) ~ `</a>` ~ pageStr;
extraHeaders ~= splitViewHeaders;
tools ~= viewModeTool(["basic", "threaded", "horizontal-split"], "group");
break;
}
case "raw":
{
enforce(path.length > 1, "Invalid URL");
auto post = getPost('<' ~ urlDecode(path[1]) ~ '>', array(map!(to!uint)(path[2..$])));
enforce(post, "Post not found");
if (!post.data && post.error)
throw new Exception(post.error);
if (post.fileName)
//response.headers["Content-Disposition"] = `inline; filename="` ~ post.fileName ~ `"`;
response.headers["Content-Disposition"] = `attachment; filename="` ~ post.fileName ~ `"`; // "
else
// TODO: separate subdomain for attachments
response.headers["Content-Disposition"] = `attachment; filename="raw"`;
return response.serveData(Data(post.data), post.mimeType ? post.mimeType : "application/octet-stream");
}
case "source":
{
enforce(path.length > 1, "Invalid URL");
auto post = getPost('<' ~ urlDecode(path[1]) ~ '>', array(map!(to!uint)(path[2..$])));
enforce(post, "Post not found");
return response.serveData(Data(post.message), "text/plain");
}
case "split-post":
enforce(path.length > 1, "No post specified");
discussionSplitPost('<' ~ urlDecode(pathX) ~ '>');
return response.serveData(cast(string)html.get());
case "set":
{
if (parameters.get("secret", "") != getUserSecret())
throw new Exception("XSRF secret verification failed. Are your cookies enabled?");
foreach (name, value; parameters)
if (name != "url" && name != "secret")
user[name] = value; // TODO: is this a good idea?
if ("url" in parameters)
return response.redirect(parameters["url"]);
else
return response.serveText("OK");
}
case "mark-unread":
{
enforce(path.length > 1, "No post specified");
auto post = getPostInfo('<' ~ urlDecode(pathX) ~ '>');
enforce(post, "Post not found");
user.setRead(post.rowid, false);
return response.serveText("OK");
}
case "first-unread":
{
enforce(path.length > 1, "No thread specified");
return response.redirect(discussionFirstUnread('<' ~ urlDecode(pathX) ~ '>'));
}
case "newpost":
{
enforce(path.length > 1, "No group specified");
string group = path[1];
title = "Posting to " ~ group;
breadcrumb1 = `<a href="/group/`~encodeEntities(group)~`">` ~ encodeEntities(group) ~ `</a>`;
breadcrumb2 = `<a href="/newpost/`~encodeEntities(group)~`">New thread</a>`;
if (discussionPostForm(Rfc850Post.newPostTemplate(group)))
bodyClass ~= " formdoc";
break;
}
case "reply":
{
enforce(path.length > 1, "No post specified");
auto post = getPost('<' ~ urlDecode(pathX) ~ '>');
enforce(post, "Post not found");
title = `Replying to "` ~ post.subject ~ `"`; // "
breadcrumb1 = `<a href="` ~ encodeEntities(idToUrl(post.id)) ~ `">` ~ encodeEntities(post.subject) ~ `</a>`;
breadcrumb2 = `<a href="/reply/`~pathX~`">Post reply</a>`;
if (discussionPostForm(post.replyTemplate()))
bodyClass ~= " formdoc";
break;
}
case "send":
{
auto postVars = request.decodePostData();
auto process = discussionSend(postVars, cast(string[string])request.headers);
if (process)
return response.redirect("/poststatus/" ~ process.pid);
title = breadcrumb1 = `Posting error`;
bodyClass ~= " formdoc";
break;
}
case "poststatus":
{
enforce(path.length > 1, "No PID specified");
auto pid = pathX;
enforce(pid in postProcesses, "Sorry, this is not a post I know of.");
bool refresh, form;
string redirectTo;
discussionPostStatus(postProcesses[pid], refresh, redirectTo, form);
if (refresh)
response.setRefresh(1, redirectTo);
if (form)
{
title = breadcrumb1 = `Posting error`;
bodyClass ~= " formdoc";
}
else
title = breadcrumb1 = `Posting status`;
break;
}
case "delete":
{
enforce(user.getLevel() >= User.Level.canDeletePosts, "You can't delete posts");
enforce(path.length > 1, "No post specified");
auto post = getPost('<' ~ urlDecode(pathX) ~ '>');
enforce(post, "Post not found");
title = `Delete "` ~ post.subject ~ `"?`; // "
breadcrumb1 = `<a href="` ~ encodeEntities(idToUrl(post.id)) ~ `">` ~ encodeEntities(post.subject) ~ `</a>`;
breadcrumb2 = `<a href="/delete/`~pathX~`">Delete post</a>`;
discussionDeleteForm(post);
bodyClass ~= " formdoc";
break;
}
case "dodelete":
{
enforce(user.getLevel() >= User.Level.canDeletePosts, "You can't delete posts");
auto postVars = request.decodePostData();
title = "Deleting post";
deletePost(postVars);
break;
}
case "loginform":
{
discussionLoginForm(parameters);
title = breadcrumb1 = `Log in`;
tools ~= `<a href="/registerform?url=__URL__">Register</a>`;
returnPage = "/";
break;
}
case "registerform":
{
discussionRegisterForm(parameters);
title = breadcrumb1 = `Registration`;
tools ~= `<a href="/registerform?url=__URL__">Register</a>`;
returnPage = "/";
break;
}
case "login":
{
try
{
parameters = request.decodePostData();
discussionLogin(parameters);
if ("url" in parameters)
return response.redirect(parameters["url"]);
else
return response.serveText("OK");
}
catch (Exception e)
{
discussionLoginForm(parameters, e.msg);
title = breadcrumb1 = `Login error`;
tools ~= `<a href="/registerform?url=__URL__">Register</a>`;
returnPage = "/";
break;
}
}
case "register":
{
try
{
parameters = request.decodePostData();
discussionRegister(parameters);
if ("url" in parameters)
return response.redirect(parameters["url"]);
else
return response.serveText("OK");
}
catch (Exception e)
{
discussionRegisterForm(parameters, e.msg);
title = breadcrumb1 = `Registration error`;
tools ~= `<a href="/registerform?url=__URL__">Register</a>`;
returnPage = "/";
break;
}
}
case "logout":
{
enforce(user.isLoggedIn(), "Not logged in");
user.logOut();
if ("url" in parameters)
return response.redirect(parameters["url"]);
else
return response.serveText("OK");
}
case "help":
title = breadcrumb1 = "Help";
html.put(readText(optimizedPath(null, "web/help.htt")));
break;
case "feed":
{
/*
enforce(path.length > 1, "Feed type not specified");
enforce(path[1]=="posts" || path[1]=="threads", "Unknown feed type");
bool threadsOnly = path[1] == "threads";
string group;
if (path.length > 2)
group = path[2];
auto hours = to!int(parameters.get("hours", text(FEED_HOURS_DEFAULT)));
enforce(hours <= FEED_HOURS_MAX, "hours parameter exceeds limit");
return getFeed(group, threadsOnly, hours).getResponse(request);
*/
// Feed generation performance is currently abyssimal with a cold cache (up to several minutes).
// Need another strategy for SQL queries.
throw new Exception("Sorry, feeds have been temporarily disabled.");
}
case "js":
case "css":
case "images":
case "favicon.ico":
case "robots.txt":
return serveFile(response, pathStr[1..$]);
case "static":
enforce(path.length > 2);
return serveFile(response, path[2..$].join("/"));
default:
return response.writeError(HttpStatusCode.NotFound);
}
}
catch (Exception e)
{
//return response.writeError(HttpStatusCode.InternalServerError, "Unprocessed exception: " ~ e.msg);
if (cast(NotFoundException) e)
{
breadcrumb1 = title = "Not Found";
status = HttpStatusCode.NotFound;
}
else
{
breadcrumb1 = title = "Error";
status = HttpStatusCode.InternalServerError;
}
auto text = encodeEntities(e.msg).replace("\n", "<br>");
debug text ~= `<pre>` ~ encodeEntities(e.toString()) ~ `</pre>`;
html.clear();
html.put(
`<table class="forum-table forum-error">`
`<tr><th>`, encodeEntities(title), `</th></tr>`
`<tr><td class="forum-table-message">`, text, `</td></tr>`
`</table>`);
}
assert(title, "No title");
assert(html.length, "No HTML");
if (breadcrumb1) breadcrumb1 = "› " ~ breadcrumb1;
if (breadcrumb2) breadcrumb2 = "» " ~ breadcrumb2;
if (user.isLoggedIn())
tools ~= `<a href="/logout?url=__URL__">Log out ` ~ encodeEntities(user.getName()) ~ `</a>`;
else
tools ~= `<a href="/loginform?url=__URL__">Log in</a>`;
tools ~= `<a href="/help">Help</a>`;
string toolStr = tools.join(" · ");
toolStr =
toolStr.replace("__URL__", encodeUrlParameter(returnPage)) ~
`<script type="text/javascript">var toolsTemplate = ` ~ toJson(toolStr) ~ `;</script>`;
string htmlStr = cast(string) html.get(); // html contents will be overwritten on next request
cookies = user.save();
foreach (cookie; cookies)
if (cookie.length > 4096 * 15/16)
{
htmlStr =
`<div class="forum-notice">Warning: cookie size approaching RFC 2109 limit.`
`Please consider <a href="/registerform">creating an account</a> to avoid losing your read post history.</div>` ~ htmlStr;
break;
}
string[string] vars = [
"title" : encodeEntities(title),
"content" : htmlStr,
"breadcrumb1" : breadcrumb1,
"breadcrumb2" : breadcrumb2,
"extraheaders" : extraHeaders.join("\n"),
"bodyclass" : bodyClass,
"tools" : toolStr,
];
debug
auto staticFiles = getStaticFiles();
else
auto staticFiles = staticFilesCache(getStaticFiles());
foreach (path, res; staticFiles)
vars["static:" ~ path] = res;
response.disableCache();
response.serveData(HttpResponseEx.loadTemplate(optimizedPath(null, "web/skel.htt"), vars));
response.setStatus(status);
return response;
}
// ***********************************************************************
// TODO: Move out to configuration files
struct GroupInfo { string name, description, postMessage, alsoVia; }
struct GroupSet { string name; GroupInfo[] groups; }
static GroupInfo makeGroupInfo(string name, string archiveName, string mlName, string description, bool mlOnly, bool bugzilla)
{
auto info = GroupInfo(name, description);
string[] alsoVia;
if (!mlOnly)
alsoVia ~= `<a href="news://news.digitalmars.com/`~name~`">NNTP</a>`;
if (mlName)
alsoVia ~= `<a href="http://lists.puremagic.com/cgi-bin/mailman/listinfo/`~mlName~`">mailing list</a>`;
if (mlOnly)
info.postMessage =
`You are viewing a mailing list archive.<br>`
`For information about posting, visit `
`<a href="http://lists.puremagic.com/cgi-bin/mailman/listinfo/`~name~`">`~name~`'s Mailman page</a>.`;
if (bugzilla)
{
alsoVia ~= `<a href="http://d.puremagic.com/issues/">Bugzilla</a>`;
info.postMessage =
`You are viewing a Bugzilla message archive.<br>`
`To report a bug, please visit the <a href="http://d.puremagic.com/issues/">D Bugzilla</a> or `
`<a href="/newpost/digitalmars.D">post to digitalmars.D</a>.`;
}
if (mlOnly)
alsoVia ~= `<a href="http://lists.puremagic.com/pipermail/`~name.toLower()~`/">archive</a>`;
else
if (archiveName)
alsoVia ~= `<a href="http://www.digitalmars.com/d/archives/`~archiveName~`/">archive</a>`;
info.alsoVia = alsoVia.join("<br>");
return info;
}
static GroupSet[] groupHierarchy = [
{ "D Programming Language - General", [
makeGroupInfo("digitalmars.D" , "digitalmars/D" , "digitalmars-d" , "General discussion of the D programming language." , false, false),
makeGroupInfo("digitalmars.D.announce" , "digitalmars/D/announce" , "digitalmars-d-announce" , "Announcements for anything D related" , false, false),
makeGroupInfo("digitalmars.D.learn" , "digitalmars/D/learn" , "digitalmars-d-learn" , "Questions about learning D" , false, false),
]},
{ "D Programming Language - Ecosystem", [
makeGroupInfo("D.gnu" , "D/gnu" , "d.gnu" , "GDC, the Gnu D Compiler " , false, false),
makeGroupInfo("digitalmars.D.ldc" , null , "digitalmars-d-ldc" , "LDC, the LLVM-based D Compiler " , false, false),
makeGroupInfo("digitalmars.D.debugger" , "digitalmars/D/debugger" , "digitalmars-d-debugger" , "Debuggers for D" , false, false),
makeGroupInfo("digitalmars.D.ide" , "digitalmars/D/ide" , "digitalmars-d-ide" , "Integrated Development Environments for D" , false, false),
]},
{ "D Programming Language - Development", [
makeGroupInfo("digitalmars.D.bugs" , "digitalmars/D/bugs" , "digitalmars-d-bugs" , "Bug reports for D compiler and library" , false, true ),
makeGroupInfo("dmd-beta" , null , "dmd-beta" , "Notify of and discuss beta versions" , true , false),
makeGroupInfo("dmd-concurrency" , null , "dmd-concurrency" , "Design of concurrency features in D and library" , true , false),
makeGroupInfo("dmd-internals" , null , "dmd-internals" , "dmd compiler internal design and implementation" , true , false),
makeGroupInfo("phobos" , null , "phobos" , "Phobos standard library design and implementation" , true , false),
makeGroupInfo("D-runtime" , null , "D-runtime" , "Runtime library design and implementation" , true , false),
]},
{ "Other", [
makeGroupInfo("digitalmars.D.dwt" , "digitalmars/D/dwt" , "digitalmars-d-dwt" , "Developing the D Widget Toolkit" , false, false),
makeGroupInfo("digitalmars.D.dtl" , "digitalmars/D/dtl" , "digitalmars-d-dtl" , "Developing the D Template Library" , false, false),
makeGroupInfo("DMDScript" , "DMDScript" , null , "General discussion of DMDScript" , false, false),
makeGroupInfo("digitalmars.empire" , "digitalmars/empire" , null , "General discussion of Empire, the Wargame of the Century" , false, false),
makeGroupInfo("D" , "" , null , "Retired, use digitalmars.D instead" , false, false),
]},
{ "C and C++", [
makeGroupInfo("c++" , "c++" , null , "General discussion of DMC++ compiler" , false, false),
makeGroupInfo("c++.announce" , "c++/announce" , null , "Announcements about C++" , false, false),
makeGroupInfo("c++.atl" , "c++/atl" , null , "Microsoft's Advanced Template Library" , false, false),
makeGroupInfo("c++.beta" , "c++/beta" , null , "Test versions of various C++ products" , false, false),
makeGroupInfo("c++.chat" , "c++/chat" , null , "Off topic discussions" , false, false),
makeGroupInfo("c++.command-line" , "c++/command-line" , null , "Command line tools" , false, false),
makeGroupInfo("c++.dos" , "c++/dos" , null , "DMC++ and DOS" , false, false),
makeGroupInfo("c++.dos.16-bits" , "c++/dos/16-bits" , null , "16 bit DOS topics" , false, false),
makeGroupInfo("c++.dos.32-bits" , "c++/dos/32-bits" , null , "32 bit extended DOS topics" , false, false),
makeGroupInfo("c++.idde" , "c++/idde" , null , "The Digital Mars Integrated Development and Debugging Environment", false, false),
makeGroupInfo("c++.mfc" , "c++/mfc" , null , "Microsoft Foundation Classes" , false, false),
makeGroupInfo("c++.rtl" , "c++/rtl" , null , "C++ Runtime Library" , false, false),
makeGroupInfo("c++.stl" , "c++/stl" , null , "Standard Template Library" , false, false),
makeGroupInfo("c++.stl.hp" , "c++/stl/hp" , null , "HP's Standard Template Library" , false, false),
makeGroupInfo("c++.stl.port" , "c++/stl/port" , null , "STLPort Standard Template Library" , false, false),
makeGroupInfo("c++.stl.sgi" , "c++/stl/sgi" , null , "SGI's Standard Template Library" , false, false),
makeGroupInfo("c++.stlsoft" , "c++/stlsoft" , null , "Stlsoft products" , false, false),
makeGroupInfo("c++.windows" , "c++/windows" , null , "Writing C++ code for Microsoft Windows" , false, false),
makeGroupInfo("c++.windows.16-bits" , "c++/windows/16-bits" , null , "16 bit Windows topics" , false, false),
makeGroupInfo("c++.windows.32-bits" , "c++/windows/32-bits" , null , "32 bit Windows topics" , false, false),
makeGroupInfo("c++.wxwindows" , "c++/wxwindows" , null , "wxWindows" , false, false),
]},
];
const(GroupInfo)* getGroupInfo(string name)
{
foreach (set; groupHierarchy)
foreach (ref group; set.groups)
if (group.name == name)
return &group;
return null;
}
// ***********************************************************************
enum MeasurePerformanceMixin =
q{
StopWatch performanceSW;
performanceSW.start();
scope(success)
{
performanceSW.stop();
perfLog(PERF_SCOPE ~ ": " ~ text(performanceSW.peek().msecs) ~ "ms");
}
};
int[string] getThreadCounts()
{
enum PERF_SCOPE = "getThreadCounts"; mixin(MeasurePerformanceMixin);
int[string] threadCounts;
foreach (string group, int count; query("SELECT `Group`, COUNT(*) FROM `Threads` GROUP BY `Group`").iterate())
threadCounts[group] = count;
return threadCounts;
}
int[string] getPostCounts()
{
enum PERF_SCOPE = "getPostCounts"; mixin(MeasurePerformanceMixin);
int[string] postCounts;
foreach (string group, int count; query("SELECT `Group`, COUNT(*) FROM `Groups` GROUP BY `Group`").iterate())
postCounts[group] = count;
return postCounts;
}
string[string] getLastPosts()
{
enum PERF_SCOPE = "getLastPosts"; mixin(MeasurePerformanceMixin);
string[string] lastPosts;
foreach (set; groupHierarchy)
foreach (group; set.groups)
foreach (string id; query("SELECT `ID` FROM `Groups` WHERE `Group`=? ORDER BY `Time` DESC LIMIT 1").iterate(group.name))
lastPosts[group.name] = id;
return lastPosts;
}
Cached!(int[string]) threadCountCache, postCountCache;
Cached!(string[string]) lastPostCache;
void discussionIndex()
{
auto threadCounts = threadCountCache(getThreadCounts());
auto postCounts = postCountCache(getPostCounts());
auto lastPosts = lastPostCache(getLastPosts());
string summarizePost(string postID)
{
auto info = getPostInfo(postID);
if (info)
with (*info)
return
`<a class="forum-postsummary-subject ` ~ (user.isRead(rowid) ? "forum-read" : "forum-unread") ~ `" href="` ~ encodeEntities(idToUrl(id)) ~ `">` ~ truncateString(subject) ~ `</a><br>` ~
`by <span class="forum-postsummary-author">` ~ truncateString(author) ~ `</span><br>` ~
`<span class="forum-postsummary-time">` ~ summarizeTime(time) ~ `</span>`;
return `<div class="forum-no-data">-</div>`;
}
html.put(`<table id="forum-index" class="forum-table">`);
foreach (set; groupHierarchy)
{
html.put(
`<tr><th colspan="5">`, encodeEntities(set.name), `</th></tr>`
`<tr class="subheader"><th>Forum</th><th>Last Post</th><th>Threads</th><th>Posts</th><th>Also via</th></tr>`);
foreach (group; set.groups)
{
html.put(
`<tr>`
`<td class="forum-index-col-forum"><a href="/group/`, encodeEntities(group.name), `">`, encodeEntities(group.name), `</a>`
`<div class="forum-index-description">`, encodeEntities(group.description), `</div>`
`</td>`
`<td class="forum-index-col-lastpost">`, group.name in lastPosts ? summarizePost( lastPosts[group.name]) : `<div class="forum-no-data">-</div>`, `</td>`
`<td class="number-column">`, group.name in threadCounts ? formatNumber (threadCounts[group.name]) : `-`, `</td>`
`<td class="number-column">`, group.name in postCounts ? formatNumber ( postCounts[group.name]) : `-`, `</td>`
`<td class="number-column">`, group.alsoVia, `</td>`
`</tr>`,
);
}
}
html.put(`</table>`);
}
// ***********************************************************************
int[] getThreadPostIndexes(string id)
{
int[] result;
foreach (int rowid; query("SELECT `ROWID` FROM `Posts` WHERE `ThreadID` = ?").iterate(id))
result ~= rowid;
return result;
}
CachedSet!(string, int[]) threadPostIndexCache;
void newPostButton(string group)
{
html.put(
`<form name="new-post-form" method="get" action="/newpost/`, encodeEntities(group), `">`
`<div class="header-tools">`
`<input type="submit" value="Create thread">`
`</div>`
`</form>`);
}
void pager(string base, int page, int pageCount, int radius = 4)
{
string linkOrNot(string text, int page, bool cond)
{
if (cond)
return `<a href="` ~ encodeEntities(base) ~ `?page=` ~ .text(page) ~ `">` ~ text ~ `</a>`;
else
return `<span class="disabled-link">` ~ text ~ `</span>`;
}
int pagerStart = max(1, page - radius);
int pagerEnd = min(pageCount, page + radius);
string[] pager;
if (pagerStart > 1)
pager ~= "…";
foreach (pagerPage; pagerStart..pagerEnd+1)
if (pagerPage == page)
pager ~= `<b>` ~ text(pagerPage) ~ `</b>`;
else
pager ~= linkOrNot(text(pagerPage), pagerPage, true);
if (pagerEnd < pageCount)
pager ~= "…";
html.put(
`<tr class="pager"><th colspan="3">`
`<div class="pager-left">`,
linkOrNot("« First", 1, page!=1),
` `,
linkOrNot("‹ Prev", page-1, page>1),
`</div>`
`<div class="pager-right">`,
linkOrNot("Next ›", page+1, page<pageCount),
` `,
linkOrNot("Last » ", pageCount, page!=pageCount),
`</div>`
`<div class="pager-numbers">`, pager.join(` `), `</div>`
`</th></tr>`);
}
enum THREADS_PER_PAGE = 15;
enum POSTS_PER_PAGE = 10;
static int indexToPage(int index, int perPage) { return index / perPage + 1; } // Return value is 1-based, index is 0-based
static int getPageCount(int count, int perPage) { return indexToPage(count-1, perPage); }
static int getPageOffset(int page, int perPage) { return (page-1) * perPage; }
void threadPager(string group, int page, int radius = 4)
{
auto threadCounts = threadCountCache(getThreadCounts());
enforce(group in threadCounts, "Empty or unknown group");
auto threadCount = threadCounts[group];
auto pageCount = getPageCount(threadCount, THREADS_PER_PAGE);
pager(`/group/` ~ group, page, pageCount, radius);
}
void discussionGroup(string group, int page)
{
enforce(page >= 1, "Invalid page");
struct Thread
{
string id;
PostInfo* _firstPost, _lastPost;
int postCount, unreadPostCount;
/// Handle orphan posts
@property PostInfo* firstPost() { return _firstPost ? _firstPost : _lastPost; }
@property PostInfo* lastPost() { return _lastPost; }
@property bool isRead() { return unreadPostCount==0; }
}
Thread[] threads;
int getUnreadPostCount(string id)
{
auto posts = threadPostIndexCache(id, getThreadPostIndexes(id));
int count = 0;
foreach (post; posts)
if (!user.isRead(post))
count++;
return count;
}
foreach (string firstPostID, string lastPostID; query("SELECT `ID`, `LastPost` FROM `Threads` WHERE `Group` = ? ORDER BY `LastUpdated` DESC LIMIT ? OFFSET ?").iterate(group, THREADS_PER_PAGE, getPageOffset(page, THREADS_PER_PAGE)))
foreach (int count; query("SELECT COUNT(*) FROM `Posts` WHERE `ThreadID` = ?").iterate(firstPostID))
threads ~= Thread(firstPostID, getPostInfo(firstPostID), getPostInfo(lastPostID), count, getUnreadPostCount(firstPostID));
void summarizeThread(string tid, PostInfo* info, bool isRead)
{
if (info)
with (*info)
return html.put(
// `<!-- Thread ID: ` ~ encodeEntities(threadID) ~ ` | First Post ID: ` ~ encodeEntities(id) ~ `-->` ~
`<a class="forum-postsummary-subject `, (isRead ? "forum-read" : "forum-unread"), `" href="`, encodeEntities(idToUrl(tid, "thread")), `">`, truncateString(subject, 100), `</a><br>`
`by <span class="forum-postsummary-author">`, truncateString(author, 100), `</span><br>`);
html.put(`<div class="forum-no-data">-</div>`);
}
void summarizeLastPost(PostInfo* info)
{
// TODO: link?
if (info)
with (*info)
return html.put(
`<span class="forum-postsummary-time">`, summarizeTime(time), `</span>`
`by <span class="forum-postsummary-author">`, truncateString(author, 25), `</span><br>`);
html.put(`<div class="forum-no-data">-</div>`);
}
void summarizePostCount(ref Thread thread)
{
if (thread.unreadPostCount == 0)
html ~= formatNumber(thread.postCount-1);
else
if (thread.unreadPostCount == thread.postCount)
html.put(`<b>`, formatNumber(thread.postCount-1), `</b>`);
else
html.put(
`<b>`, formatNumber(thread.postCount-1), `</b>`
`<br>(<a href="`, idToUrl(thread.id, "first-unread"), `">`, formatNumber(thread.unreadPostCount), ` new</a>)`);
}
html.put(
`<table id="group-index" class="forum-table">`
`<tr class="group-index-header"><th colspan="3"><div class="header-with-tools">`), newPostButton(group), html.put(encodeEntities(group), `</div></th></tr>`
`<tr class="subheader"><th>Thread / Thread Starter</th><th>Last Post</th><th>Replies</th>`);
foreach (thread; threads)
html.put(
`<tr>`
`<td class="group-index-col-first">`), summarizeThread(thread.id, thread.firstPost, thread.isRead), html.put(`</td>`
`<td class="group-index-col-last">`), summarizeLastPost(thread.lastPost), html.put(`</td>`
`<td class="number-column">`), summarizePostCount(thread), html.put(`</td>`
`</tr>`);
threadPager(group, page);
html.put(
`</table>`
);
}
// ***********************************************************************
string[][string] referenceCache; // invariant
void formatThreadedPosts(PostInfo*[] postInfos, string selectedID = null)
{
enum OFFSET_INIT = 1f;
enum OFFSET_MAX = 2f;
enum OFFSET_WIDTH = 37.5f;
enum OFFSET_UNITS = "%";
class Post
{
PostInfo* info;
SysTime maxTime;
Post[] children;
int maxDepth;
bool ghost; // dummy parent for orphans
string ghostSubject;
@property string subject() { return ghostSubject ? ghostSubject : info.subject; }
this(PostInfo* info = null) { this.info = info; }
void calcStats()
{
foreach (child; children)
child.calcStats();
if (info)
maxTime = info.time;
foreach (child; children)
if (maxTime < child.maxTime)
maxTime = child.maxTime;
//maxTime = reduce!max(time, map!"a.maxTime"(children));
maxDepth = 1;
foreach (child; children)
if (maxDepth < 1 + child.maxDepth)
maxDepth = 1 + child.maxDepth;