Removed unnecessary event listener
[lw2-viewer.git] / lw2.lisp
blobf47fc60fdae17e647eaa9869b155d2503de3537d
1 (uiop:define-package #:lw2-viewer
2 (:use #:cl #:sb-thread #:flexi-streams #:djula
3 #:lw2-viewer.config #:lw2.utils #:lw2.lmdb #:lw2.backend #:lw2.links #:lw2.clean-html #:lw2.login #:lw2.context #:lw2.sites #:lw2.components #:lw2.html-reader)
4 (:import-from #:alexandria #:ensure-list)
5 (:unintern
6 #:define-regex-handler #:*fonts-stylesheet-uri* #:generate-fonts-link
7 #:user-nav-bar #:*primary-nav* #:*secondary-nav* #:*nav-bars*
8 #:begin-html #:end-html))
10 (in-package #:lw2-viewer)
12 (named-readtables:in-readtable html-reader)
14 (add-template-directory (asdf:system-relative-pathname "lw2-viewer" "templates/"))
16 (define-cache-database "auth-token-to-userid" "auth-token-to-username" "comment-markdown-source" "post-markdown-source")
18 (defvar *current-auth-token*)
19 (defvar *current-userid*)
20 (defvar *current-username*)
21 (defvar *current-user-slug*)
23 (defvar *read-only-mode* nil)
24 (defvar *read-only-default-message* "Due to a system outage, you cannot log in or post at this time.")
26 (defparameter *default-prefs* (alist :items-per-page 20 :default-sort "new"))
27 (defvar *current-prefs* nil)
29 (defun logged-in-userid (&optional is-userid)
30 (let ((current-userid *current-userid*))
31 (if is-userid
32 (string= current-userid is-userid)
33 current-userid)))
35 (defun logged-in-username ()
36 *current-username*)
38 (defun logged-in-user-slug ()
39 *current-user-slug*)
41 (defun pretty-time (timestring &key format)
42 (let ((time (local-time:parse-timestring timestring)))
43 (values (local-time:format-timestring nil time :timezone local-time:+utc-zone+ :format (or format '(:day #\ :short-month #\ :year #\ :hour #\: (:min 2) #\ :timezone)))
44 (* (local-time:timestamp-to-unix time) 1000))))
46 (defun pretty-number (number &optional object)
47 (let ((str (coerce (format nil "~:D~@[<span> ~A~P</span>~]" number object number) '(vector character))))
48 (if (eq (aref str 0) #\-)
49 (setf (aref str 0) #\MINUS_SIGN))
50 str))
52 (defun generate-post-auth-link (post &optional comment-id absolute need-auth)
53 (if need-auth
54 (concatenate 'string (generate-post-link post comment-id absolute) "?need-auth=y")
55 (generate-post-link post comment-id absolute)))
57 (defun clean-lw-link (url)
58 (when url
59 (ppcre:regex-replace "([^/]*//[^/]*)lesserwrong\.com" url "\\1lesswrong.com")))
61 (defun votes-to-tooltip (votes)
62 (if votes
63 (format nil "~A vote~:*~P"
64 (typecase votes (integer votes) (list (length votes))))
65 ""))
67 (defun post-section-to-html (post &key skip-section)
68 (alist-bind ((user-id string)
69 (frontpage-date (or null string))
70 (curated-date (or null string))
71 (meta boolean)
72 (af boolean)
73 (draft boolean))
74 post
75 (multiple-value-bind (class title href)
76 (cond (af (if (eq skip-section :alignment-forum) nil (values "alignment-forum" "View Alignment Forum posts" "/index?view=alignment-forum")))
77 ; show alignment forum even if skip-section is t
78 ((eq skip-section t) nil)
79 (draft nil)
80 (curated-date (if (eq skip-section :featured) nil (values "featured" "View Featured posts" "/index?view=featured")))
81 (frontpage-date (if (eq skip-section :frontpage) nil (values "frontpage" "View Frontpage posts" "/")))
82 (meta (if (eq skip-section :meta) nil (values "meta" "View Meta posts" "/index?view=meta")))
83 (t (if (eq skip-section :personal) nil (values "personal" (format nil "View posts by ~A" (get-username user-id)) (format nil "/users/~A?show=posts" (get-user-slug user-id))))))
84 <a class=("post-section ~A" class) title=title href=href></a>)))
86 (defun post-headline-to-html (post &key skip-section need-auth)
87 (alist-bind ((post-id string :--id)
88 (title string)
89 (user-id string)
90 (url (or null string))
91 (posted-at string)
92 (base-score fixnum)
93 (comment-count (or null fixnum))
94 (page-url (or null string))
95 (word-count (or null fixnum))
96 (frontpage-date (or null string))
97 (curated-date (or null string))
98 (meta boolean)
99 (af boolean)
100 (question boolean)
101 (vote-count (or null fixnum))
102 (draft boolean))
103 post
104 (multiple-value-bind (pretty-time js-time) (pretty-time posted-at)
105 <h1 class=("listing~{ ~A~}" (list-cond
106 (url "link-post-listing")
107 (question "question-post-listing")
108 ((logged-in-userid user-id) "own-post-listing")))>
109 (if url <a href=(convert-any-link (string-trim " " url))>&#xf0c1;</a>)
110 <a href=(generate-post-auth-link post nil nil need-auth)>
111 (if question <span class="post-type-prefix">[Question] </span>)
112 (safe (clean-text-to-html title))
113 </a>
114 (if (logged-in-userid user-id) <a class="edit-post-link button" href=("/edit-post?post-id=~A" post-id)></a>)
115 </h1>
116 <div class="post-meta">
117 <a class=("author~{ ~A~}" (list-cond ((logged-in-userid user-id) "own-user-author")))
118 href=("/users/~A" (get-user-slug user-id))
119 data-userid=user-id>
120 (get-username user-id)
121 </a>
122 <div class="date" data-js-date=js-time>(progn pretty-time)</div>
123 <div class="karma">
124 <span class="karma-value" title=(votes-to-tooltip vote-count)>(safe (pretty-number base-score "point"))</span>
125 </div>
126 <a class="comment-count" href=("~A#comments" (generate-post-link post))>(safe (pretty-number (or comment-count 0) "comment"))</a>
127 (if word-count <span class="read-time" title=(safe (pretty-number word-count "word"))>(max 1 (round word-count 300))<span> min read</span></span>)
128 (if page-url <a class="lw2-link" href=(clean-lw-link page-url)>(main-site-abbreviation *current-site*)<span> link</span></a>)
129 (with-html-stream-output (post-section-to-html post :skip-section skip-section))
130 (if url <div class="link-post-domain">("(~A)" (puri:uri-host (puri:parse-uri (string-trim " " url))))</div>)
131 </div>)))
133 (defun post-body-to-html (post)
134 (alist-bind ((post-id string :--id)
135 (title string)
136 (user-id string)
137 (url (or null string))
138 (posted-at string)
139 (base-score fixnum)
140 (tags (or null list))
141 (comment-count (or null fixnum))
142 (page-url (or null string))
143 (frontpage-date (or null string))
144 (curated-date (or null string))
145 (meta boolean)
146 (draft boolean)
147 (af boolean)
148 (question boolean)
149 (vote-count (or null fixnum))
150 (html-body (or null string)))
151 post
152 (multiple-value-bind (pretty-time js-time) (pretty-time posted-at)
153 <div class=("post~{ ~A~}" (list-cond
154 (url "link-post")
155 (question "question-post")))>
156 <h1 class="post-title">
157 (if question <span class="post-type-prefix">[Question] </span>)
158 (safe (clean-text-to-html title :hyphenation nil))
159 </h1>
160 <div class="post-meta">
161 <a class=("author~{ ~A~}" (list-cond
162 ((logged-in-userid user-id) "own-user-author")))
163 href=("/users/~A" (get-user-slug user-id))
164 data-userid=user-id>
165 (get-username user-id)
166 </a>
167 <div class="date" data-js-date=js-time>(progn pretty-time)</div>
168 <div class="karma" data-post-id=post-id>
169 <span class="karma-value" title=(votes-to-tooltip vote-count)>(safe (pretty-number base-score "point"))</span>
170 </div>
171 <a class="comment-count" href="#comments">(safe (pretty-number (or comment-count 0) "comment"))</a>
172 (if page-url <a class="lw2-link" href=(clean-lw-link page-url)>(main-site-abbreviation *current-site*)<span> link</span></a>)
173 (with-html-stream-output (post-section-to-html post))
174 (when tags
175 <div id="tags">
176 (dolist (tag tags) (alist-bind ((text string)) tag <a href=("/tags/~A" text)>(progn text)</a>))
177 </div>)
178 </div>
179 <div class="post-body">
180 (if url <p><a class="link-post-link" href=(convert-any-link (string-trim " " url))>Link post</a></p>)
181 (with-html-stream-output
182 (write-sequence (clean-html* (or html-body "") :with-toc t :post-id post-id) *html-output*))
183 </div>
184 </div>)))
186 (defparameter *comment-individual-link* nil)
188 (defun comment-to-html (out-stream comment &key with-post-title)
189 (if (or (cdr (assoc :deleted comment)) (cdr (assoc :deleted-public comment)))
190 (format out-stream "<div class=\"comment deleted-comment\"><div class=\"comment-meta\"><span class=\"deleted-meta\">[ ]</span></div><div class=\"comment-body\">[deleted]</div></div>")
191 (alist-bind ((comment-id string :--id)
192 (user-id string)
193 (posted-at string)
194 (highlight-new boolean)
195 (post-id string)
196 (base-score fixnum)
197 (page-url (or null string))
198 (parent-comment list)
199 (parent-comment-id (or null string))
200 (child-count (or null fixnum))
201 (children list)
202 (vote-count (or null fixnum))
203 (retracted boolean)
204 (answer boolean)
205 (parent-answer-id (or null string))
206 (html-body string))
207 comment
208 (multiple-value-bind (pretty-time js-time) (pretty-time posted-at)
209 <div class=("comment~{ ~A~}"
210 (list-cond
211 ((and (logged-in-userid user-id)
212 (< (* 1000 (local-time:timestamp-to-unix (local-time:now))) (+ js-time 15000)))
213 "just-posted-comment")
214 (highlight-new "comment-item-highlight")
215 (retracted "retracted")))>
216 <div class="comment-meta">
217 <a class=("author~:[~; own-user-author~]" (logged-in-userid user-id))
218 href=("/users/~A" (encode-entities (get-user-slug user-id)))
219 data-userid=user-id>
220 (get-username user-id)
221 </a>
222 <a class="date" href=(generate-post-link post-id comment-id) data-js-date=js-time> (safe pretty-time) </a>
223 <div class="karma">
224 <span class="karma-value" title=(votes-to-tooltip vote-count)> (safe (pretty-number base-score "point")) </span>
225 </div>
226 <a class="permalink" href=("~A/~A/~A"
227 (generate-post-link post-id)
228 (cond ((or answer parent-answer-id) "answer") (t "comment"))
229 comment-id)
230 title="Permalink"></a>
231 (with-html-stream-output
232 (when page-url
233 <a class="lw2-link" href=(clean-lw-link page-url) title=(main-site-abbreviation *current-site*)></a>)
234 (if with-post-title
235 <div class="comment-post-title">
236 (with-html-stream-output
237 (when parent-comment
238 (alist-bind ((user-id string)
239 (post-id string)
240 (parent-id string :--id))
241 parent-comment
242 <span class="comment-in-reply-to">in reply to:
243 <a href=("/users/~A" (get-user-slug user-id))
244 class=("inline-author~:[~; own-user-author~]" (logged-in-userid user-id))
245 data-userid=(progn user-id)>
246 (get-username user-id)</a>'s
247 <a href=(generate-post-link post-id parent-id)>comment</a>
248 (progn " ")
249 </span>)))
250 <span class="comment-post-title2">on: <a href=(generate-post-link post-id)>(safe (clean-text-to-html (get-post-title post-id)))</a></span>
251 </div>
252 (when parent-comment-id
253 (if *comment-individual-link*
254 <a class="comment-parent-link" href=(progn parent-comment-id) title="Parent"></a>
255 <a class="comment-parent-link" href=("#comment-~A" parent-comment-id)>Parent</a>)))
256 (when children
257 <div class="comment-child-links">
258 Replies:
259 (with-html-stream-output
260 (dolist (child children)
261 (alist-bind ((comment-id string)
262 (user-id string))
263 child
264 <a href=("#comment-~A" comment-id)>(">~A" (get-username user-id))</a>)))
265 </div>)
266 <div class="comment-minimize-button"
267 data-child-count=(progn child-count)>
268 </div>)
269 </div>
270 <div class="comment-body" (safe ("~@[ data-markdown-source=\"~A\"~]"
271 (if (logged-in-userid user-id)
272 (encode-entities
273 (or (cache-get "comment-markdown-source" comment-id)
274 html-body)))))>
275 (with-html-stream-output (write-sequence (clean-html* html-body) out-stream))
276 </div>
277 </div>))))
279 (defun postprocess-conversation-title (title)
280 (if (or (null title) (string= title ""))
281 "[Untitled conversation]"
282 title))
284 (defun conversation-message-to-html (out-stream message)
285 (alist-bind ((user-id string)
286 (created-at string)
287 (highlight-new boolean)
288 (conversation list)
289 (content list)
290 (html-body (or string null)))
291 message
292 (multiple-value-bind (pretty-time js-time) (pretty-time created-at)
293 (format out-stream "<div class=\"comment private-message~A\"><div class=\"comment-meta\"><a class=\"author\" href=\"/users/~A\">~A</a> <span class=\"date\" data-js-date=\"~A\">~A</span><div class=\"comment-post-title\">Private message in: <a href=\"/conversation?id=~A\">~A</a></div></div><div class=\"comment-body\">"
294 (if highlight-new " comment-item-highlight" "")
295 (encode-entities (get-user-slug user-id))
296 (encode-entities (get-username user-id))
297 js-time
298 pretty-time
299 (encode-entities (cdr (assoc :--id conversation)))
300 (encode-entities (postprocess-conversation-title (cdr (assoc :title conversation))))))
301 (if html-body
302 (write-sequence (clean-html* html-body) out-stream)
303 (format out-stream "~{<p>~A</p>~}" (loop for block in (cdr (assoc :blocks content)) collect (encode-entities (cdr (assoc :text block))))))
304 (format out-stream "</div></div>")))
306 (defun conversation-index-to-html (out-stream conversation)
307 (alist-bind ((conversation-id string :--id)
308 (title (or null string))
309 (created-at (or null string))
310 (participants list)
311 (messages-total fixnum))
312 conversation
313 (multiple-value-bind (pretty-time js-time) (if created-at (pretty-time created-at) (values "[Error]" 0))
314 (format out-stream "<h1 class=\"listing\"><a href=\"/conversation?id=~A\">~A</a></h1><div class=\"post-meta\"><div class=\"conversation-participants\"><ul>~:{<li><a href=\"/users/~A\">~A</a></li>~}</ul></div><div class=\"messages-count\">~A</div><div class=\"date\" data-js-date=\"~A\">~A</div></div>"
315 (encode-entities conversation-id)
316 (encode-entities (postprocess-conversation-title title))
317 (loop for p in participants
318 collect (list (encode-entities (cdr (assoc :slug p))) (encode-entities (cdr (assoc :display-name p)))))
319 (pretty-number messages-total "message")
320 js-time
321 pretty-time))))
323 (defun error-to-html (out-stream condition)
324 (format out-stream "<div class=\"gw-error\"><h1>Error</h1><p>~A</p></div>"
325 (encode-entities (princ-to-string condition))))
327 (defmacro with-error-html-block ((out-stream) &body body)
328 "If an error occurs within BODY, write an HTML representation of the
329 signaled condition to OUT-STREAM."
330 `(handler-case
331 (log-conditions (progn ,@body))
332 (serious-condition (c)
333 (error-to-html ,out-stream c))))
335 (defun make-comment-parent-hash (comments)
336 (let ((existing-comment-hash (make-hash-table :test 'equal))
337 (hash (make-hash-table :test 'equal)))
338 (dolist (c comments)
339 (alexandria:if-let (id (cdr (assoc :--id c)))
340 (setf (gethash id existing-comment-hash) t)))
341 (dolist (c comments)
342 (let* ((parent-id (cdr (assoc :parent-comment-id c)))
343 (old (gethash parent-id hash)))
344 (setf (gethash parent-id hash) (cons c old))
345 (when (and parent-id (not (gethash parent-id existing-comment-hash)))
346 (let ((placeholder (alist :--id parent-id :parent-comment-id nil :deleted t)))
347 (setf (gethash parent-id existing-comment-hash) t
348 (gethash nil hash) (cons placeholder (gethash nil hash)))))))
349 (maphash (lambda (k old)
350 (setf (gethash k hash) (nreverse old)))
351 hash)
352 (labels
353 ((count-children (parent)
354 (let ((children (gethash (cdr (assoc :--id parent)) hash)))
355 (+ (length children) (apply #'+ (map 'list #'count-children children)))))
356 (add-child-counts (comment-list)
357 (loop for c in comment-list
358 as id = (cdr (assoc :--id c))
359 do (setf (gethash id hash) (add-child-counts (gethash id hash)))
360 collecting (cons (cons :child-count (count-children c)) c))))
361 (setf (gethash nil hash) (add-child-counts (gethash nil hash))))
362 hash))
364 (defun comment-thread-to-html (out-stream emit-comment-item-fn)
365 (format out-stream "<ul class=\"comment-thread\">")
366 (funcall emit-comment-item-fn)
367 (format out-stream "</ul>"))
369 (defun comment-item-to-html (out-stream comment &key extra-html-fn)
370 (with-error-html-block (out-stream)
371 (let ((c-id (cdr (assoc :--id comment))))
372 (format out-stream "<li id=\"comment-~A\" class=\"comment-item\">" c-id)
373 (unwind-protect
374 (comment-to-html out-stream comment)
375 (if extra-html-fn (funcall extra-html-fn c-id))
376 (format out-stream "</li>")))))
378 (defun comment-tree-to-html (out-stream comment-hash &optional (target nil) (level 0))
379 (let ((comments (gethash target comment-hash)))
380 (when comments
381 (comment-thread-to-html out-stream
382 (lambda ()
383 (loop for c in comments do
384 (comment-item-to-html out-stream c
385 :extra-html-fn (lambda (c-id)
386 (if (and (= level 10) (gethash c-id comment-hash))
387 (format out-stream "<input type=\"checkbox\" id=\"expand-~A\"><label for=\"expand-~:*~A\" data-child-count=\"~A comment~:P\">Expand this thread</label>"
388 c-id
389 (cdr (assoc :child-count c))))
390 (comment-tree-to-html out-stream comment-hash c-id (1+ level))))))))))
392 (defun comment-chrono-to-html (out-stream comments)
393 (let ((comment-hash (make-comment-parent-hash comments))
394 (comments-sorted (sort comments #'local-time:timestamp< :key (lambda (c) (local-time:parse-timestring (cdr (assoc :posted-at c)))))))
395 (comment-thread-to-html out-stream
396 (lambda ()
397 (loop for c in comments-sorted do
398 (let* ((c-id (cdr (assoc :--id c)))
399 (new-c (acons :children (gethash c-id comment-hash) c)))
400 (comment-item-to-html out-stream new-c)))))))
402 (defun comment-post-interleave (list &key limit offset (sort-by :date))
403 (multiple-value-bind (sort-fn sort-key)
404 (ecase sort-by
405 (:date (values #'local-time:timestamp> (lambda (x) (local-time:parse-timestring (cdr (assoc :posted-at x))))))
406 (:score (values #'> (lambda (x) (cdr (assoc :base-score x))))))
407 (let ((sorted (sort list sort-fn :key sort-key)))
408 (loop for end = (if (or limit offset) (+ (or limit 0) (or offset 0)))
409 for x in sorted
410 for count from 0
411 until (and end (>= count end))
412 when (or (not offset) (>= count offset))
413 collect x))))
415 (defun identify-item (x)
416 (cond
417 ((typep x 'condition)
418 :condition)
419 ((assoc :message x)
420 :notification)
421 ((string= (cdr (assoc :----typename x)) "Message")
422 :message)
423 ((string= (cdr (assoc :----typename x)) "Conversation")
424 :conversation)
425 ((assoc :comment-count x)
426 :post)
428 :comment)))
430 (defun write-index-items-to-html (out-stream items &key need-auth (empty-message "No entries.") skip-section)
431 (if items
432 (dolist (x items)
433 (with-error-html-block (out-stream)
434 (ecase (identify-item x)
435 (:condition
436 (error-to-html out-stream x))
437 (:notification
438 (format out-stream "<p>~A</p>" (cdr (assoc :message x))))
439 (:message
440 (format out-stream "<ul class=\"comment-thread\"><li class=\"comment-item\">")
441 (unwind-protect
442 (conversation-message-to-html out-stream x)
443 (format out-stream "</li></ul>")))
444 (:conversation
445 (conversation-index-to-html out-stream x))
446 (:post
447 (post-headline-to-html x :need-auth need-auth :skip-section skip-section))
448 (:comment
449 (format out-stream "<ul class=\"comment-thread\"><li class=\"comment-item\" id=\"comment-~A\">" (cdr (assoc :--id x)))
450 (unwind-protect
451 (comment-to-html out-stream x :with-post-title t)
452 (format out-stream "</li></ul>"))))))
453 (format out-stream "<div class=\"listing-message\">~A</div>" empty-message)))
455 (defun write-index-items-to-rss (out-stream items &key title need-auth)
456 (let ((full-title (format nil "~@[~A - ~]~A" title (site-title *current-site*))))
457 (xml-emitter:with-rss2 (out-stream :encoding "UTF-8")
458 (xml-emitter:rss-channel-header full-title (site-uri *current-site*) :description full-title)
459 (labels ((emit-item (item &key title link (guid (cdr (assoc :--id item))) (author (get-username (cdr (assoc :user-id item))))
460 (date (pretty-time (cdr (assoc :posted-at item)) :format local-time:+rfc-1123-format+)) body)
461 (xml-emitter:rss-item
462 title
463 :link link
464 :author author
465 :pubDate date
466 :guid guid
467 :description body)))
468 (dolist (item items)
469 (ecase (identify-item item)
470 (:post
471 (let ((author (get-username (cdr (assoc :user-id item)))))
472 (emit-item item
473 :title (clean-text (format nil "~A by ~A" (cdr (assoc :title item)) author))
474 :author author
475 :link (generate-post-auth-link item nil t need-auth)
476 :body (clean-html (or (cdr (assoc :html-body (get-post-body (cdr (assoc :--id item)) :revalidate nil))) "") :post-id (cdr (assoc :--id item))))))
477 (:comment
478 (emit-item item
479 :title (format nil "Comment by ~A on ~A" (get-username (cdr (assoc :user-id item))) (get-post-title (cdr (assoc :post-id item))))
480 :link (generate-post-link (cdr (assoc :post-id item)) (cdr (assoc :--id item)) t)
481 :body (clean-html (cdr (assoc :html-body item)))))))))))
483 (defparameter *fonts-stylesheet-uris*
484 '("https://fonts.greaterwrong.com/?fonts=InconsolataGW,CharterGW,ConcourseGW,Whitney,MundoSans,SourceSansPro,Raleway,ProximaNova,TiredOfCourier,AnonymousPro,InputSans,InputSansNarrow,InputSansCondensed,GaramondPremierPro,TriplicateCode,TradeGothic,NewsGothicBT,Caecilia,SourceSerifPro,SourceCodePro"
485 "https://fonts.greaterwrong.com/?fonts=BitmapFonts,FontAwesomeGW&base64encode=1"))
486 ;(defparameter *fonts-stylesheet-uris* '("https://fonts.greaterwrong.com/?fonts=*"))
488 (defvar *fonts-redirect-data* nil)
489 (sb-ext:defglobal *fonts-redirect-lock* (make-mutex))
490 (sb-ext:defglobal *fonts-redirect-thread* nil)
492 (defun generate-fonts-links ()
493 (let ((current-time (get-unix-time)))
494 (labels ((get-redirects (uri-list)
495 (loop for request-uri in uri-list collect
496 (multiple-value-bind (body status headers uri)
497 (drakma:http-request request-uri :method :head :close t :redirect nil :additional-headers (alist :referer (site-uri (first *sites*)) :accept "text/css,*/*;q=0.1"))
498 (declare (ignore body uri))
499 (let ((location (cdr (assoc :location headers))))
500 (if (and (typep status 'integer) (< 300 status 400) location)
501 location
502 nil)))))
503 (update-redirects ()
504 (handler-case
505 (let* ((new-redirects (get-redirects *fonts-stylesheet-uris*))
506 (new-redirects (loop for new-redirect in new-redirects
507 for original-uri in *fonts-stylesheet-uris*
508 collect (if new-redirect (quri:render-uri (quri:merge-uris (quri:uri new-redirect) (quri:uri original-uri))) original-uri))))
509 (with-mutex (*fonts-redirect-lock*) (setf *fonts-redirect-data* (list *fonts-stylesheet-uris* new-redirects current-time)
510 *fonts-redirect-thread* nil))
511 new-redirects)
512 (serious-condition () *fonts-stylesheet-uris*)))
513 (ensure-update-thread ()
514 (with-mutex (*fonts-redirect-lock*)
515 (or *fonts-redirect-thread*
516 (setf *fonts-redirect-thread* (make-thread #'update-redirects :name "fonts redirect update"))))))
517 (destructuring-bind (&optional base-uris redirect-uris timestamp) (with-mutex (*fonts-redirect-lock*) *fonts-redirect-data*)
518 (if (and (eq base-uris *fonts-stylesheet-uris*) timestamp)
519 (progn
520 (if (>= current-time (+ timestamp 60))
521 (ensure-update-thread))
522 (or redirect-uris *fonts-stylesheet-uris*))
523 (update-redirects))))))
525 (defparameter *html-head*
526 (format nil
527 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
528 <meta name=\"HandheldFriendly\" content=\"True\" />"))
530 (defparameter *extra-external-scripts* "")
531 (defparameter *extra-inline-scripts* "")
533 (defun generate-versioned-link (file)
534 (format nil "~A?v=~A" file (sb-posix:stat-mtime (sb-posix:stat (format nil "www~A" file)))))
536 (defun search-bar-to-html (out-stream)
537 (declare (special *current-search-query*))
538 (let ((query (and (boundp '*current-search-query*) (hunchentoot:escape-for-html *current-search-query*))))
539 (format out-stream "<form action=\"/search\" class=\"nav-inner\"><input name=\"q\" type=\"search\" ~@[value=\"~A\"~] autocomplete=\"off\" accesskey=\"s\" title=\"Search [s]~@[&#10;Tip: Paste a ~A URL here to jump to that page.~]\"><button>Search</button></form>" query (main-site-title *current-site*))))
541 (defun inbox-to-html (out-stream user-slug &optional new-messages)
542 (let* ((target-uri (format nil "/users/~A?show=inbox" user-slug))
543 (as-link (string= (hunchentoot:request-uri*) target-uri)))
544 (multiple-value-bind (nm-class nm-text)
545 (if new-messages (values "new-messages" "New messages") (values "no-messages" "Inbox"))
546 (format out-stream "<~:[a href=\"~A\"~;span~*~] id=\"inbox-indicator\" class=\"~A\" accesskey=\"o\" title=\"~A~:[ [o]~;~]\">~A</a>"
547 as-link target-uri nm-class nm-text as-link nm-text))))
549 (defmethod site-nav-bars ((site site))
550 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
551 ("about" "/about" "About" :accesskey "t")
552 ("search" "/search" "Search" :html search-bar-to-html)
553 user-nav-item))
554 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
555 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
557 (defmethod site-nav-bars ((site lesswrong-viewer-site))
558 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
559 ("about" "/about" "About" :accesskey "t")
560 ("search" "/search" "Search" :html search-bar-to-html)
561 user-nav-item))
562 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
563 ("featured" "/index?view=featured" "Featured" :description "Latest featured posts" :accesskey "f")
564 ("all" "/index?view=all" "All" :description "Latest posts from all sections" :accesskey "a")
565 ("meta" "/index?view=meta" "Meta" :description "Latest meta posts" :accesskey "m")
566 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
568 (defmethod site-nav-bars ((site ea-forum-viewer-site))
569 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
570 ("about" "/about" "About" :accesskey "t")
571 ("search" "/search" "Search" :html search-bar-to-html)
572 user-nav-item))
573 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
574 ("all" "/index?view=all" "All" :description "Latest posts from all sections" :accesskey "a")
575 ("meta" "/index?view=community" "Community" :description "Latest community posts" :accesskey "m")
576 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
578 (defun prepare-nav-bar (nav-bar current-uri)
579 (list (first nav-bar)
580 (map 'list (lambda (item) (if (listp item) item (funcall item current-uri)))
581 (second nav-bar))))
583 (defun nav-item-active (item current-uri)
584 (when item
585 (destructuring-bind (id uri name &key description html accesskey nofollow trailing-html override-uri) item
586 (declare (ignore id name description html accesskey nofollow trailing-html))
587 (string= (or override-uri uri) current-uri))))
589 (defun nav-bar-active (nav-bar current-uri)
590 (some (lambda (x) (nav-item-active x current-uri)) (second nav-bar)))
592 (defun nav-bar-inner (out-stream items &optional current-uri)
593 (maplist (lambda (items)
594 (let ((item (first items)))
595 (destructuring-bind (id uri name &key description html accesskey nofollow trailing-html override-uri) item
596 (declare (ignore override-uri))
597 (let* ((item-active (nav-item-active item current-uri))
598 (nav-class (format nil "nav-item ~:[nav-inactive~;nav-current~]~:[~; nav-item-last-before-current~]"
599 item-active (and (not item-active) (nav-item-active (cadr items) current-uri)))))
600 (format out-stream "<span id=\"nav-item-~A\" class=\"~A\" ~@[title=\"~A\"~]>"
601 id nav-class description)
602 (if html
603 (funcall html out-stream)
604 (link-if-not out-stream item-active uri "nav-inner" name :accesskey accesskey :nofollow nofollow))
605 (if trailing-html
606 (funcall trailing-html out-stream))
607 (format out-stream "</span>")))))
608 items))
610 (defun nav-bar-outer (out-stream class nav-bar &optional current-uri)
611 (format out-stream "<div id=\"~A\" class=\"nav-bar~@[ ~A~]\">" (string-downcase (first nav-bar)) class)
612 (nav-bar-inner out-stream (second nav-bar) current-uri)
613 (format out-stream "</div>"))
615 (defun nav-bar-to-html (out-stream &optional current-uri)
616 (let* ((nav-bars (map 'list (lambda (x) (prepare-nav-bar x current-uri)) (site-nav-bars *current-site*)))
617 (active-bar (or (find-if (lambda (x) (nav-bar-active x current-uri)) nav-bars) (car (last nav-bars))))
618 (inactive-bars (remove active-bar nav-bars)))
619 (dolist (bar inactive-bars)
620 (nav-bar-outer out-stream "inactive-bar" bar current-uri))
621 (nav-bar-outer out-stream "active-bar" active-bar current-uri)))
623 (defun user-nav-item (&optional current-uri)
624 (if *read-only-mode*
625 `("login" "/login" "Read Only Mode" :html ,(lambda () (format nil "<span class=\"nav-inner\" title=\"~A\">[Read Only Mode]</span>"
626 (typecase *read-only-mode*
627 (string *read-only-mode*)
628 (t *read-only-default-message*)))))
629 (alexandria:if-let (username (logged-in-username))
630 (let ((user-slug (encode-entities (logged-in-user-slug))))
631 `("login" ,(format nil "/users/~A" user-slug) ,(plump:encode-entities username) :description "User page" :accesskey "u"
632 :trailing-html ,(lambda (out-stream) (inbox-to-html out-stream user-slug))))
633 `("login" ,(format nil "/login?return=~A" (url-rewrite:url-encode current-uri)) "Log In" :accesskey "u" :nofollow t :override-uri "/login"))))
635 (defun sublevel-nav-to-html (out-stream options current &key default (base-uri (hunchentoot:request-uri*)) (param-name "show") (remove-params '("offset")) extra-class)
636 (declare (type (or null string) extra-class))
637 (format out-stream "<div class=\"sublevel-nav~@[ ~A~]\">" extra-class)
638 (loop for item in options
639 do (multiple-value-bind (param-value text) (if (atom item)
640 (values (string-downcase item) (string-capitalize item))
641 (values-list item))
642 (let* ((selected (string-equal current param-value))
643 (class (if selected "sublevel-item selected" "sublevel-item")))
644 (link-if-not out-stream selected (apply #'replace-query-params base-uri param-name (unless (string-equal param-value default) param-value)
645 (loop for x in remove-params nconc (list x nil)))
646 class text))))
647 (format out-stream "</div>"))
649 (defun make-csrf-token (&optional (session-token (hunchentoot:cookie-in "session-token")) (nonce (ironclad:make-random-salt)))
650 (if (typep session-token 'string) (setf session-token (base64:base64-string-to-usb8-array session-token)))
651 (let ((csrf-token (concatenate '(vector (unsigned-byte 8)) nonce (ironclad:digest-sequence :sha256 (concatenate '(vector (unsigned-byte 8)) nonce session-token)))))
652 (values (base64:usb8-array-to-base64-string csrf-token) csrf-token)))
654 (defun check-csrf-token (csrf-token &optional (session-token (hunchentoot:cookie-in "session-token")))
655 (let* ((session-token (base64:base64-string-to-usb8-array session-token))
656 (csrf-token (base64:base64-string-to-usb8-array csrf-token))
657 (correct-token (nth-value 1 (make-csrf-token session-token (subseq csrf-token 0 16)))))
658 (assert (ironclad:constant-time-equal csrf-token correct-token) nil "CSRF check failed.")
659 t))
661 (defun generate-css-link ()
662 (labels ((gen-inner (theme os)
663 (generate-versioned-link (format nil "/css/style~@[-~A~].~A.css" (if (and theme (> (length theme) 0)) theme) os))))
664 (let* ((ua (hunchentoot:header-in* :user-agent))
665 (theme (hunchentoot:cookie-in "theme"))
666 (os (cond ((search "Windows" ua) "windows")
667 ((search "Mac OS" ua) "mac")
668 (t "linux"))))
669 (handler-case (gen-inner theme os)
670 (serious-condition () (gen-inner nil os))))))
672 (defun html-body (out-stream fn &key title description current-uri content-class robots)
673 (let* ((session-token (hunchentoot:cookie-in "session-token"))
674 (csrf-token (and session-token (make-csrf-token session-token))))
675 (format out-stream "<!DOCTYPE html><html lang=\"en-US\"><head>")
676 (format out-stream "<script>window.GW = { }; loggedInUserId=\"~A\"; loggedInUserDisplayName=\"~A\"; loggedInUserSlug=\"~A\"; ~@[GW.csrfToken=\"~A\"; ~]~A</script>~A"
677 (or (logged-in-userid) "")
678 (or (logged-in-username) "")
679 (or (logged-in-user-slug) "")
680 csrf-token
681 (load-time-value (with-open-file (s "www/head.js") (uiop:slurp-stream-string s)) t)
682 *extra-inline-scripts*)
683 (format out-stream "~A<link rel=\"stylesheet\" href=\"~A\">~{<link rel=\"stylesheet\" href=\"~A\">~}<link rel=\"shortcut icon\" href=\"~A\">"
684 *html-head*
685 (generate-css-link)
686 (generate-fonts-links)
687 (generate-versioned-link "/assets/favicon.ico"))
688 (format out-stream "<script src=\"~A\" async></script>~A"
689 (generate-versioned-link "/script.js")
690 *extra-external-scripts*)
691 (format out-stream "<title>~@[~A - ~]~A</title>~@[<meta name=\"description\" content=\"~A\">~]~@[<meta name=\"robots\" content=\"~A\">~]"
692 (if title (encode-entities title))
693 (site-title *current-site*)
694 description
695 robots)
696 (format out-stream "</head>"))
697 (unwind-protect
698 (progn
699 (format out-stream "<body><div id=\"content\"~@[ class=\"~A\"~]>"
700 content-class)
701 (nav-bar-to-html out-stream (or current-uri (replace-query-params (hunchentoot:request-uri*) "offset" nil "sort" nil)))
702 (force-output out-stream)
703 (funcall fn))
704 (format out-stream "</div></body></html>")))
706 (defun replace-query-params (uri &rest params)
707 (let* ((quri (quri:uri uri))
708 (old-params (quri:uri-query-params quri))
709 (new-params (loop with out = old-params
710 for (param value) on params by #'cddr
711 do (if value
712 (alexandria:if-let (old-cons (assoc param out :test #'equal))
713 (setf (cdr old-cons) value)
714 (setf out (nconc out (list (cons param value)))))
715 (setf out (remove-if (lambda (x) (equal (car x) param)) out)))
716 finally (return out))))
717 (if new-params
718 (setf (quri:uri-query-params quri) new-params)
719 (setf (quri:uri-query quri) nil))
720 (quri:render-uri quri)))
722 (defun pagination-nav-bars (&key offset total with-next (items-per-page (user-pref :items-per-page)))
723 (lambda (out-stream fn)
724 (labels ((pages-to-end (n) (< (+ offset (* items-per-page n)) total)))
725 (let* ((with-next (if total (pages-to-end 1) with-next))
726 (next (if (and offset with-next) (+ offset items-per-page)))
727 (prev (if (and offset (>= offset items-per-page)) (- offset items-per-page)))
728 (request-uri (hunchentoot:request-uri*))
729 (first-uri (if (and prev (> prev 0)) (replace-query-params request-uri "offset" nil)))
730 (prev-uri (if prev (replace-query-params request-uri "offset" (if (= prev 0) nil prev))))
731 (next-uri (if next (replace-query-params request-uri "offset" next)))
732 (last-uri (if (and total offset (pages-to-end 2))
733 (replace-query-params request-uri "offset" (- total (mod (- total 1) items-per-page) 1)))))
734 (if (or next prev last-uri)
735 (labels ((write-item (uri class title accesskey)
736 (format out-stream "<a href=\"~A\" class=\"button nav-item-~A~:[ disabled~;~]\" title=\"~A [~A]\" accesskey=\"~A\"></a>"
737 (or uri "#") class uri title accesskey accesskey)))
738 (format out-stream "<div id='top-nav-bar'>")
739 (write-item first-uri "first" "First page" "\\")
740 (write-item prev-uri "prev" "Previous page" "[")
741 (format out-stream "<span class='page-number'><span class='page-number-label'>Page</span> ~A</span>" (+ 1 (/ (or offset 0) items-per-page)))
742 (write-item next-uri "next" "Next page" "]")
743 (write-item last-uri "last" "Last page" "/")
744 (format out-stream "</div>")))
745 (funcall fn)
746 (nav-bar-outer out-stream nil (list :bottom-bar
747 (list-cond
748 (first-uri `("first" ,first-uri "Back to first"))
749 (prev-uri `("prev" ,prev-uri "Previous" :nofollow t))
750 (t `("top" "#top" "Back to top"))
751 (next-uri `("next" ,next-uri "Next" :nofollow t))
752 (last-uri `("last" ,last-uri "Last" :nofollow t)))))
753 (format out-stream "<script>document.querySelectorAll('#bottom-bar').forEach(bb => { bb.classList.add('decorative'); });</script>")))))
755 (defun map-output (out-stream fn list)
756 (loop for item in list do (write-string (funcall fn item) out-stream)))
758 (defmacro with-outputs ((out-stream) &body body)
759 (alexandria:with-gensyms (stream-sym)
760 (let ((out-body (map 'list (lambda (x) `(princ ,x ,stream-sym)) body)))
761 `(let ((,stream-sym ,out-stream))
762 ,.out-body))))
764 (defun call-with-emit-page (out-stream fn &key title description current-uri content-class (return-code 200) robots (pagination (pagination-nav-bars)) top-nav)
765 (declare (ignore return-code))
766 (ignore-errors
767 (log-conditions
768 (html-body out-stream
769 (lambda ()
770 (when top-nav (funcall top-nav out-stream))
771 (funcall pagination out-stream fn))
772 :title title :description description :current-uri current-uri :content-class content-class :robots robots)
773 (force-output out-stream))))
775 (defun set-cookie (key value &key (max-age (- (expt 2 31) 1)) (path "/"))
776 (hunchentoot:set-cookie key :value value :path path :max-age max-age :secure (site-secure *current-site*)))
778 (defun set-default-headers (return-code)
779 (let ((push-option (if (hunchentoot:cookie-in "push") '("nopush"))))
780 (setf (hunchentoot:content-type*) "text/html; charset=utf-8"
781 (hunchentoot:return-code*) return-code
782 (hunchentoot:header-out :link) (format nil "~:{<~A>;rel=preload;type=~A;as=~A~@{;~A~}~:^,~}"
783 `((,(generate-css-link) "text/css" "style" ,.push-option)
784 ,.(loop for link in (generate-fonts-links)
785 collect (list* link "text/css" "style" push-option))
786 (,(generate-versioned-link "/script.js") "text/javascript" "script" ,.push-option))))
787 (unless push-option (set-cookie "push" "t" :max-age (* 4 60 60)))))
789 (defun user-pref (key)
790 (or (cdr (assoc key *current-prefs*))
791 (cdr (assoc key *default-prefs*))))
793 (defun set-user-pref (key value)
794 (assert (boundp 'hunchentoot:*reply*))
795 (setf *current-prefs* (remove-duplicates (acons key value *current-prefs*) :key #'car :from-end t))
796 (set-cookie "prefs" (quri:url-encode (json:encode-json-to-string *current-prefs*))))
798 (defmacro with-response-stream ((out-stream) &body body) `(call-with-response-stream (lambda (,out-stream) ,.body)))
800 (defun call-with-response-stream (fn)
801 (let ((*html-output* (make-flexi-stream (hunchentoot:send-headers) :external-format :utf-8)))
802 (funcall fn *html-output*)))
804 (defmacro emit-page ((out-stream &rest args &key (return-code 200) &allow-other-keys) &body body)
805 (alexandria:once-only (return-code)
806 `(progn
807 (set-default-headers ,return-code)
808 (with-response-stream (,out-stream)
809 (call-with-emit-page ,out-stream
810 (lambda () ,@body)
811 ,@args)))))
813 (defun call-with-error-page (fn)
814 (let* ((lw2-status
815 (alexandria:if-let (status-string (hunchentoot:cookie-in "lw2-status"))
816 (if (string= status-string "") nil
817 (let ((json:*identifier-name-to-key* #'json:safe-json-intern))
818 (json:decode-json-from-string status-string)))))
819 (*current-prefs*
820 (alexandria:if-let (prefs-string (hunchentoot:cookie-in "prefs"))
821 (let ((json:*identifier-name-to-key* 'json:safe-json-intern))
822 (ignore-errors (json:decode-json-from-string (quri:url-decode prefs-string)))))))
823 (with-site-context ((let ((host (or (hunchentoot:header-in* :x-forwarded-host) (hunchentoot:header-in* :host))))
824 (or (find-site host)
825 (error "Unknown site: ~A" host))))
826 (multiple-value-bind (*current-auth-token* *current-userid* *current-username*)
827 (if *read-only-mode*
828 (values)
829 (alexandria:if-let
830 (auth-token
831 (alexandria:if-let
832 (at (hunchentoot:cookie-in "lw2-auth-token"))
833 (if (or (string= at "") (not lw2-status) (> (get-unix-time) (- (cdr (assoc :expires lw2-status)) (* 60 60 24))))
834 nil at)))
835 (with-cache-readonly-transaction
836 (values
837 auth-token
838 (cache-get "auth-token-to-userid" auth-token)
839 (cache-get "auth-token-to-username" auth-token)))))
840 (let ((*current-user-slug* (and *current-userid* (get-user-slug *current-userid*))))
841 (handler-case
842 (log-conditions
843 (funcall fn))
844 (serious-condition (condition)
845 (emit-page (out-stream :title "Error" :return-code (condition-http-return-code condition) :content-class "error-page")
846 (error-to-html out-stream condition)
847 (when (eq (hunchentoot:request-method*) :post)
848 <form method="post" class="error-retry-form">
849 (loop for (key . value) in (hunchentoot:post-parameters*)
850 do <input type="hidden" name=key value=value>)
851 <input type="submit" value="Retry">
852 </form>)))))))))
854 (defmacro with-error-page (&body body)
855 `(call-with-error-page (lambda () ,@body)))
857 (defun output-form (out-stream method action id heading csrf-token fields button-label &key textarea end-html)
858 (format out-stream "<form method=\"~A\" action=\"~A\" id=\"~A\"><h1>~A</h1>" method action id heading)
859 (loop for (id label type . params) in fields
860 do (format out-stream "<label for=\"~A\">~A:</label>" id label)
861 do (cond
862 ((string= type "select")
863 (destructuring-bind (option-list &optional default) params
864 (format out-stream "<select name=\"~A\">" id)
865 (loop for (value label) in option-list
866 do (format out-stream "<option value=\"~A\"~:[~; selected~]>~A</option>" value (string= default value) label))
867 (format out-stream "</select>")))
869 (destructuring-bind (&optional (autocomplete "off") default) params
870 (format out-stream "<input type=\"~A\" name=\"~A\" autocomplete=\"~A\"~@[ value=\"~A\"~]>" type id autocomplete (and default (encode-entities default))))))
871 do (format out-stream ""))
872 (if textarea
873 (destructuring-bind (ta-name ta-contents) textarea
874 (format out-stream "<div class=\"textarea-container\"><textarea name=\"~A\">~A</textarea><span class='markdown-reference-link'>You can use <a href='http://commonmark.org/help/' target='_blank'>Markdown</a> here.</span></div>" ta-name (encode-entities ta-contents))))
875 (format out-stream "<input type=\"hidden\" name=\"csrf-token\" value=\"~A\"><input type=\"submit\" value=\"~A\">~@[~A~]</form>"
876 csrf-token button-label end-html))
878 (defun page-toolbar-to-html (out-stream &key title new-post new-conversation logout (rss t))
879 (let ((liu (logged-in-userid)))
880 (format out-stream "<div class=\"page-toolbar\">")
881 (when logout
882 (format out-stream "<form method=\"post\" action=\"/logout\"><button class=\"logout-button button\" name=\"logout\" value=\"~A\">Log out</button></form>"
883 (make-csrf-token)))
884 (when (and new-conversation liu)
885 (multiple-value-bind (text to)
886 (typecase new-conversation (string (values "Send private message" new-conversation)) (t "New conversation"))
887 (format out-stream "<a class=\"new-private-message button\" href=\"/conversation~@[?to=~A~]\">~A</a>"
888 to text)))
889 (when (and new-post liu)
890 (format out-stream "<a class=\"new-post button\" href=\"/edit-post~@[?section=~A~]\" accesskey=\"n\" title=\"Create new post [n]\">New post</a>"
891 (typecase new-post (string new-post) (t nil))))
892 (when (and title rss)
893 (format out-stream "<a class=\"rss\" rel=\"alternate\" type=\"application/rss+xml\" title=\"~A RSS feed\" href=\"~A\">RSS</a>"
894 title (replace-query-params (hunchentoot:request-uri*) "offset" nil "format" "rss")))
895 (format out-stream "</div>")))
897 (defun view-items-index (items &key section title current-uri hide-title need-auth (pagination (pagination-nav-bars)) (top-nav (lambda (s) (page-toolbar-to-html s :title title))) (content-class "index-page"))
898 (alexandria:switch ((hunchentoot:get-parameter "format") :test #'string=)
899 ("rss"
900 (setf (hunchentoot:content-type*) "application/rss+xml; charset=utf-8")
901 (with-response-stream (out-stream)
902 (write-index-items-to-rss out-stream items :title title)))
904 (emit-page (out-stream :title (if hide-title nil title) :description (site-description *current-site*) :content-class content-class
905 :current-uri current-uri :robots (if (hunchentoot:get-parameter :offset) "noindex, nofollow")
906 :pagination pagination :top-nav top-nav)
907 (write-index-items-to-html out-stream items
908 :need-auth need-auth
909 :skip-section section)))))
911 (defun link-if-not (stream linkp url class text &key accesskey nofollow)
912 (declare (dynamic-extent linkp url text))
913 (if (not linkp)
914 (format stream "<a href=\"~A\" class=\"~A\"~@[ accesskey=\"~A\"~]~:[~; rel=\"nofollow\"~]>~A</a>" url class accesskey nofollow text)
915 (format stream "<span class=\"~A\">~A</span>" class text)))
917 (defun postprocess-markdown (markdown)
918 (if (typep *current-site* 'alternate-frontend-site)
919 (ppcre:regex-replace-all
920 (concatenate 'string (ppcre:regex-replace-all "\\." (site-uri *current-site*) "\\.") "posts/([^/ ]{17})/([^/# ]*)(?:#comment-([^/ ]{17})|/comment/([^/ ]{17}))?")
921 markdown
922 (lambda (target-string start end match-start match-end reg-starts reg-ends)
923 (declare (ignore start end match-start match-end))
924 (labels ((reg (n) (if (and (> (length reg-starts) n) (aref reg-starts n))
925 (substring target-string (aref reg-starts n) (aref reg-ends n)))))
926 (quri:render-uri
927 (quri:merge-uris
928 (format nil "/posts/~A/~A~@[#~A~]" (reg 0) (reg 1) (or (reg 2) (reg 3)))
929 (main-site-uri *current-site*))))))
930 markdown))
932 (defun redirect (uri &key (type :see-other))
933 (setf (hunchentoot:return-code*) (ecase type (:see-other 303) (:permanent 301))
934 (hunchentoot:header-out "Location") uri))
936 (defmacro ignorable-multiple-value-bind ((&rest bindings) value-form &body body)
937 (let (new-bindings ignores)
938 (dolist (binding (reverse bindings))
939 (if (eq binding '*)
940 (let ((gensym (gensym)))
941 (push gensym new-bindings)
942 (push gensym ignores))
943 (push binding new-bindings)))
944 `(multiple-value-bind ,new-bindings ,value-form
945 (declare (ignore ,.ignores))
946 ,@body)))
948 (defmacro define-page (name path-specifier additional-vars &body body)
949 (labels ((make-lambda (args)
950 (loop for a in args
951 collect (if (atom a) a (first a))))
952 (filter-plist (plist &rest args)
953 (declare (dynamic-extent args))
954 (map-plist (lambda (key val) (when (member key args) (list key val))) plist)))
955 (multiple-value-bind (path-specifier-form path-bindings-wrapper specifier-vars)
956 (if (stringp path-specifier)
957 (values path-specifier #'identity)
958 (destructuring-bind (specifier-type specifier-body &rest specifier-args) path-specifier
959 (ecase specifier-type
960 (:function
961 (values `(lambda (r) (funcall ,specifier-body (hunchentoot:request-uri r)))
962 (if specifier-args
963 (lambda (body) `(ignorable-multiple-value-bind ,(make-lambda specifier-args) (funcall ,specifier-body (hunchentoot:request-uri*)) ,body))
964 #'identity)
965 specifier-args))
966 (:regex
967 (let ((fn `(lambda (r) (ppcre:scan-to-strings ,specifier-body (hunchentoot:request-uri r)))))
968 (values fn
969 (lambda (body)
970 (alexandria:with-gensyms (result-vector)
971 `(let ((,result-vector (nth-value 1 (funcall ,fn hunchentoot:*request*))))
972 (declare (type simple-vector ,result-vector))
973 (let
974 ,(loop for v in (make-lambda specifier-args) as x from 0 collecting `(,v (if (> (length ,result-vector) ,x) (aref ,result-vector ,x))))
975 ,body))))
976 specifier-args))))))
977 (let* ((rewritten-body
978 (if (eq (ignore-errors (caar body)) 'request-method)
979 (progn
980 (unless (= (length body) 1)
981 (error "REQUEST-METHOD must be the only form when it appears in DEFINE-PAGE."))
982 `((ecase (hunchentoot:request-method*)
983 ,.(loop for method-body in (cdar body)
984 collect (destructuring-bind (method args &body inner-body) method-body
985 (unless (eq method :get)
986 (alexandria:with-gensyms (csrf-token)
987 (push `(,csrf-token :real-name "csrf-token" :required t) args)
988 (push `(check-csrf-token ,csrf-token) inner-body)))
989 `(,method ,(make-binding-form (mapcar (lambda (x) (append (ensure-list x) `(:request-type ,method))) args)
990 inner-body)))))))
991 body)))
992 `(hunchentoot:define-easy-handler (,name :uri ,path-specifier-form) ()
993 (with-error-page
994 (block nil
995 ,(funcall path-bindings-wrapper
996 (make-binding-form (append (mapcar (lambda (x) (append (ensure-list x) '(:passthrough t))) specifier-vars) additional-vars)
997 rewritten-body)))))))))
999 (define-component sort-widget (&key (sort-options '(:new :hot)) (pref :default-sort) (param-name "sort") (html-class "sort"))
1000 (:http-args '((sort :real-name param-name :member sort-options)))
1001 (let ((sort-string (if sort (string-downcase sort))))
1002 (if sort-string
1003 (set-user-pref :default-sort sort-string))
1004 (renderer (out-stream)
1005 (sublevel-nav-to-html out-stream
1006 sort-options
1007 (user-pref pref)
1008 :param-name param-name
1009 :extra-class html-class))
1010 (or sort-string (user-pref pref))))
1012 (define-page view-root "/" ((offset :type fixnum)
1013 (limit :type fixnum))
1014 (component-value-bind ((sort-string sort-widget))
1015 (multiple-value-bind (posts total)
1016 (get-posts-index :offset offset :limit (or limit (user-pref :items-per-page)) :sort sort-string)
1017 (view-items-index posts
1018 :section :frontpage :title "Frontpage posts" :hide-title t
1019 :pagination (pagination-nav-bars :offset (or offset 0) :total total :with-next (not total))
1020 :top-nav (lambda (out-stream)
1021 (page-toolbar-to-html out-stream
1022 :title "Frontpage posts"
1023 :new-post t)
1024 (funcall sort-widget out-stream))))))
1026 (define-page view-index "/index" ((view :member '(:all :new :frontpage :featured :meta :community :alignment-forum :questions) :default :all)
1027 before after
1028 (offset :type fixnum)
1029 (limit :type fixnum))
1030 (when (eq view :new) (redirect (replace-query-params (hunchentoot:request-uri*) "view" "all" "all" nil) :type :permanent) (return))
1031 (component-value-bind ((sort-string sort-widget))
1032 (multiple-value-bind (posts total)
1033 (get-posts-index :view (string-downcase view) :before before :after after :offset offset :limit (or limit (user-pref :items-per-page)) :sort sort-string)
1034 (let ((page-title (format nil "~@(~A posts~)" view)))
1035 (view-items-index posts
1036 :section view :title page-title
1037 :pagination (pagination-nav-bars :offset (or offset 0) :total total :with-next (not total))
1038 :content-class (format nil "index-page ~(~A~)-index-page" view)
1039 :top-nav (lambda (out-stream)
1040 (page-toolbar-to-html out-stream
1041 :title page-title
1042 :new-post (if (eq view :meta) "meta" t))
1043 (if (member view '(:all))
1044 (funcall sort-widget out-stream))))))))
1046 (define-page view-post "/post" ((id :required t))
1047 (redirect (generate-post-link id) :type :permanent))
1049 (define-page view-post-lw1-link (:function #'match-lw1-link) ()
1050 (redirect (convert-lw1-link (hunchentoot:request-uri*)) :type :permanent))
1052 (define-page view-post-lw2-slug-link (:function #'match-lw2-slug-link) ()
1053 (redirect (convert-lw2-slug-link (hunchentoot:request-uri*)) :type :see-other))
1055 (define-page view-post-lw2-sequence-link (:function #'match-lw2-sequence-link) ()
1056 (redirect (convert-lw2-sequence-link (hunchentoot:request-uri*)) :type :see-other))
1058 (define-page view-feed "/feed" ()
1059 (redirect "/?format=rss" :type :permanent))
1061 (define-page view-post-lw2-link (:function #'match-lw2-link post-id comment-id * comment-link-type) (need-auth chrono)
1062 (request-method
1063 (:get ()
1064 (let ((lw2-auth-token *current-auth-token*))
1065 (labels ((output-comments (out-stream id comments target)
1066 (format out-stream "<div id=\"~A\" class=\"comments\">" id)
1067 (with-error-html-block (out-stream)
1068 (if target
1069 (comment-thread-to-html out-stream
1070 (lambda ()
1071 (comment-item-to-html
1072 out-stream
1073 target
1074 :extra-html-fn (lambda (c-id)
1075 (let ((*comment-individual-link* nil))
1076 (comment-tree-to-html out-stream (make-comment-parent-hash comments) c-id))))))
1077 (if comments
1078 (if chrono
1079 (comment-chrono-to-html out-stream comments)
1080 (comment-tree-to-html out-stream (make-comment-parent-hash comments)))
1081 <div class="comments-empty-message">(if (string= id "answers") "No answers." "No comments.")</div>)))
1082 (format out-stream "</div>"))
1083 (output-comments-votes (out-stream)
1084 (handler-case
1085 (when lw2-auth-token
1086 (format out-stream "<script>commentVotes=~A</script>"
1087 (json:encode-json-to-string (get-post-comments-votes post-id lw2-auth-token))))
1088 (t () nil)))
1089 (output-post-vote (out-stream)
1090 (handler-case
1091 (format out-stream "<script>postVote=~A</script>"
1092 (json:encode-json-to-string (get-post-vote post-id lw2-auth-token)))
1093 (t () nil))))
1094 (multiple-value-bind (post title condition)
1095 (handler-case (nth-value 0 (get-post-body post-id :auth-token (and need-auth lw2-auth-token)))
1096 (serious-condition (c) (values nil "Error" c))
1097 (:no-error (post) (values post (cdr (assoc :title post)) nil)))
1098 (if comment-id
1099 (let* ((*comment-individual-link* t)
1100 (comment-thread-type (if (string= comment-link-type "answer") :answer :comment))
1101 (comments (case comment-thread-type
1102 (:comment (get-post-comments post-id))
1103 (:answer (get-post-answers post-id))))
1104 (target-comment (find comment-id comments :key (lambda (c) (cdr (assoc :--id c))) :test #'string=))
1105 (display-name (get-username (cdr (assoc :user-id target-comment))))
1106 (verb-phrase (cond
1107 ((and (eq comment-thread-type :answer)
1108 (not (cdr (assoc :parent-comment-id target-comment))))
1109 "answers")
1110 (t "comments on"))))
1111 (emit-page (out-stream :title (format nil "~A ~A ~A" display-name verb-phrase title)
1112 :content-class "individual-thread-page comment-thread-page")
1113 (format out-stream "<h1 class=\"post-title\">~A ~A <a href=\"~A\">~A</a></h1>"
1114 (encode-entities display-name)
1115 verb-phrase
1116 (generate-post-link post-id)
1117 (clean-text-to-html title :hyphenation nil))
1118 (output-comments out-stream "comments" comments target-comment)
1119 (when lw2-auth-token
1120 (force-output out-stream)
1121 (output-comments-votes out-stream))))
1122 (emit-page (out-stream :title title :content-class (format nil "post-page comment-thread-page~:[~; question-post-page~]" (cdr (assoc :question post))))
1123 (cond
1124 (condition
1125 (error-to-html out-stream condition))
1127 (post-body-to-html post)))
1128 (when (and lw2-auth-token (equal (logged-in-userid) (cdr (assoc :user-id post))))
1129 (format out-stream "<div class=\"post-controls\"><a class=\"edit-post-link button\" href=\"/edit-post?post-id=~A\" accesskey=\"e\" title=\"Edit post [e]\">Edit post</a></div>"
1130 (cdr (assoc :--id post))))
1131 (force-output out-stream)
1132 (handler-case
1133 (let* ((question (cdr (assoc :question post)))
1134 (answers (when question
1135 (get-post-answers post-id)))
1136 (comments (get-post-comments post-id)))
1137 (when question
1138 (output-comments out-stream "answers" answers nil))
1139 (output-comments out-stream "comments" comments nil))
1140 (serious-condition (c) (error-to-html out-stream c)))
1141 (when lw2-auth-token
1142 (force-output out-stream)
1143 (output-post-vote out-stream)
1144 (output-comments-votes out-stream))))))))
1145 (:post (csrf-token text answer parent-answer-id parent-comment-id edit-comment-id retract-comment-id unretract-comment-id delete-comment-id)
1146 (let ((lw2-auth-token *current-auth-token*))
1147 (check-csrf-token csrf-token)
1148 (assert lw2-auth-token)
1149 (let ((question (cdr (assoc :question (get-post-body post-id :auth-token lw2-auth-token))))
1150 (new-comment-id
1151 (cond
1152 (text
1153 (let ((comment-data
1154 (list-cond
1155 (t :body (postprocess-markdown text))
1156 (t :last-edited-as "markdown")
1157 ((not edit-comment-id) :post-id post-id)
1158 (parent-comment-id :parent-comment-id parent-comment-id)
1159 (answer :answer t)
1160 (parent-answer-id :parent-answer-id parent-answer-id))))
1161 (if edit-comment-id
1162 (prog1 edit-comment-id
1163 (do-lw2-comment-edit lw2-auth-token edit-comment-id comment-data))
1164 (do-lw2-comment lw2-auth-token comment-data))))
1165 (retract-comment-id
1166 (do-lw2-comment-edit lw2-auth-token retract-comment-id '((:retracted . t))))
1167 (unretract-comment-id
1168 (do-lw2-comment-edit lw2-auth-token unretract-comment-id '((:retracted . nil))))
1169 (delete-comment-id
1170 (do-lw2-comment-edit lw2-auth-token delete-comment-id '((:deleted . t) (:deleted-public . t)
1171 (:deleted-reason . "Comment deleted by its author.")))
1172 nil))))
1173 (ignore-errors
1174 (get-post-comments post-id :force-revalidate t)
1175 (when question
1176 (get-post-answers post-id :force-revalidate t)))
1177 (when text
1178 (cache-put "comment-markdown-source" new-comment-id text)
1179 (redirect (generate-post-link (match-lw2-link (hunchentoot:request-uri*)) new-comment-id))))))))
1181 (defparameter *edit-post-template* (compile-template* "edit-post.html"))
1183 (define-page view-edit-post "/edit-post" (title url section post-id link-post)
1184 (request-method
1185 (:get ()
1186 (let* ((csrf-token (make-csrf-token))
1187 (post-body (if post-id (get-post-body post-id :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1188 (section (or section (loop for (sym . sec) in '((:draft . "drafts") (:meta . "meta") (:frontpage-date . "frontpage"))
1189 if (cdr (assoc sym post-body)) return sec
1190 finally (return "all")))))
1191 (emit-page (out-stream :title (if post-id "Edit Post" "New Post") :content-class "edit-post-page")
1192 (render-template* *edit-post-template* out-stream
1193 :csrf-token csrf-token
1194 :title (cdr (assoc :title post-body))
1195 :url (cdr (assoc :url post-body))
1196 :question (cdr (assoc :question post-body))
1197 :post-id post-id
1198 :section-list (loop for (name desc) in '(("all" "All") ("meta" "Meta") ("drafts" "Drafts"))
1199 collect (alist :name name :desc desc :selected (string= name section)))
1200 :markdown-source (or (and post-id (cache-get "post-markdown-source" post-id)) (cdr (assoc :html-body post-body)) "")))))
1201 (:post (text question)
1202 (let ((lw2-auth-token *current-auth-token*)
1203 (url (if (string= url "") nil url)))
1204 (assert lw2-auth-token)
1205 (let* ((post-data
1206 (list-cond
1207 (t :body (postprocess-markdown text))
1208 (t :title title)
1209 (t :last-edited-as "markdown")
1210 (link-post :url url)
1211 (t :meta (string= section "meta"))
1212 (t :draft (string= section "drafts"))
1213 ((not post-id) :question (and question t))))
1214 (post-unset (if link-post nil (alist :url t)))
1215 (new-post-data
1216 (if post-id
1217 (do-lw2-post-edit lw2-auth-token post-id post-data post-unset)
1218 (do-lw2-post lw2-auth-token post-data)))
1219 (new-post-id (cdr (assoc :--id new-post-data))))
1220 (assert new-post-id)
1221 (cache-put "post-markdown-source" new-post-id text)
1222 (ignore-errors (get-post-body post-id :force-revalidate t))
1223 (redirect (if (cdr (assoc :draft post-data))
1224 (concatenate 'string (generate-post-link new-post-data) "?need-auth=y")
1225 (generate-post-link new-post-data))))))))
1227 (hunchentoot:define-easy-handler (view-karma-vote :uri "/karma-vote") ((csrf-token :request-type :post) (target :request-type :post) (target-type :request-type :post) (vote-type :request-type :post))
1228 (with-error-page
1229 (check-csrf-token csrf-token)
1230 (let ((lw2-auth-token (hunchentoot:cookie-in "lw2-auth-token")))
1231 (multiple-value-bind (points vote-type) (do-lw2-vote lw2-auth-token target target-type vote-type)
1232 (json:encode-json-to-string (list (pretty-number points "point") vote-type))))))
1234 (hunchentoot:define-easy-handler (view-check-notifications :uri "/check-notifications") ()
1235 (with-error-page
1236 (if *current-auth-token*
1237 (let ((notifications-status (check-notifications (logged-in-userid) *current-auth-token*)))
1238 (json:encode-json-to-string notifications-status)))))
1240 (define-page view-recent-comments "/recentcomments" ((offset :type fixnum)
1241 (limit :type fixnum))
1242 (let ((want-total (not (or (typep *current-backend* 'backend-lw2) (typep *current-backend* 'backend-ea-forum))))) ; LW2/EAF can't handle total queries. TODO: handle this in backend.
1243 (multiple-value-bind (recent-comments total)
1244 (if (or offset limit (/= (user-pref :items-per-page) 20))
1245 (lw2-graphql-query (lw2-query-string :comment :list
1246 (remove nil (alist :view "postCommentsNew" :limit (or limit (user-pref :items-per-page)) :offset offset)
1247 :key #'cdr)
1248 (comments-index-fields)
1249 :with-total want-total))
1250 (get-recent-comments :with-total want-total))
1251 (view-items-index recent-comments :title "Recent comments" :pagination (pagination-nav-bars :offset (or offset 0) :with-next (not want-total) :total (if want-total total))))))
1253 (define-page view-user (:regex "^/users/(.*?)(?:$|\\?)|^/user" user-slug) (id
1254 (offset :type fixnum :default 0)
1255 (show :member '(:all :posts :comments :drafts :conversations :inbox) :default :all)
1256 (sort :member '(:top :new) :default :new))
1257 (let* ((auth-token (if (eq show :inbox) *current-auth-token*))
1258 (user-query-terms (cond
1259 (user-slug (alist :slug user-slug))
1260 (id (alist :document-id id))))
1261 (user-info
1262 (let ((ui (lw2-graphql-query (lw2-query-string :user :single user-query-terms `(:--id :slug :display-name :karma ,@(if (eq show :inbox) '(:last-notifications-check))))
1263 :auth-token auth-token)))
1264 (if (cdr (assoc :--id ui))
1266 (error (make-condition 'lw2-user-not-found-error)))))
1267 (user-id (cdr (assoc :--id user-info)))
1268 (own-user-page (logged-in-userid user-id))
1269 (comments-index-fields (remove :page-url (comments-index-fields))) ; page-url sometimes causes "Cannot read property '_id' of undefined" error
1270 (display-name (if user-slug (cdr (assoc :display-name user-info)) user-id))
1271 (show-text (if (not (eq show :all)) (string-capitalize show)))
1272 (title (format nil "~A~@['s ~A~]" display-name show-text))
1273 (sort-type (case sort (:top :score) (:new :date)))
1274 (comments-base-terms (ecase sort-type (:score (load-time-value (alist :view "postCommentsTop"))) (:date (load-time-value (alist :view "allRecentComments"))))))
1275 (multiple-value-bind (items total)
1276 (case show
1277 (:posts
1278 (get-user-posts user-id :offset offset :limit (+ 1 (user-pref :items-per-page)) :sort-type sort-type))
1279 (:comments
1280 (lw2-graphql-query (lw2-query-string :comment :list
1281 (nconc (alist :offset offset :limit (+ 1 (user-pref :items-per-page)) :user-id user-id)
1282 comments-base-terms)
1283 comments-index-fields)))
1284 (:drafts
1285 (get-user-posts user-id :drafts t :offset offset :limit (+ 1 (user-pref :items-per-page)) :auth-token (hunchentoot:cookie-in "lw2-auth-token")))
1286 (:conversations
1287 (let ((conversations
1288 (lw2-graphql-query (lw2-query-string :conversation :list
1289 (alist :view "userConversations" :limit (+ 1 (user-pref :items-per-page)) :offset offset :user-id user-id)
1290 '(:--id :created-at :title (:participants :display-name :slug) :----typename))
1291 :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1292 (lw2-graphql-query-map
1293 (lambda (c)
1294 (lw2-query-string* :message :total (alist :view "messagesConversation" :conversation-id (cdr (assoc :--id c))) nil))
1295 conversations
1296 :postprocess (lambda (c result)
1297 (acons :messages-total result c))
1298 :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1299 (:inbox
1300 (prog1
1301 (let ((notifications (get-notifications :user-id user-id :offset offset :auth-token (hunchentoot:cookie-in "lw2-auth-token")))
1302 (last-check (ignore-errors (local-time:parse-timestring (cdr (assoc :last-notifications-check user-info))))))
1303 (labels ((check-new (key obj)
1304 (if (ignore-errors (local-time:timestamp< last-check (local-time:parse-timestring (cdr (assoc key obj)))))
1305 (acons :highlight-new t obj)
1306 obj)))
1307 (lw2-graphql-query-map
1308 (lambda (n)
1309 (alexandria:switch ((cdr (assoc :document-type n)) :test #'string=)
1310 ("comment"
1311 (lw2-query-string* :comment :single
1312 (alist :document-id (cdr (assoc :document-id n)))
1313 (comments-index-fields)))
1314 ("post"
1315 (lw2-query-string* :post :single (alist :document-id (cdr (assoc :document-id n)))
1316 (posts-index-fields)))
1317 ("message"
1318 (lw2-query-string* :message :single (alist :document-id (cdr (assoc :document-id n)))
1319 *messages-index-fields*))
1321 (values n t))))
1322 notifications
1323 :postprocess (lambda (n result)
1324 (if result
1325 (check-new
1326 (alexandria:switch ((cdr (assoc :document-type n)) :test #'string=)
1327 ("comment" :posted-at)
1328 ("post" :posted-at)
1329 ("message" :created-at))
1330 result)
1332 :auth-token auth-token)))
1333 (do-user-edit
1334 (hunchentoot:cookie-in "lw2-auth-token")
1335 user-id
1336 (alist :last-notifications-check
1337 (local-time:format-timestring nil (local-time:now)
1338 :format lw2.graphql:+graphql-timestamp-format+
1339 :timezone local-time:+utc-zone+)))))
1341 (let ((user-posts (get-user-posts user-id :limit (+ 1 (user-pref :items-per-page) offset)))
1342 (user-comments (lw2-graphql-query (lw2-query-string :comment :list (nconc (alist :limit (+ 1 (user-pref :items-per-page) offset) :user-id user-id) comments-base-terms)
1343 comments-index-fields))))
1344 (concatenate 'list user-posts user-comments))))
1345 (let ((with-next (> (length items) (+ (if (eq show :all) offset 0) (user-pref :items-per-page))))
1346 (interleave (if (eq show :all) (comment-post-interleave items :limit (user-pref :items-per-page) :offset (if (eq show :all) offset nil) :sort-by sort-type) (firstn items (user-pref :items-per-page))))) ; this destructively sorts items
1347 (view-items-index interleave :title title
1348 :content-class (format nil "user-page~@[ ~A-user-page~]~:[~; own-user-page~]" show-text own-user-page)
1349 :current-uri (format nil "/users/~A" user-slug)
1350 :section :personal
1351 :pagination (pagination-nav-bars :offset offset :total total :with-next (if (not total) with-next))
1352 :need-auth (eq show :drafts) :section (if (eq show :drafts) "drafts" nil)
1353 :top-nav (lambda (out-stream)
1354 (page-toolbar-to-html out-stream
1355 :title title
1356 :rss (not (member show '(:drafts :conversations :inbox)))
1357 :new-post (if (eq show :drafts) "drafts" t)
1358 :new-conversation (if own-user-page t user-slug)
1359 :logout own-user-page)
1360 (format out-stream "<h1 class=\"page-main-heading\"~@[ ~A~]>~A</h1><div class=\"user-stats\">Karma: <span class=\"karma-total\">~A</span></div>"
1361 (if (not own-user-page)
1362 (if user-slug
1363 (format nil "data-anti-kibitzer-redirect=\"/user?id=~A\"" (cdr (assoc :--id user-info)))
1364 (format nil "data-kibitzer-redirect=\"/users/~A\"" (cdr (assoc :slug user-info)))))
1365 (encode-entities display-name)
1366 (if user-slug (pretty-number (or (cdr (assoc :karma user-info)) 0)) "##"))
1367 (sublevel-nav-to-html out-stream
1368 `(:all :posts :comments
1369 ,@(if own-user-page
1370 '(:drafts :conversations :inbox)))
1371 show
1372 :default :all)
1373 (when (member show '(:all :posts :comments))
1374 (sublevel-nav-to-html out-stream
1375 '(:new :top)
1376 sort
1377 :default :new
1378 :param-name "sort"
1379 :extra-class "sort"))))))))
1381 (defparameter *conversation-template* (compile-template* "conversation.html"))
1383 (define-page view-conversation "/conversation" (id to subject)
1384 (request-method
1385 (:get ()
1386 (cond
1387 ((and id to) (error "This is an invalid URL."))
1389 (multiple-value-bind (conversation messages)
1390 (get-conversation-messages id (hunchentoot:cookie-in "lw2-auth-token"))
1391 (view-items-index (nreverse messages) :content-class "conversation-page" :need-auth t :title (encode-entities (postprocess-conversation-title (cdr (assoc :title conversation))))
1392 :top-nav (lambda (out-stream) (render-template* *conversation-template* out-stream
1393 :conversation conversation :csrf-token (make-csrf-token))))))
1395 (emit-page (out-stream :title "New conversation" :content-class "conversation-page")
1396 (render-template* *conversation-template* out-stream
1397 :to to
1398 :csrf-token (make-csrf-token))))))
1399 (:post ((text :required t))
1400 (let* ((id (or id
1401 (let ((participant-ids (list (logged-in-userid) (cdar (lw2-graphql-query (lw2-query-string :user :single (alist :slug to) '(:--id)))))))
1402 (do-create-conversation (hunchentoot:cookie-in "lw2-auth-token") (alist :participant-ids participant-ids :title subject))))))
1403 (do-create-message (hunchentoot:cookie-in "lw2-auth-token") id text)
1404 (redirect (format nil "/conversation?id=~A" id))))))
1406 (defun search-result-markdown-to-html (item)
1407 (cons (cons :html-body
1408 (handler-case (markdown:parse (cdr (assoc :body item)))
1409 (serious-condition () "[Error while processing search result]")))
1410 item))
1412 (define-page view-search "/search" ((q :required t))
1413 (let ((*current-search-query* q)
1414 (link (convert-any-link* q)))
1415 (declare (special *current-search-query*))
1416 (if link
1417 (redirect link)
1418 (multiple-value-bind (posts comments) (lw2-search-query q)
1419 (view-items-index (nconc (map 'list (lambda (p) (if (cdr (assoc :comment-count p)) p (cons (cons :comment-count 0) p))) posts)
1420 (map 'list #'search-result-markdown-to-html comments))
1421 :content-class "search-results-page" :current-uri "/search"
1422 :title (format nil "~@[~A - ~]Search" q))))))
1424 (define-page view-login "/login" (return cookie-check
1425 (csrf-token :request-type :post) (login-username :request-type :post) (login-password :request-type :post)
1426 (signup-username :request-type :post) (signup-email :request-type :post) (signup-password :request-type :post) (signup-password2 :request-type :post))
1427 (labels
1428 ((emit-login-page (&key error-message)
1429 (let ((csrf-token (make-csrf-token)))
1430 (emit-page (out-stream :title "Log in" :current-uri "/login" :content-class "login-page" :robots "noindex, nofollow")
1431 (when error-message
1432 (format out-stream "<div class=\"error-box\">~A</div>" error-message))
1433 (with-outputs (out-stream) "<div class=\"login-container\">")
1434 (output-form out-stream "post" (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))) "login-form" "Log in" csrf-token
1435 '(("login-username" "Username" "text" "username")
1436 ("login-password" "Password" "password" "current-password"))
1437 "Log in"
1438 :end-html "<a href=\"/reset-password\">Forgot password</a>")
1439 (output-form out-stream "post" (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))) "signup-form" "Create account" csrf-token
1440 '(("signup-username" "Username" "text" "username")
1441 ("signup-email" "Email" "text" "email")
1442 ("signup-password" "Password" "password" "new-password")
1443 ("signup-password2" "Confirm password" "password" "new-password"))
1444 "Create account")
1445 (alexandria:if-let (main-site-title (main-site-title *current-site*))
1446 (format out-stream "<div class=\"login-tip\"><span>Tip:</span> You can log in with the same username and password that you use on ~A~:*. Creating an account here also creates one on ~A.</div>"
1447 main-site-title))
1448 (format out-stream "</div>"))))
1449 (finish-login (username user-id auth-token error-message &optional expires)
1450 (cond
1451 (auth-token
1452 (set-cookie "lw2-auth-token" auth-token :max-age (and expires (+ (- expires (get-unix-time)) (* 24 60 60))))
1453 (if expires (set-cookie "lw2-status" (json:encode-json-to-string (alist :expires expires))))
1454 (cache-put "auth-token-to-userid" auth-token user-id)
1455 (cache-put "auth-token-to-username" auth-token username)
1456 (redirect (if (and return (ppcre:scan "^/[^/]" return)) return "/")))
1458 (emit-login-page :error-message error-message)))))
1459 (cond
1460 ((not (or cookie-check (hunchentoot:cookie-in "session-token")))
1461 (set-cookie "session-token" (base64:usb8-array-to-base64-string (ironclad:make-random-salt)))
1462 (redirect (format nil "/login?~@[return=~A&~]cookie-check=y" (if return (url-rewrite:url-encode return)))))
1463 (cookie-check
1464 (if (hunchentoot:cookie-in "session-token")
1465 (redirect (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))))
1466 (emit-page (out-stream :title "Log in" :current-uri "/login")
1467 (format out-stream "<h1>Enable cookies</h1><p>Please enable cookies in your browser and <a href=\"/login~@[?return=~A~]\">try again</a>.</p>" (if return (url-rewrite:url-encode return))))))
1468 (login-username
1469 (check-csrf-token csrf-token)
1470 (cond
1471 ((or (string= login-username "") (string= login-password "")) (emit-login-page :error-message "Please enter a username and password"))
1472 (t (multiple-value-call #'finish-login login-username (do-login "username" login-username login-password)))))
1473 (signup-username
1474 (check-csrf-token csrf-token)
1475 (cond
1476 ((not (every (lambda (x) (not (string= x ""))) (list signup-username signup-email signup-password signup-password2)))
1477 (emit-login-page :error-message "Please fill in all fields"))
1478 ((not (string= signup-password signup-password2))
1479 (emit-login-page :error-message "Passwords do not match"))
1480 (t (multiple-value-call #'finish-login signup-username (do-lw2-create-user signup-username signup-email signup-password)))))
1482 (emit-login-page)))))
1484 (define-page view-logout "/logout" ((logout :request-type :post))
1485 (check-csrf-token logout)
1486 (set-cookie "lw2-auth-token" "" :max-age 0)
1487 (redirect "/"))
1489 (defparameter *reset-password-template* (compile-template* "reset-password.html"))
1491 (define-page view-reset-password "/reset-password" ((csrf-token :request-type :post) (email :request-type :post) (reset-link :request-type :post) (password :request-type :post) (password2 :request-type :post))
1492 (labels ((emit-rpw-page (&key message message-type step)
1493 (let ((csrf-token (make-csrf-token)))
1494 (emit-page (out-stream :title "Reset password" :content-class "reset-password" :robots "noindex, nofollow")
1495 (render-template* *reset-password-template* out-stream
1496 :csrf-token csrf-token
1497 :reset-link reset-link
1498 :message message
1499 :message-type message-type
1500 :step step)))))
1501 (cond
1502 (email
1503 (check-csrf-token csrf-token)
1504 (multiple-value-bind (ret error)
1505 (do-lw2-forgot-password email)
1506 (declare (ignore ret))
1507 (if error
1508 (emit-rpw-page :step 1 :message error :message-type "error")
1509 (emit-rpw-page :step 1 :message "Password reset email sent." :message-type "success"))))
1510 (reset-link
1511 (ppcre:register-groups-bind (reset-token) ("(?:reset-password/|^)([^/#]+)$" reset-link)
1512 (cond
1513 ((not reset-token)
1514 (emit-rpw-page :step 2 :message "Invalid password reset link." :message-type "error"))
1515 ((not (string= password password2))
1516 (emit-rpw-page :step 2 :message "Passwords do not match." :message-type "error"))
1518 (check-csrf-token csrf-token)
1519 (multiple-value-bind (user-id auth-token error-message) (do-lw2-reset-password reset-token password)
1520 (declare (ignore user-id auth-token))
1521 (cond
1522 (error-message (emit-rpw-page :step 2 :message error-message :message-type "error"))
1524 (with-error-page (emit-page (out-stream :title "Reset password" :content-class "reset-password")
1525 (format out-stream "<h1>Password reset complete</h1><p>You can now <a href=\"/login\">log in</a> with your new password.</p>"))))))))))
1527 (emit-rpw-page)))))
1529 (defun firstn (list n)
1530 (loop for x in list
1531 for i from 1 to n
1532 collect x))
1534 (defparameter *earliest-post* (local-time:parse-timestring "2005-01-01"))
1536 (define-page view-archive (:regex "^/archive(?:/(\\d{4})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))"
1537 (year :type (mod 10000))
1538 (month :type (integer 1 12))
1539 (day :type (integer 1 31)))
1540 ((offset :type fixnum :default 0))
1541 (local-time:with-decoded-timestamp (:day current-day :month current-month :year current-year) (local-time:now)
1542 (local-time:with-decoded-timestamp (:day earliest-day :month earliest-month :year earliest-year) *earliest-post*
1543 (labels ((url-elements (&rest url-elements)
1544 (declare (dynamic-extent url-elements))
1545 (format nil "/~{~A~^/~}" url-elements))
1546 (archive-nav (out-stream)
1547 (with-outputs (out-stream) "<div class=\"archive-nav\"><div class=\"archive-nav-years\">")
1548 (link-if-not out-stream (not (or year month day)) (url-elements "archive") "archive-nav-item-year" "All")
1549 (loop for y from earliest-year to current-year
1550 do (link-if-not out-stream (eq y year) (url-elements "archive" y) "archive-nav-item-year" y))
1551 (format out-stream "</div>")
1552 (when year
1553 (format out-stream "<div class=\"archive-nav-months\">")
1554 (link-if-not out-stream (not month) (url-elements "archive" year) "archive-nav-item-month" "All")
1555 (loop for m from (if (= (or year current-year) earliest-year) earliest-month 1) to (if (= (or year current-year) current-year) current-month 12)
1556 do (link-if-not out-stream (eq m month) (url-elements "archive" (or year current-year) m) "archive-nav-item-month" (elt local-time:+short-month-names+ m)))
1557 (format out-stream "</div>"))
1558 (when month
1559 (format out-stream "<div class=\"archive-nav-days\">")
1560 (link-if-not out-stream (not day) (url-elements "archive" year month) "archive-nav-item-day" "All")
1561 (loop for d from (if (and (= (or year current-year) earliest-year) (= (or month current-month) earliest-month)) earliest-day 1)
1562 to (if (and (= (or year current-year) current-year) (= (or month current-month) current-month)) current-day (local-time:days-in-month (or month current-month) (or year current-year)))
1563 do (link-if-not out-stream (eq d day) (url-elements "archive" (or year current-year) (or month current-month) d) "archive-nav-item-day" d))
1564 (format out-stream "</div>"))
1565 (format out-stream "</div>")))
1566 (multiple-value-bind (posts total)
1567 (lw2-graphql-query (lw2-query-string :post :list
1568 (alist :view (if day "new" "top") :limit 51 :offset offset
1569 :after (if (and year (not day)) (format nil "~A-~A-~A" (or year earliest-year) (or month 1) (or day 1)))
1570 :before (if year (format nil "~A-~A-~A" (or year current-year) (or month 12)
1571 (or day (local-time:days-in-month (or month 12) (or year current-year))))))
1572 (posts-index-fields)))
1573 (emit-page (out-stream :title "Archive" :current-uri "/archive" :content-class "archive-page"
1574 :top-nav #'archive-nav
1575 :pagination (pagination-nav-bars :items-per-page 50 :offset offset :total total :with-next (if total nil (> (length posts) 50))))
1576 (write-index-items-to-html out-stream (firstn posts 50) :empty-message "No posts for the selected period.")))))))
1578 (define-page view-about "/about" ()
1579 (emit-page (out-stream :title "About" :current-uri "/about" :content-class "about-page")
1580 (alexandria:with-input-from-file (in-stream "www/about.html" :element-type '(unsigned-byte 8))
1581 (alexandria:copy-stream in-stream out-stream))))
1583 (hunchentoot:define-easy-handler (view-versioned-resource :uri (lambda (r)
1584 (multiple-value-bind (file content-type)
1585 #.(labels ((defres (uri content-type)
1586 `(,uri (values (concatenate 'string "www" ,uri) ,content-type))))
1587 (concatenate 'list
1588 '(alexandria:switch ((hunchentoot:script-name r) :test #'string=))
1589 (loop for system in '("mac" "windows" "linux") nconc
1590 (loop for theme in '(nil "dark" "grey" "ultramodern" "zero" "brutalist" "rts")
1591 collect (defres (format nil "/css/style~@[-~A~].~A.css" theme system) "text/css")))
1592 (loop for (uri content-type) in
1593 '(("/script.js" "text/javascript")
1594 ("/assets/favicon.ico" "image/x-icon"))
1595 collect (defres uri content-type))))
1596 (when file
1597 (when (assoc "v" (hunchentoot:get-parameters r) :test #'string=)
1598 (setf (hunchentoot:header-out "Cache-Control") (format nil "public, max-age=~A, immutable" (- (expt 2 31) 1))))
1599 (hunchentoot:handle-static-file file content-type)
1600 t))))
1601 nil)