1 (uiop:define-package
#:lw2-viewer
2 (:use
#:cl
#:sb-thread
#:flexi-streams
#:djula
#:iterate
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
#:lw2.fonts
13 #:lw2.data-viewers.post
14 #:lw2.data-viewers.comment
17 (:import-from
#:alexandria
#:with-gensyms
#:once-only
#:ensure-list
#:when-let
#:when-let
* #:if-let
#:alist-hash-table
)
18 (:import-from
#:collectors
#:with-collector
)
19 (:import-from
#:ppcre
#:regex-replace-all
)
21 #:define-regex-handler
#:*fonts-stylesheet-uri
* #:generate-fonts-link
22 #:user-nav-bar
#:*primary-nav
* #:*secondary-nav
* #:*nav-bars
*
23 #:begin-html
#:end-html
24 #:*fonts-stylesheet-uris
* #:*fonts-redirect-data
* #:*fonts-redirect-lock
* #:*fonts-redirect-thread
*
25 #:postprocess-conversation-title
28 #:*extra-external-scripts
* #:*extra-inline-scripts
*
29 #:site-stylesheets
#:site-inline-scripts
#:site-scripts
#:site-external-scripts
#:site-head-elements
34 (:recycle
#:lw2-viewer
#:lw2.backend
))
36 (in-package #:lw2-viewer
)
38 (named-readtables:in-readtable html-reader
)
40 (add-template-directory (asdf:system-relative-pathname
"lw2-viewer" "templates/"))
42 (define-cache-database 'backend-lw2-legacy
43 "auth-token-to-userid" "auth-token-to-username" "user-ignore-list")
45 (defvar *read-only-mode
* nil
)
46 (defvar *read-only-default-message
* "Due to a system outage, you cannot log in or post at this time.")
48 (defparameter *default-prefs
* (alist :items-per-page
20 :default-sort
"new"))
49 (defvar *current-prefs
* nil
)
51 (defun get-post-sequences (post-id)
52 (when-let (sequence-ids (get-post-sequence-ids post-id
))
54 (dolist (sequence-id sequence-ids
)
55 (let* ((sequence (get-sequence sequence-id
))
56 (posts (sequence-post-ids sequence
)))
57 (multiple-value-bind (prev next
)
58 (loop for prev
= nil then
(car current
)
60 when
(string= (car current
) post-id
)
61 return
(values prev
(second current
)))
64 (and prev
(get-sequence-post sequence prev
))
65 (and next
(get-sequence-post sequence next
))))))))
68 (defun rectify-post-relations (post-relations)
69 (remove-if-not (lambda (pr) (cdr (assoc :--id
(cdr (first pr
))))) post-relations
))
71 (defun post-nav-links (post post-sequences
)
72 <nav class
="post-nav-links">
73 (schema-bind (:post post
(target-post-relations source-post-relations
) :context
:body
)
74 (let ((target-post-relations (rectify-post-relations target-post-relations
))
75 (source-post-relations (rectify-post-relations source-post-relations
)))
76 (when (or target-post-relations source-post-relations
)
77 <div class
="related-posts">
78 (dolist (relations `((,source-post-relations
"Parent question")
79 (,target-post-relations
"Sub-question")))
80 (destructuring-bind (related-posts relation-type
) relations
82 <div class
="related-post-group">
83 <div class
="related-post-type">("~A~A" relation-type
(if (second related-posts
) "s" ""))</div
>
84 (dolist (post-relation related-posts
)
85 (post-headline-to-html (or (cdr (assoc :source-post post-relation
))
86 (cdr (assoc :target-post post-relation
)))))
89 (loop for
(sequence prev next
) in post-sequences do
91 <div class
="post-nav-item sequence">
92 <a class
="post-nav sequence-title" href
=("/s/~A" (cdr (assoc :--id sequence
)))>
93 <span class
="post-nav-label">Part of the sequence
:</span
>
94 <span class
="post-nav-title">(safe (clean-text-to-html (cdr (assoc :title sequence
))))</span
>
96 (labels ((post-nav-link (direction post
)
97 <a class
=("post-nav ~A" (string-downcase direction
)) href
=(generate-item-link :post post
)>
98 <span class
="post-nav-label">(case direction
(:prev
"Previous: ") (:next
"Next: "))</span
>
99 <span class
="post-nav-title">(safe (clean-text-to-html (cdr (assoc :title post
))))</span
>
101 (when prev
(post-nav-link :prev prev
))
102 (when next
(post-nav-link :next next
)))
106 (defun rectify-conversation (conversation)
107 (alist-bind ((title (or null string
)))
109 (if (or (null title
) (string= title
""))
110 (acons :title
"[Untitled conversation]" conversation
)
113 (defun conversation-message-to-html (out-stream message
)
114 (alist-bind ((user-id string
)
116 (highlight-new boolean
)
120 (html-body (or string null
)))
122 (let ((conversation (rectify-conversation conversation
)))
123 (multiple-value-bind (pretty-time js-time
) (pretty-time created-at
)
124 (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~A</span><div class=\"comment-post-title\">Private message in: <a href=\"/conversation?id=~A\">~A</a></div></div><div class=\"body-text comment-body\">"
125 (if highlight-new
" comment-item-highlight" "")
126 (encode-entities (get-user-slug user-id
))
127 (encode-entities (get-username user-id
))
131 (encode-entities (cdr (assoc :--id conversation
)))
132 (encode-entities (cdr (assoc :title conversation
)))))
133 (labels ((ws (html-body) (let ((*memoized-output-stream
* out-stream
)) (clean-html* html-body
))))
135 (contents (ws (cdr (assoc :html contents
))))
136 (html-body (ws html-body
))
137 (t (format out-stream
"~{<p>~A</p>~}" (loop for block in
(cdr (assoc :blocks content
)) collect
(encode-entities (cdr (assoc :text block
))))))))
138 (format out-stream
"</div></div>"))))
140 (defun conversation-index-to-html (out-stream conversation
)
141 (alist-bind ((conversation-id string
:--id
)
142 (title (or null string
))
143 (created-at (or null string
))
145 (messages-total fixnum
))
146 (rectify-conversation conversation
)
147 (multiple-value-bind (pretty-time js-time
) (if created-at
(pretty-time created-at
) (values "[Error]" 0))
148 (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~A</div></div>"
149 (encode-entities conversation-id
)
150 (encode-entities title
)
151 (loop for p in participants
152 collect
(list (encode-entities (cdr (assoc :slug p
))) (encode-entities (cdr (assoc :display-name p
)))))
153 (pretty-number messages-total
"message")
158 (defun collection-to-contents (collection &optional
(heading-level 1) (used-anchors (make-hash-table :test
'equal
)))
159 (alist-bind ((title (or string null
)))
161 (let ((subcollections (cdr
162 (find-if (lambda (x) (member (car x
) '(:books
:sequences
:chapters
) :test
#'eq
))
164 contents-head contents-tail
)
165 (labels ((add-contents (c)
168 (setf (cdr contents-tail
) c
)
169 (setf contents-head c
))
170 (setf contents-tail
(last c
)))))
172 ((and title
(not (cdr (assoc :books collection
))))
173 (add-contents (list (list heading-level title
(title-to-anchor title used-anchors
))))
174 (dolist (subcollection subcollections
)
175 (add-contents (collection-to-contents subcollection
(1+ heading-level
) used-anchors
))))
177 (dolist (subcollection subcollections
)
178 (add-contents (collection-to-contents subcollection heading-level used-anchors
)))))
181 (defun collection-to-html (collection &optional
(heading-level 1) (used-anchors (make-hash-table :test
'equal
)))
182 (alist-bind ((title (or string null
))
183 (subtitle (or string null
))
184 (number (or fixnum null
))
188 (let* ((subcollections (cdr
189 (find-if (lambda (x) (member (car x
) '(:books
:sequences
:chapters
) :test
#'eq
))
191 (html-body (cdr (assoc :html contents
))))
193 ((or html-body title posts
)
195 (when (or html-body title
)
196 <div class
="body-text sequence-text">
198 (with-html-stream-output (:stream stream
)
199 (format stream
"<h~A id=\"~A\" class=\"sequence-chapter\">~@[~A. ~]~A</h~A>"
201 (title-to-anchor title used-anchors
)
203 (clean-text-to-html title
)
205 (when (assoc :books collection
)
206 (contents-to-html (collection-to-contents collection
) 1 *html-output
*))
208 <div class
="sequence-subtitle">(safe (clean-text-to-html subtitle
))</div
>)
210 (with-html-stream-output (:stream stream
)
211 (let ((*memoized-output-stream
* stream
)) (clean-html* html-body
))))
215 (post-headline-to-html post
))
216 (dolist (subcollection subcollections
)
217 (collection-to-html subcollection
(1+ heading-level
) used-anchors
)))
220 (dolist (subcollection subcollections
)
221 (collection-to-html subcollection heading-level used-anchors
)))))))
223 (defun sequence-to-html (sequence)
224 (labels ((contents-to-html (contents &key title subtitle number
)
225 (let ((html-body (cdr (assoc :html contents
))))
226 (when (or html-body title subtitle
)
227 <div class
="body-text sequence-text">
229 <h1 class
="sequence-chapter">(safe (format nil
"~@[~A. ~]~A" number
(clean-text-to-html title
:hyphenation nil
)))</h1
>)
231 <div class
="sequence-subtitle">(clean-text-to-html subtitle
)</div
>)
232 (with-html-stream-output (:stream stream
)
234 (let ((*memoized-output-stream
* stream
)) (clean-html* html-body
))))
236 (chapter-to-html (chapter)
237 (alist-bind ((title (or string null
))
238 (subtitle (or string null
))
239 (number (or fixnum null
))
244 (with-html-stream-output
245 (contents-to-html contents
:title title
:subtitle subtitle
:number number
)
247 (with-html-stream-output
249 (post-headline-to-html post
)))
252 (alist-bind ((sequence-id string
:--id
)
259 (multiple-value-bind (pretty-time js-time
) (pretty-time created-at
)
262 <h1 class
="post-title">(safe (clean-text-to-html title
:hyphenation nil
))</h1
>
263 <h1 class
="listing"><a href
=("/s/~A" sequence-id
)>(safe (clean-text-to-html title
:hyphenation nil
))</a
></h1
>)
264 <div class
="post-meta">
265 <a class
=("author~{ ~A~}" (list-cond ((logged-in-userid user-id
) "own-user-author")))
266 href
=("/users/~A" (get-user-slug user-id
))
268 (get-username user-id
)
270 <div class
="date" data-js-date
=js-time
>
272 (safe (pretty-time-js))
275 (with-html-stream-output
277 (contents-to-html contents
)
278 (dolist (chapter chapters
)
279 (chapter-to-html chapter
))))
282 (defun abort-response ()
283 (throw 'abort-response nil
))
285 (defun abort-response-if-unrecoverable (condition)
286 (when (html-output-stream-error-p condition
)
289 (defmacro with-error-html-block
(() &body body
)
290 "If an error occurs within BODY, write an HTML representation of the
291 signaled condition to *HTML-OUTPUT*."
292 `(block with-error-html-block
293 (handler-bind ((serious-condition (lambda (c)
294 (abort-response-if-unrecoverable c
)
296 (return-from with-error-html-block nil
))))
297 (log-conditions (progn ,@body
)))))
299 (defun make-comment-parent-hash-real (comments)
300 (let ((existing-comment-hash (make-hash-table :test
'equal
))
301 (hash (make-hash-table :test
'equal
)))
303 (if-let (id (cdr (assoc :--id c
)))
304 (setf (gethash id existing-comment-hash
) t
)))
306 (let* ((parent-id (cdr (assoc :parent-comment-id c
)))
307 (old (gethash parent-id hash
)))
308 (setf (gethash parent-id hash
) (cons c old
))
309 (when (and parent-id
(not (gethash parent-id existing-comment-hash
)))
310 (let ((placeholder (alist :--id parent-id
:parent-comment-id nil
:deleted t
)))
311 (setf (gethash parent-id existing-comment-hash
) t
312 (gethash nil hash
) (cons placeholder
(gethash nil hash
)))))))
313 (maphash (lambda (k old
)
314 (setf (gethash k hash
) (nreverse old
)))
317 ((count-children (parent)
318 (let ((children (gethash (cdr (assoc :--id parent
)) hash
)))
319 (+ (length children
) (apply #'+ (map 'list
#'count-children children
)))))
320 (add-child-counts (comment-list)
321 (loop for c in comment-list
322 as id
= (cdr (assoc :--id c
))
323 do
(setf (gethash id hash
) (add-child-counts (gethash id hash
)))
324 collecting
(cons (cons :child-count
(count-children c
)) c
))))
325 (setf (gethash nil hash
) (add-child-counts (gethash nil hash
))))
328 (defparameter *comment-parent-hash-cache
* (make-hash-table :test
'eq
332 (defun make-comment-parent-hash (comments)
333 (or (gethash comments
*comment-parent-hash-cache
*)
334 (setf (gethash comments
*comment-parent-hash-cache
*) (make-comment-parent-hash-real comments
))))
336 (defun comment-thread-to-html (out-stream emit-comment-item-fn
)
337 (format out-stream
"<ul class=\"comment-thread\">")
338 (funcall emit-comment-item-fn
)
339 (format out-stream
"</ul>"))
341 (defun comment-item-to-html (out-stream comment
&key extra-html-fn with-post-title level level-invert
)
342 (with-error-html-block ()
343 (let ((c-id (cdr (assoc :--id comment
)))
344 (user-id (cdr (assoc :user-id comment
))))
345 (format out-stream
"<li id=\"comment-~A\" class=\"comment-item~{ ~A~}\">"
348 (t (if (let ((is-odd (or (not level
) (evenp level
)))) ;inverted because level counts from 0
349 (if level-invert
(not is-odd
) is-odd
))
350 "depth-odd" "depth-even"))
351 ((and *current-ignore-hash
* (gethash user-id
*current-ignore-hash
*)) "ignored")))
353 (comment-to-html out-stream comment
:with-post-title with-post-title
)
354 (if extra-html-fn
(funcall extra-html-fn c-id
))
355 (format out-stream
"</li>")))))
357 (defun comment-tree-to-html (out-stream comment-hash
&key
(target nil
) (level (if target
1 0)) level-invert
)
358 (let ((comments (gethash target comment-hash
)))
360 (comment-thread-to-html out-stream
362 (loop for c in comments do
363 (comment-item-to-html out-stream c
365 :level-invert level-invert
366 :extra-html-fn
(lambda (c-id)
367 (if (and (= level
10) (gethash c-id comment-hash
))
368 (format out-stream
"<input type=\"checkbox\" id=\"expand-~A\"><label for=\"expand-~:*~A\" data-child-count=\"~A comment~:P\">Expand this thread</label>"
370 (cdr (assoc :child-count c
))))
371 (comment-tree-to-html out-stream comment-hash
:target c-id
:level
(1+ level
) :level-invert level-invert
)))))))))
373 (defun sort-items (items sort-by
)
374 (multiple-value-bind (sort-fn key-fn
)
376 ((:old
:new
) (values (if (eq sort-by
:old
)
377 (lambda (a b
) (ignore-errors (local-time:timestamp
< a b
)))
378 (lambda (a b
) (ignore-errors (local-time:timestamp
> a b
))))
379 (lambda (c) (ignore-errors (local-time:parse-timestring
(or (cdr (assoc :posted-at c
))
380 (cdr (assoc :created-at c
)))))))))
381 (sort items sort-fn
:key key-fn
)))
383 (defun comment-chrono-to-html (out-stream comments
)
384 (let ((comment-hash (make-comment-parent-hash comments
))
385 (comments (sort-items comments
:old
)))
386 (comment-thread-to-html out-stream
388 (loop for c in comments do
389 (let* ((c-id (cdr (assoc :--id c
)))
390 (new-c (acons :children
(gethash c-id comment-hash
) c
)))
391 (comment-item-to-html out-stream new-c
)))))))
393 (defun comment-post-interleave (list &key limit offset
(sort-by :date
))
394 (multiple-value-bind (sort-fn sort-key
)
396 (:date
(values #'local-time
:timestamp
> (lambda (x) (local-time:parse-timestring
(cdr (assoc :posted-at x
))))))
397 (:date-reverse
(values #'local-time
:timestamp
< (lambda (x) (local-time:parse-timestring
(cdr (assoc :posted-at x
))))))
398 (:score
(values #'> (lambda (x) (cdr (assoc :base-score x
))))))
399 (let ((sorted (sort list sort-fn
:key sort-key
)))
400 (loop for end
= (if (or limit offset
) (+ (or limit
0) (or offset
0)))
403 until
(and end
(>= count end
))
404 when
(or (not offset
) (>= count offset
))
407 (defun identify-item (x)
410 (if-let (typename (cdr (assoc :----typename x
)))
411 (find-symbol (string-upcase typename
) (find-package :keyword
))
415 ((assoc :comment-count x
)
419 (condition :condition
)))
421 (defun write-index-items-to-html (out-stream items
&key need-auth
(empty-message "No entries.") skip-section
)
424 (with-error-html-block ()
425 (ecase (identify-item x
)
429 (format out-stream
"<p>~A</p>" (cdr (assoc :message x
))))
431 (format out-stream
"<ul class=\"comment-thread\"><li class=\"comment-item depth-odd\">")
433 (conversation-message-to-html out-stream x
)
434 (format out-stream
"</li></ul>")))
436 (conversation-index-to-html out-stream x
))
438 (post-headline-to-html x
:need-auth
(or need-auth
(cdr (assoc :draft x
))) :skip-section skip-section
))
440 (comment-thread-to-html out-stream
441 (lambda () (comment-item-to-html out-stream x
:with-post-title t
))))
443 (sequence-to-html x
)))))
444 (format out-stream
"<div class=\"listing-message\">~A</div>" empty-message
)))
446 (defun write-index-items-to-rss (out-stream items
&key title need-auth
)
447 (let ((full-title (format nil
"~@[~A - ~]~A" title
(site-title *current-site
*)))
448 (items (firstn (sort-items items
:new
) 20)))
449 (xml-emitter:with-rss2
(out-stream :encoding
"UTF-8")
450 (xml-emitter:rss-channel-header full-title
(site-uri *current-site
*) :description full-title
)
451 (labels ((emit-item (item &key title link
(guid (cdr (assoc :--id item
))) (author (get-username (cdr (assoc :user-id item
))))
452 (date (pretty-time (cdr (assoc :posted-at item
)) :format local-time
:+rfc-1123-format
+)) body
)
453 (xml-emitter:rss-item
461 (ecase (identify-item item
)
463 (let ((author (get-username (cdr (assoc :user-id item
))))
464 (is-event (cdr (assoc :is-event item
))))
466 :title
(clean-text (format nil
"~A by ~A" (cdr (assoc :title item
)) author
))
468 :link
(generate-post-auth-link item
:absolute t
:need-auth need-auth
:item-subtype
(if is-event
"event" "post"))
469 :body
(clean-html (or (cdr (assoc :html-body
(get-post-body (cdr (assoc :--id item
)) :revalidate nil
))) "") :post-id
(cdr (assoc :--id item
))))))
471 (schema-bind (:comment item
(comment-id post-id user-id html-body
))
472 (when post-id
; XXX fixme
474 :title
(format nil
"Comment by ~A on ~A" (get-username user-id
) (get-post-title post-id
))
475 :link
(generate-item-link :post post-id
:comment-id comment-id
:absolute t
)
476 :body
(clean-html html-body
)))))))))))
478 (defun search-bar-to-html (out-stream)
479 (declare (special *current-search-query
*))
480 (let ((query (and (boundp '*current-search-query
*) (hunchentoot:escape-for-html
*current-search-query
*))))
481 (format out-stream
"<form action=\"/search\" class=\"nav-inner\"><input name=\"q\" type=\"search\" ~@[value=\"~A\"~] autocomplete=\"off\" accesskey=\"s\" title=\"Search [s]~@[ Tip: Paste a ~A URL here to jump to that page.~]\"><button>Search</button></form>" query
(main-site-title *current-site
*))))
483 (defun inbox-to-html (out-stream user-slug
&optional new-messages
)
484 (let* ((target-uri (format nil
"/users/~A?show=inbox" user-slug
))
485 (as-link (string= (hunchentoot:request-uri
*) target-uri
)))
486 (multiple-value-bind (nm-class nm-text
)
487 (if new-messages
(values "new-messages" "New messages") (values "no-messages" "Inbox"))
488 (format out-stream
"<~:[a href=\"~A\"~;span~*~] id=\"inbox-indicator\" class=\"~A\" accesskey=\"o\" title=\"~A~:[ [o]~;~]\">~A</a>"
489 as-link target-uri nm-class nm-text as-link nm-text
))))
491 (defmethod site-nav-bars ((site site
))
492 '((:secondary-bar
(("archive" "/archive" "Archive" :accesskey
"r")
493 ("about" "/about" "About" :accesskey
"t")
494 ("search" "/search" "Search" :html search-bar-to-html
)
496 (:primary-bar
(("home" "/" "Home" :description
"Latest frontpage posts" :accesskey
"h")
497 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description
"Latest comments" :accesskey
"c")))))
499 (defmethod site-nav-bars ((site lesswrong-viewer-site
))
500 '((:secondary-bar
(("archive" "/archive" "Archive" :accesskey
"r")
501 ("sequences" "/library" "Sequences" :description
"Sequences" :accesskey
"q")
502 ("about" "/about" "About" :accesskey
"t")
503 ("search" "/search" "Search" :html search-bar-to-html
)
505 (:tertiary-bar
(("questions" "/index?view=questions" "Questions")
506 ("events" "/index?view=events" "Events")
507 ("shortform" "/shortform" "Shortform" :description
"Latest Shortform posts")
508 ("alignment-forum" "/index?view=alignment-forum" "Alignment Forum")
509 ("alignment-forum-comments" "/recentcomments?view=alignment-forum" "AF Comments")))
510 (:primary-bar
(("home" "/" "Home" :description
"Latest frontpage posts" :accesskey
"h")
511 ("featured" "/index?view=featured" "Featured" :description
"Latest featured posts" :accesskey
"f")
512 ("all" "/index?view=all" "All" :description
"Latest posts from all sections" :accesskey
"a")
513 ("tags" "/tags" "Tags" :description
"All tags" :accesskey
"v")
514 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description
"Latest comments" :accesskey
"c")))))
516 (defmethod site-nav-bars ((site ea-forum-viewer-site
))
517 '((:secondary-bar
(("archive" "/archive" "Archive" :accesskey
"r")
518 ("about" "/about" "About" :accesskey
"t")
519 ("search" "/search" "Search" :html search-bar-to-html
)
521 (:primary-bar
(("home" "/" "Home" :description
"Latest frontpage posts" :accesskey
"h")
522 ("all" "/index?view=all" "All" :description
"Latest posts from all sections" :accesskey
"a")
523 ("tags" "/tags" "Wiki" :description
"Wiki pages and tags" :accesskey
"v")
524 ("shortform" "/shortform" "Shortform" :description
"Latest Shortform posts")
525 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description
"Latest comments" :accesskey
"c")))))
527 (defun prepare-nav-bar (nav-bar current-uri
)
528 (list (first nav-bar
)
529 (map 'list
(lambda (item) (if (listp item
) item
(funcall item current-uri
)))
532 (defun nav-item-active (item current-uri
)
534 (destructuring-bind (id uri name
&key description html accesskey nofollow trailing-html override-uri
) item
535 (declare (ignore id name description html accesskey nofollow trailing-html
))
536 (string= (or override-uri uri
) current-uri
))))
538 (defun nav-bar-active (nav-bar current-uri
)
539 (some (lambda (x) (nav-item-active x current-uri
)) (second nav-bar
)))
541 (defun nav-bar-inner (out-stream items
&optional current-uri
)
542 (maplist (lambda (items)
543 (let ((item (first items
)))
544 (destructuring-bind (id uri name
&key description html accesskey nofollow trailing-html override-uri
) item
545 (declare (ignore override-uri
))
546 (let* ((item-active (nav-item-active item current-uri
))
547 (nav-class (format nil
"nav-item ~:[nav-inactive~;nav-current~]~:[~; nav-item-last-before-current~]"
548 item-active
(and (not item-active
) (nav-item-active (cadr items
) current-uri
)))))
549 (format out-stream
"<span id=\"nav-item-~A\" class=\"~A\" ~@[title=\"~A\"~]>"
550 id nav-class description
)
552 (funcall html out-stream
)
553 (link-if-not out-stream item-active uri
"nav-inner" name
:accesskey accesskey
:nofollow nofollow
))
555 (funcall trailing-html out-stream
))
556 (format out-stream
"</span>")))))
559 (defun nav-bar-outer (out-stream class nav-bar
&optional current-uri
)
560 (format out-stream
"<nav id=\"~A\" class=\"nav-bar~@[ ~A~]\">" (string-downcase (first nav-bar
)) class
)
561 (nav-bar-inner out-stream
(second nav-bar
) current-uri
)
562 (format out-stream
"</nav>"))
564 (defun nav-bar-to-html (out-stream class current-uri
)
565 (let* ((nav-bars (map 'list
(lambda (x) (prepare-nav-bar x current-uri
)) (site-nav-bars *current-site
*)))
566 (active-bar (or (find-if (lambda (x) (nav-bar-active x current-uri
)) nav-bars
) (car (last nav-bars
))))
567 (inactive-bars (remove active-bar nav-bars
)))
568 (dolist (bar inactive-bars
)
569 (nav-bar-outer out-stream
(format nil
"~@[~A ~]inactive-bar" class
) bar current-uri
))
570 (nav-bar-outer out-stream
(format nil
"~@[~A ~]active-bar" class
) active-bar current-uri
)))
572 (defun user-nav-item (&optional current-uri
)
574 `("login" "/login" "Read Only Mode" :html
,(lambda (out-stream)
575 (format out-stream
"<span class=\"nav-inner\" title=\"~A\">[Read Only Mode]</span>"
576 (typecase *read-only-mode
*
577 (string *read-only-mode
*)
578 (t *read-only-default-message
*)))))
579 (if-let (username (logged-in-username))
580 (let ((user-slug (encode-entities (logged-in-user-slug))))
581 `("login" ,(format nil
"/users/~A" user-slug
) ,(plump:encode-entities username
) :description
"User page" :accesskey
"u"
582 :trailing-html
,(lambda (out-stream) (inbox-to-html out-stream user-slug
))))
583 `("login" "/login" "Log In"
584 :html
,(lambda (out-stream)
585 (write-string "<form action='/login' id='login-button-form'><input type='hidden' name='return' value='" out-stream
)
586 (encode-entities current-uri out-stream
)
587 (write-string "'></form><button class='nav-inner' form='login-button-form' accesskey='u'>Log In</button>" out-stream
))))))
589 (defun sublevel-nav-to-html (options current
&key default
(base-uri (hunchentoot:request-uri
*)) (param-name "show") (remove-params '("offset")) extra-class
)
590 (declare (type (or null string
) extra-class
))
591 (let ((out-stream *html-output
*))
592 (format out-stream
"<nav class=\"sublevel-nav~@[ ~A~]\">" extra-class
)
593 (loop for item in options
594 do
(destructuring-bind (param-value &key
(text (string-capitalize param-value
)) description
) (if (atom item
) (list item
) item
)
595 (let* ((param-value (string-downcase param-value
))
596 (selected (string-equal current param-value
))
597 (class (if selected
"sublevel-item selected" "sublevel-item")))
598 (link-if-not out-stream selected
(apply #'replace-query-params base-uri param-name
(unless (string-equal param-value default
) param-value
)
599 (loop for x in remove-params nconc
(list x nil
)))
600 class text
:title description
))))
601 (format out-stream
"</nav>")))
603 (defmacro set-script-variables
(&rest clauses
)
604 (with-gensyms (out-stream name value
)
605 `(with-html-stream-output (:stream
,out-stream
)
606 ,.
(loop for clause in clauses
607 collect
(destructuring-bind (name-form value-form
) clause
608 `(let ((,name
,name-form
)
609 (,value
,value-form
))
610 (declare (dynamic-extent ,name
,value
))
611 (write-string ,name
,out-stream
)
612 (write-string "=" ,out-stream
)
613 (json:encode-json
,value
,out-stream
)
614 (write-string #.
(format nil
";~%") ,out-stream
)))))))
616 (defun html-body (out-stream fn
&key title description social-description current-uri content-class robots extra-head
)
617 (macrolet ((for-resource-type ((resource-type &rest args
) &body body
)
618 (with-gensyms (resource)
619 `(dolist (,resource page-resources
)
620 (when (eq (first ,resource
) ,resource-type
)
621 (destructuring-bind ,args
(rest ,resource
)
623 (with-html-stream-output
624 (let* ((session-token (hunchentoot:cookie-in
"session-token"))
625 (csrf-token (and session-token
(make-csrf-token session-token
)))
626 (hide-nav-bars (truthy-string-p (hunchentoot:get-parameter
"hide-nav-bars")))
628 (page-resources (nreverse *page-resources
*))
629 (site-domain (site-domain *current-site
*)))
630 (setf *page-resources
* nil
)
631 (write-string "<!DOCTYPE html><html lang=\"en-US\"><head>
632 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
633 <meta name=\"HandheldFriendly\" content=\"True\" />"
635 (with-delimited-writer (out-stream delimit
:begin
"<script>" :end
"</script>")
638 (set-script-variables ("document.domain" site-domain
))) ; Requires origin-agent-cluster header, see below
641 (when (typep *current-site
* 'login-site
)
642 (set-script-variables
643 ("loggedInUserId" (or (logged-in-userid) ""))
644 ("loggedInUserDisplayName" (or (logged-in-username) ""))
645 ("loggedInUserSlug" (or (logged-in-user-slug) ""))))
646 (set-script-variables
647 ("applicationServerKey" (get-vapid-public-key))
648 ("GW" (alist "useFancyFeatures" (not (typep *current-site
* 'arbital-site
))
649 "secureCookies" (to-boolean (site-secure *current-site
*))
650 "csrfToken" csrf-token
651 "assets" (alist "popup.svg" (generate-versioned-link "/assets/popup.svg"))
652 "sites" (if site-domain
653 (loop for site in
*sites
*
654 when
(let ((sd (site-domain site
))) (and sd
(string-equal sd site-domain
)))
655 collect
(cons (site-host site
) t
))
656 (alist (site-host *current-site
*) t
)))))
657 (for-resource-type (:inline-script script-text
)
658 (write-string ";" out-stream
)
659 (write-string script-text out-stream
))))
661 (funcall lw2.resources
::*script-tags
* out-stream
)
662 (for-resource-type (:script uri
)
663 (format out-stream
"<script src=\"~A\"></script>" uri
))
664 (funcall lw2.resources
::*async-script-tags
* out-stream
)
665 (for-resource-type (:async-script uri
)
666 (format out-stream
"<script src=\"~A\" async></script>" uri
)))
667 (funcall lw2.resources
::*style-tags
* out-stream
)
668 (for-resource-type (:stylesheet uri
&key media class
)
669 (format out-stream
"<link rel=\"stylesheet\" href=\"~A\"~@[ media=\"~A\"~]~@[ class=\"~A\"~]>" uri media class
))
670 (generate-fonts-html-headers (site-fonts-source *current-site
*))
671 (format out-stream
"<link rel=\"shortcut icon\" href=\"~A\">"
672 (generate-versioned-link "/assets/favicon.ico"))
673 (format out-stream
"<title>~@[~A - ~]~A</title>~@[<meta name=\"description\" content=\"~A\">~]~@[<meta name=\"robots\" content=\"~A\">~]"
674 (if title
(encode-entities title
))
675 (site-title *current-site
*)
680 <meta property
="og:title" content
=title
>)
681 (when social-description
682 <meta property
="og:description" content
=social-description
>
683 <meta property
="og:type" content
="article">))
684 (with-delimited-writer (out-stream delimit
:begin
"<style>" :between
#.
(format nil
"~%") :end
"</style>")
685 (unless (and (typep *current-site
* 'login-site
) (logged-in-userid))
687 (write-string "button.vote { display: none }" out-stream
))
688 (when *memoized-output-without-hyphens
*
689 ;; The browser has been detected as having bugs related to soft-hyphen characters.
690 ;; But there is some hope that it could still do hyphenation by itself.
692 (write-string ".body-text { hyphens: auto; -ms-hyphens: auto; -webkit-hyphens: auto; }" out-stream
)))
694 (format out-stream
"<base target='_top'>"))
695 (when extra-head
(funcall extra-head
))
696 (format out-stream
"</head>")
699 (format out-stream
"<body class=\"theme-~A\"><div id=\"content\"~@[ class=\"~{~A~^ ~}\"~]>"
700 (let ((theme (hunchentoot:cookie-in
"theme")))
701 (if (and theme
(> (length theme
) 0))
704 (list-cond (content-class content-class
)
705 (hide-nav-bars "no-nav-bars")
706 (preview "preview")))
707 (unless (or hide-nav-bars preview
)
708 (nav-bar-to-html out-stream
"nav-bar-top" (or current-uri
(replace-query-params (hunchentoot:request-uri
*) "offset" nil
"sort" nil
)))
709 (when (and (typep *current-site
* 'login-site
) (logged-in-userid))
710 (call-with-server-data 'process-user-status
"/current-user-status")))
711 (activate-client-trigger "navBarLoaded")
713 (format out-stream
"</div></body></html>"))))))
715 (defun replace-query-params (uri &rest params
)
716 (let* ((quri (quri:uri uri
))
717 (old-params (quri:uri-query-params quri
))
718 (new-params (loop with out
= old-params
719 for
(param value
) on params by
#'cddr
721 (if-let (old-cons (assoc param out
:test
#'equal
))
722 (setf (cdr old-cons
) value
)
723 (setf out
(nconc out
(list (cons param value
)))))
724 (setf out
(remove-if (lambda (x) (equal (car x
) param
)) out
)))
725 finally
(return out
))))
727 (setf (quri:uri-query-params quri
) new-params
)
728 (setf (quri:uri-query quri
) nil
))
729 (quri:render-uri quri
)))
731 (defun pagination-nav-bars (&key offset total with-next
(items-per-page (user-pref :items-per-page
)))
733 (lambda (out-stream fn
)
734 (declare (ignore out-stream
))
736 (lambda (out-stream fn
)
737 (labels ((pages-to-end (n) (< (+ offset
(* items-per-page n
)) total
)))
738 (let* ((with-next (if total
(pages-to-end 1) with-next
))
739 (next (if (and offset with-next
) (+ offset items-per-page
)))
740 (prev (if (and offset
(>= offset items-per-page
)) (- offset items-per-page
)))
741 (request-uri (hunchentoot:request-uri
*))
742 (first-uri (if (and prev
(> prev
0)) (replace-query-params request-uri
"offset" nil
)))
743 (prev-uri (if prev
(replace-query-params request-uri
"offset" (if (= prev
0) nil prev
))))
744 (next-uri (if next
(replace-query-params request-uri
"offset" next
)))
745 (last-uri (if (and total offset
(pages-to-end 2))
746 (replace-query-params request-uri
"offset" (- total
(mod (- total
1) items-per-page
) 1)))))
747 (if (or next prev last-uri
)
748 (labels ((write-item (uri class title accesskey
)
749 (format out-stream
"<a href=\"~A\" class=\"button nav-item-~A~:[ disabled~;~]\" title=\"~A [~A]\" accesskey=\"~A\"></a>"
750 (or uri
"#") class uri title accesskey accesskey
)))
751 (format out-stream
"<nav id='top-nav-bar'>")
752 (write-item first-uri
"first" "First page" "\\")
753 (write-item prev-uri
"prev" "Previous page" "[")
754 (format out-stream
"<span class='page-number'><span class='page-number-label'>Page</span> ~A</span>" (+ 1 (/ (or offset
0) items-per-page
)))
755 (write-item next-uri
"next" "Next page" "]")
756 (write-item last-uri
"last" "Last page" "/")
757 (format out-stream
"</nav>")))
759 (nav-bar-outer out-stream nil
(list :bottom-bar
761 (first-uri `("first" ,first-uri
"Back to first"))
762 (prev-uri `("prev" ,prev-uri
"Previous" :nofollow t
))
763 (t `("top" "#top" "Back to top"))
764 (next-uri `("next" ,next-uri
"Next" :nofollow t
))
765 (last-uri `("last" ,last-uri
"Last" :nofollow t
)))))
766 (format out-stream
"<script>document.querySelectorAll('#bottom-bar').forEach(bb => { bb.classList.add('decorative'); });</script>"))))))
768 (defun decode-json-as-hash-table (json-source)
769 (let (current-hash-table current-key
)
770 (declare (special current-hash-table current-key
))
771 (json:bind-custom-vars
772 (:beginning-of-object
(lambda () (setf current-hash-table
(make-hash-table :test
'equal
)))
773 :object-key
(lambda (x) (setf current-key x
))
774 :object-value
(lambda (x) (setf (gethash current-key current-hash-table
) x
))
775 :end-of-object
(lambda () current-hash-table
)
776 :aggregate-scope
'(current-hash-table current-key
))
777 (json:decode-json-from-source json-source
))))
779 (defun get-ignore-hash (&optional
(user-id (logged-in-userid)))
780 (if-let (ignore-json (and user-id
(cache-get "user-ignore-list" user-id
)))
781 (decode-json-as-hash-table ignore-json
)
782 (make-hash-table :test
'equal
)))
784 (defmacro with-outputs
((out-stream) &body body
)
785 (with-gensyms (stream-sym)
786 (let ((out-body (map 'list
(lambda (x) `(princ ,x
,stream-sym
)) body
)))
787 `(let ((,stream-sym
,out-stream
))
790 (defun call-with-emit-page (out-stream fn
&key title description social-description current-uri content-class
(return-code 200) robots
(pagination (pagination-nav-bars)) top-nav extra-head
)
791 (declare (ignore return-code
))
794 (html-body out-stream
796 (when top-nav
(funcall top-nav
))
797 (funcall pagination out-stream fn
))
798 :title title
:description description
:social-description social-description
:current-uri current-uri
:content-class content-class
:robots robots
:extra-head extra-head
))))
800 (defun set-cookie (key value
&key
(max-age (- (expt 2 31) 1)) (path "/"))
801 (hunchentoot:set-cookie key
:value value
:path path
:max-age max-age
:secure
(site-secure *current-site
*)))
803 (defun set-default-headers (return-code)
804 (setf (hunchentoot:content-type
*) "text/html; charset=utf-8"
805 (hunchentoot:return-code
*) return-code
806 (hunchentoot:header-out
:link
) (let ((output
807 (with-output-to-string (stream)
808 (with-delimited-writer (stream delimit
:between
",")
809 (funcall lw2.resources
::*link-header
* stream delimit
)))))
810 (when (> (length output
) 0)
812 (unless lw2.resources
::*push-option
* (set-cookie "push" "t" :max-age
(* 4 60 60))))
814 (defun user-pref (key)
815 (or (cdr (assoc key
*current-prefs
*))
816 (cdr (assoc key
*default-prefs
*))))
818 (defun set-user-pref (key value
)
819 (assert (boundp 'hunchentoot
:*reply
*))
821 (setf *current-prefs
* (remove-duplicates (acons key value
*current-prefs
*) :key
#'car
:from-end t
))
822 (setf *current-prefs
* (remove key
*current-prefs
* :key
#'car
)))
823 (set-cookie "prefs" (quri:url-encode
(json:encode-json-to-string
*current-prefs
*))))
825 (defmacro emit-page
((out-stream &rest args
&key
(return-code 200) &allow-other-keys
) &body body
)
826 (once-only (return-code)
828 (set-default-headers ,return-code
)
829 (with-response-stream (,out-stream
)
830 (dynamic-flet ((fn () ,@body
))
831 (call-with-emit-page ,out-stream
835 (defmethod call-with-backend-context ((backend backend-token-login
) (request (eql t
)) fn
)
836 (let ((*current-auth-status
* (safe-decode-json (hunchentoot:cookie-in
"lw2-status"))))
837 (multiple-value-bind (*current-auth-token
* *current-userid
* *current-username
*)
838 (let* ((auth-token (hunchentoot:cookie-in
"lw2-auth-token"))
839 (expires (cdr (assoc :expires
*current-auth-status
*))))
840 (when (and (nonempty-string auth-token
)
841 (not *read-only-mode
*)
843 (and (integerp expires
) (<= (get-unix-time) (- expires
(* 60 60 24))))))
844 (with-cache-readonly-transaction
847 (cache-get "auth-token-to-userid" auth-token
)
848 (cache-get "auth-token-to-username" auth-token
)))))
849 (let ((*current-user-slug
* (and *current-userid
* (get-user-slug *current-userid
*)))
850 (*enable-rate-limit
* (if *current-userid
* nil
*enable-rate-limit
*)))
853 (defmethod call-with-site-context ((site ignore-list-site
) (request (eql t
)) fn
)
857 (let ((*current-ignore-hash
* (get-ignore-hash)))
860 (defun call-with-error-page (fn)
861 (with-response-context ()
862 (let* ((*current-prefs
* (safe-decode-json (hunchentoot:cookie-in
"prefs")))
863 (*preview
* (string-equal (hunchentoot:get-parameter
"format") "preview")))
864 (multiple-value-bind (*revalidate-default
* *force-revalidate-default
*)
865 (cond ((ppcre:scan
"(?:^|,?)\\s*(?:no-cache|max-age=0)(?:$|,)" (hunchentoot:header-in
* :cache-control
))
871 (when (not *revalidate-default
*)
872 (setf (hunchentoot:header-out
:cache-control
) (format nil
"public, max-age=~A" (* 5 60))))
873 (when (site-domain *current-site
*)
874 (setf (hunchentoot:header-out
:origin-agent-cluster
) "?0")) ; Allow document.domain in Chrome: https://developer.chrome.com/blog/immutable-document-domain/
875 (let ((*memoized-output-without-hyphens
*
876 ;; Soft hyphen characters mess up middle-click paste and screen readers, so try to identify whether they are necessary.
877 ;; See https://caniuse.com/?search=hyphens
878 (if-let ((ua (hunchentoot:header-in
* :user-agent
)))
881 (declare (regex-groups-min 1))
882 (or (> (parse-integer (reg 0)) 87)
883 (ppcre:scan
"Macintosh|Android" ua
)))
885 (declare (regex-groups-min 1))
886 (> 19 (parse-integer (reg 0))))
890 (catch 'abort-response
892 ((fatal-error (lambda (condition)
893 (abort-response-if-unrecoverable condition
)
894 (let ((error-html (with-output-to-string (*html-output
*) (error-to-html condition
))))
895 (emit-page (out-stream :title
"Error" :return-code
(condition-http-return-code condition
) :content-class
"error-page")
896 (write-string error-html out-stream
)
897 (when (eq (hunchentoot:request-method
*) :post
)
898 <form method
="post" class
="error-retry-form">
899 (loop for
(key . value
) in
(hunchentoot:post-parameters
*)
900 do
<input type
="hidden" name
=key value
=value
>)
901 <input type
="submit" value
="Retry">
903 (return-from call-with-error-page
)))))
905 (if (or (eq (hunchentoot:request-method
*) :post
)
906 (not (and (boundp '*test-acceptor
*) (boundp '*hunchentoot-taskmaster
*)))) ; TODO fix this hack
908 (sb-sys:with-deadline
(:seconds
(expt 1.3
909 (min (round (log 30 1.3))
910 (- (hunchentoot:taskmaster-max-thread-count
(symbol-value '*hunchentoot-taskmaster
*))
911 (hunchentoot:acceptor-requests-in-progress
(symbol-value '*test-acceptor
*))))))
912 (funcall fn
))))))))))))
914 (defmacro with-error-page
(&body body
)
915 `(dynamic-flet ((fn () ,@body
)) (call-with-error-page #'fn
)))
917 (defun output-form (out-stream method action id heading csrf-token fields button-label
&key textarea end-html
)
918 (format out-stream
"<form method=\"~A\" action=\"~A\" id=\"~A\"><h1>~A</h1>" method action id heading
)
919 (loop for
(id label type . params
) in fields
920 do
(format out-stream
"<label for=\"~A\">~A:</label>" id label
)
922 ((string= type
"select")
923 (destructuring-bind (option-list &optional default
) params
924 (format out-stream
"<select name=\"~A\">" id
)
925 (loop for
(value label
) in option-list
926 do
(format out-stream
"<option value=\"~A\"~:[~; selected~]>~A</option>" value
(string= default value
) label
))
927 (format out-stream
"</select>")))
929 (destructuring-bind (&optional
(autocomplete "off") default
) params
930 (format out-stream
"<input type=\"~A\" name=\"~A\" autocomplete=\"~A\"~@[ value=\"~A\"~]>" type id autocomplete
(and default
(encode-entities default
))))))
931 do
(format out-stream
""))
933 (destructuring-bind (ta-name ta-contents
) textarea
934 (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
))))
935 (format out-stream
"<input type=\"hidden\" name=\"csrf-token\" value=\"~A\"><input type=\"submit\" value=\"~A\">~@[~A~]</form>"
936 csrf-token button-label end-html
))
938 (defun page-toolbar-to-html (&key title new-post new-conversation logout
(rss t
) ignore enable-push-notifications
)
940 (let ((out-stream *html-output
*)
941 (liu (logged-in-userid)))
942 (format out-stream
"<div class=\"page-toolbar~@[ hide-until-init~]\">" enable-push-notifications
)
944 (format out-stream
"<form method=\"post\" action=\"/logout\"><input type=\"hidden\" name=\"csrf-token\" value=\"~A\"><button class=\"logout-button button\" name=\"logout\">Log out</button></form>"
948 (when enable-push-notifications
949 (format out-stream
"<script>document.currentScript.outerHTML='<button id=\"enable-push-notifications\" class=\"button\" style=\"display: none\" data-enabled=\"~:[~;true~]\">~:*~:[En~;Dis~]able push notifications</button>'</script>"
950 (find-subscription *current-auth-token
*)))
951 (when (and new-conversation liu
)
952 (multiple-value-bind (text to
)
953 (typecase new-conversation
(string (values "Send private message" new-conversation
)) (t "New conversation"))
954 (format out-stream
"<a class=\"new-private-message button\" href=\"/conversation~@[?to=~A~]\">~A</a>"
956 (when (and new-post liu
)
957 (format out-stream
"<a class=\"new-post button\" href=\"/edit-post~@[?section=~A~]\" accesskey=\"n\" title=\"Create new post [n]\">New post</a>"
958 (typecase new-post
(string new-post
) (t nil
))))
959 (when (and title rss
)
960 (format out-stream
"<a class=\"rss\" rel=\"alternate\" type=\"application/rss+xml\" title=\"~A RSS feed\" href=\"~A\">RSS</a>"
961 title
(replace-query-params (hunchentoot:request-uri
*) "offset" nil
"format" "rss")))
962 (format out-stream
"</div>"))))
964 (defun view-items-index (items &key section title current-uri hide-title need-auth extra-head
(pagination (pagination-nav-bars)) (top-nav (lambda () (page-toolbar-to-html :title title
))) (content-class "index-page") alternate-html
)
965 (alexandria:switch
((hunchentoot:get-parameter
"format") :test
#'string
=)
967 (setf (hunchentoot:content-type
*) "application/rss+xml; charset=utf-8")
968 (with-response-stream (out-stream)
969 (write-index-items-to-rss out-stream items
:title title
)))
971 (emit-page (out-stream :title
(if hide-title nil title
) :description
(site-description *current-site
*) :content-class content-class
972 :current-uri current-uri
:robots
(if (hunchentoot:get-parameter
:offset
) "noindex, nofollow")
973 :pagination pagination
:top-nav top-nav
:extra-head extra-head
)
975 (funcall alternate-html
)
976 (write-index-items-to-html out-stream items
978 :skip-section section
))))))
980 (defun link-if-not (stream linkp url class text
&key accesskey nofollow title
)
981 (declare (dynamic-extent linkp url text
))
983 (format stream
"<a href=\"~A\" class=\"~A\"~@[ accesskey=\"~A\"~]~:[~; rel=\"nofollow\"~]~@[ title=\"~A\"~]>~A</a>" url class accesskey nofollow title text
)
984 (format stream
"<span class=\"~A\"~@[ title=\"~A\"~]>~A</span>" class title text
)))
986 (defgeneric main-site-link
(site item-type item-designator
&key
)
987 (:method
((site lw2-frontend-site
) (item-type (eql :post
)) (post-id string
) &key slug comment-id direct-comment-link
)
989 (format nil
"/posts/~A/~A~[~;#~A~;?commentId=~A~]" post-id slug
(if comment-id
(if direct-comment-link
2 1) 0) comment-id
)
990 (main-site-uri *current-site
*)))
991 (:method
((site lw2-frontend-site
) (item-type (eql :tag
)) (slug string
) &key comment-id direct-comment-link
)
992 (when (not (and comment-id direct-comment-link
))
994 (format nil
"/tag/~A~@[/discussion#~A~]" slug comment-id
)
995 (main-site-uri *current-site
*)))))
997 (defun postprocess-markdown (markdown)
998 (if (typep *current-site
* 'alternate-frontend-site
)
1000 ((concatenate 'string
(regex-replace-all "\\." (site-uri *current-site
*) "\\.") "posts/([^/ ]{17})/([^/# ]*)(?:(#comment-|/comment/|/answer/)([^/ ]{17}))?")
1002 (main-site-link *current-site
*
1003 :post
(reg 0) :slug
(reg 1) :comment-id
(reg 3)
1004 :direct-comment-link
(and (reg 3) (reg 2) (string= "/" (reg 2) :end2
1))))
1007 (defun redirect (uri &key
(type :see-other
) preserve-query
)
1008 (setf (hunchentoot:return-code
*) (ecase type
(:see-other
303) (:permanent
301))
1009 (hunchentoot:header-out
"Location") (if-let ((query (and preserve-query
(hunchentoot:query-string
*))))
1010 (quri:render-uri
(quri:make-uri
:defaults uri
:query query
))
1013 (defun main-site-redirect (uri &key
(type :see-other
))
1014 (redirect (merge-uris uri
(main-site-uri *current-site
*)) :type type
))
1016 (defmacro request-method
(&body method-clauses
)
1017 (with-gensyms (request-method)
1018 `(let ((,request-method
(hunchentoot:request-method
*)))
1020 ,.
(loop for method-body in method-clauses
1021 collect
(destructuring-bind (method args
&body inner-body
) method-body
1022 `(,(if (eq method
:get
) `(member ,request-method
'(:get
:head
)) `(eq ,request-method
,method
))
1023 ,(make-binding-form (mapcar (lambda (x) (append (ensure-list x
) `(:request-type
,method
))) args
)
1026 (defmacro define-page
(name path-specifier additional-vars
&body body
)
1027 (labels ((make-lambda (args)
1029 collect
(if (atom a
) a
(first a
)))))
1030 (multiple-value-bind (path-specifier-form path-bindings-wrapper specifier-vars
)
1031 (if (stringp path-specifier
)
1032 (values path-specifier
#'identity
)
1033 (destructuring-bind (specifier-type specifier-body
&rest specifier-args
) path-specifier
1034 (ecase specifier-type
1036 (values `(lambda (r) (funcall ,specifier-body
(hunchentoot:request-uri r
)))
1038 (lambda (body) `(ignorable-multiple-value-bind ,(make-lambda specifier-args
) (funcall ,specifier-body
(hunchentoot:request-uri
*)) ,body
))
1042 (let ((fn `(lambda (r) (ppcre:scan-to-strings
,specifier-body
(hunchentoot:request-uri r
)))))
1045 (with-gensyms (result-vector)
1046 `(let ((,result-vector
(nth-value 1 (funcall ,fn hunchentoot
:*request
*))))
1047 (declare (type simple-vector
,result-vector
)
1048 (ignorable ,result-vector
))
1050 ,(loop for v in
(make-lambda specifier-args
) as x from
0 collecting
`(,v
(if (> (length ,result-vector
) ,x
) (aref ,result-vector
,x
))))
1052 specifier-args
))))))
1053 `(hunchentoot:define-easy-handler
(,name
:uri
,path-specifier-form
) ()
1056 ,(funcall path-bindings-wrapper
1057 (make-binding-form (append (mapcar (lambda (x) (append (ensure-list x
) '(:passthrough t
))) specifier-vars
) additional-vars
)
1060 (define-component sort-widget
(&key
(sort-options '((:new
:description
"Sort by date posted")
1061 (:hot
:description
"Sort by time-weighted score")
1062 (:active
:description
"Sort by date posted or last comment")
1063 (:old
:description
"Sort by date posted, oldest first")))
1064 (pref :default-sort
) (param-name "sort") (html-class "sort"))
1065 (:http-args
((sort :real-name param-name
:member
(mapcar (lambda (x) (if (listp x
) (first x
) x
)) sort-options
))
1066 (sortedby :real-name
"sortedBy" :type string
)
1067 &without-csrf-check
))
1072 (let ((sort-string (if sort
(string-downcase sort
))))
1074 (set-user-pref :default-sort sort-string
))
1076 (sublevel-nav-to-html sort-options
1078 :param-name param-name
1079 :extra-class html-class
))
1080 (or sort-string
(user-pref pref
)))))
1082 (defun handle-last-modified (last-modified)
1084 (let ((last-modified (max last-modified
(load-time-value (get-universal-time)))))
1085 (setf (hunchentoot:header-out
:last-modified
) (hunchentoot:rfc-1123-date last-modified
)
1086 (hunchentoot:header-out
:vary
) "cookie")
1087 (hunchentoot:handle-if-modified-since last-modified
))))
1089 (define-component view-index
()
1090 (:http-args
((view :member
'(:all
:new
:frontpage
:featured
:alignment-forum
:questions
:nominations
:reviews
:events
) :default
:frontpage
)
1092 (offset :type fixnum
)
1093 (limit :type fixnum
:default
(user-pref :items-per-page
))
1094 (karma-threshold :type fixnum
)
1095 &without-csrf-check
))
1096 (when (eq view
:new
) (redirect (replace-query-params (hunchentoot:request-uri
*) "view" "all" "all" nil
) :type
:permanent
) (return))
1097 (component-value-bind ((sort-string sort-widget
))
1098 (multiple-value-bind (posts total last-modified
)
1099 (get-posts-index :view
(string-downcase view
) :before before
:after after
:offset offset
:limit
(1+ limit
) :sort sort-string
:karma-threshold karma-threshold
)
1100 (handle-last-modified last-modified
)
1101 (let ((page-title (format nil
"~@(~A posts~)" view
)))
1103 (view-items-index (firstn posts limit
)
1104 :section view
:title page-title
:hide-title
(eq view
:frontpage
)
1105 :pagination
(pagination-nav-bars :offset
(or offset
0) :total total
:with-next
(and (not total
) (> (length posts
) limit
)))
1106 :content-class
(format nil
"index-page ~(~A~)-index-page" view
)
1108 (page-toolbar-to-html :title page-title
1109 :new-post
(if (eq view
:meta
) "meta" t
))
1110 (funcall sort-widget
))))))))
1112 (defmacro route-component
(name lambda-list
&rest args
)
1113 `(lambda ,lambda-list
1115 (component-value-bind ((() (,name
,@args
)))
1117 (funcall ,name
))))))
1119 (defmacro define-component-routes
(site-class &rest clauses
)
1122 (for clause in clauses
)
1123 (destructuring-bind (name (route-class &rest route-args
) route-bindings
(component-name &rest component-args
)) clause
1124 (collect `(define-route ',site-class
',route-class
1125 :name
',name
,@route-args
1126 :handler
(route-component ,component-name
,route-bindings
,@component-args
)))))))
1128 (define-component-routes forum-site
1129 (view-root (standard-route :uri
"/") () (view-index))
1130 (view-index (standard-route :uri
"/index") () (view-index)))
1132 (hunchentoot:define-easy-handler
1135 (declare (ignore req
))
1136 (with-site-context ((let ((host (or (hunchentoot:header-in
* :x-forwarded-host
) (hunchentoot:header-in
* :host
))))
1137 (or (find-site host
)
1138 (error "Unknown site: ~A" host
))))
1139 (call-route-handler *current-site
* (hunchentoot:script-name
*)))))
1142 (define-page view-post
"/post" ((id :required t
))
1143 (redirect (generate-item-link :post id
) :type
:permanent
))
1145 (define-page view-post-lw1-link
(:function
#'match-lw1-link
) ()
1146 (redirect (convert-lw1-link (hunchentoot:script-name
*)) :preserve-query t
:type
:permanent
))
1148 (define-page view-post-ea1-link
(:function
#'match-ea1-link
) ()
1149 (redirect (convert-ea1-link (hunchentoot:script-name
*)) :preserve-query t
:type
:permanent
))
1151 (define-page view-post-lw2-slug-link
(:function
#'match-lw2-slug-link
) ()
1152 (redirect (convert-lw2-slug-link (hunchentoot:request-uri
*)) :type
:see-other
))
1154 (define-page view-post-lw2-sequence-link
(:function
#'match-lw2-sequence-link
) ()
1155 (redirect (convert-lw2-sequence-link (hunchentoot:request-uri
*)) :type
:see-other
))
1157 (define-page view-feed
"/feed" ()
1158 (redirect "/?format=rss" :type
:permanent
))
1160 (define-page view-allposts
"/allPosts" ()
1161 (redirect (format nil
"/index~@[?~A~]" (hunchentoot:query-string
*)) :type
:see-other
))
1163 (define-page view-nominations
"/nominations" ()
1164 (redirect "/index?view=nominations" :type
:see-other
))
1166 (define-page view-reviews
"/reviews" ()
1167 (redirect "/index?view=reviews" :type
:see-other
))
1169 (define-page view-review-voting
"/reviewVoting" ()
1170 (redirect "https://www.lesswrong.com/reviewVoting" :type
:see-other
))
1172 (define-page view-coronavirus-link-database
"/coronavirus-link-database" ()
1173 (redirect "https://www.lesswrong.com/coronavirus-link-database" :type
:see-other
))
1175 (defun post-comment (&key need-auth
((:post-id post-id-real
)) ((:tag-id tag-id-real
)) shortform
)
1177 (:post
(text answer nomination nomination-review af post-id tag-id parent-answer-id parent-comment-id edit-comment-id retract-comment-id unretract-comment-id delete-comment-id
)
1178 (let ((lw2-auth-token *current-auth-token
*))
1179 (assert lw2-auth-token
)
1180 (let* ((post-id (or post-id-real post-id
))
1181 (tag-id (or tag-id-real tag-id
))
1182 (question (when post-id
(cdr (assoc :question
(get-post-body post-id
:auth-token lw2-auth-token
)))))
1188 (t :body
(postprocess-markdown text
))
1189 ((and post-id
(not (or edit-comment-id
(and shortform
(not parent-comment-id
))))) :post-id post-id
)
1190 ((and tag-id
(not edit-comment-id
)) :tag-id tag-id
)
1191 (parent-comment-id :parent-comment-id parent-comment-id
)
1193 (nomination :nominated-for-review
"2020")
1194 (nomination-review :reviewing-for-review
"2020")
1195 (parent-answer-id :parent-answer-id parent-answer-id
)
1197 ((and shortform
(not parent-comment-id
)) :shortform t
))))
1199 (do-lw2-comment-edit lw2-auth-token edit-comment-id comment-data
)
1200 (do-lw2-comment lw2-auth-token comment-data
))))
1202 (do-lw2-comment-edit lw2-auth-token retract-comment-id
'((:retracted . t
))))
1203 (unretract-comment-id
1204 (do-lw2-comment-edit lw2-auth-token unretract-comment-id
'((:retracted .
:false
))))
1206 (do-lw2-comment-remove lw2-auth-token delete-comment-id
:reason
"Comment deleted by its author.")
1210 (get-post-comments post-id
:force-revalidate t
)
1212 (get-post-answers post-id
:force-revalidate t
))))
1214 (alist-bind ((new-comment-id simple-string
:--id
)
1215 (new-comment-html simple-string
:html-body
))
1217 (mark-comment-replied (alist* :parent-comment-id parent-comment-id
:user-id
*current-userid
* new-comment-result
))
1218 (setf (markdown-source :comment new-comment-id new-comment-html
) text
)
1219 (redirect (merge-uris (quri:make-uri
:fragment
(format nil
"comment-~A" new-comment-id
)
1220 :query
(list-cond (need-auth "need-auth" "y")))
1221 (hunchentoot:request-uri
*))))))))))
1223 (defun output-comments (out-stream id comments target
&key overcomingbias-sort preview chrono replies-open
)
1224 (labels ((output-comments-inner ()
1225 (with-error-html-block ()
1227 (comment-thread-to-html out-stream
1229 (comment-item-to-html
1232 :level-invert preview
1233 :extra-html-fn
(lambda (c-id)
1234 (let ((*comment-individual-link
* nil
))
1235 (comment-tree-to-html out-stream
(make-comment-parent-hash comments
)
1237 :level-invert preview
))))))
1239 (progn #|
<div class
="comments-empty-message">(safe (pretty-number (length comments
) id
))</div
>|
#
1241 (comment-chrono-to-html out-stream comments
)
1242 (let ((parent-hash (make-comment-parent-hash comments
)))
1243 (when overcomingbias-sort
1244 (setf (gethash nil parent-hash
)
1245 (sort-items (gethash nil parent-hash
) :old
)))
1246 (comment-tree-to-html out-stream parent-hash
))))
1247 <div class
="comments-empty-message">("No ~As." id
)</div
>)))))
1249 (output-comments-inner)
1250 (progn (format out-stream
"<div id=\"~As\" class=\"comments~:[~; replies-open~]\">" id
(and *enable-voting
* replies-open
))
1252 <script
>initializeCommentControls\
(\
)</script
>)
1253 (output-comments-inner)
1254 (format out-stream
"</div>")))))
1256 (define-json-endpoint (view-karma-vote-post forum-site
"/karma-vote/post")
1257 (let ((auth-token *current-auth-token
*))
1260 (hash-cond (make-hash-table)
1261 (post-id "Post" (sethash (make-hash-table) post-id
(get-post-vote post-id auth-token
)))
1262 (post-id "Comment" (get-post-comments-votes post-id auth-token
))
1263 (post-id "Tag" (get-post-tag-votes post-id auth-token
)))))))
1265 (define-page view-post-lw2-link
(:function
#'match-lw2-link post-id comment-id
* comment-link-type post-type
)
1268 (show-comments :real-name
"comments" :type boolean
:default t
)
1269 (format :type string
))
1272 (when (hunchentoot:get-parameter
"commentId")
1273 (redirect (format nil
"~A/comment/~A" (generate-item-link :post post-id
) comment-id
))
1275 (let* ((lw2-auth-token *current-auth-token
*)
1276 (preview (string-equal format
"preview"))
1277 (show-comments (and (not preview
) show-comments
))
1278 (*enable-voting
* (not (null (logged-in-userid)))))
1279 (multiple-value-bind (post title condition
)
1280 (handler-case (nth-value 0 (get-post-body post-id
:auth-token
(and need-auth lw2-auth-token
)))
1281 (serious-condition (c)
1282 (setf *enable-voting
* nil
)
1283 (values nil
"[missing post]" c
))
1285 (values post
(cdr (assoc :title post
)) nil
)))
1286 (let* ((is-event (cdr (assoc :is-event post
)))
1287 (correct-subtype (if is-event
"event" "post")))
1288 (when (string/= post-type correct-subtype
)
1289 (redirect (generate-item-link :post post
:comment-id comment-id
:item-subtype correct-subtype
))
1291 (labels ((extra-head ()
1292 (when-let (canonical-source (or (and (not comment-id
)
1293 (cdr (assoc :canonical-source post
)))
1294 (and (always-canonical *current-site
*)
1295 (main-site-link *current-site
* :post post-id
:slug
(cdr (assoc :slug post
))
1296 :comment-id comment-id
:direct-comment-link t
))))
1297 <link rel
="canonical" href
=canonical-source
>)
1298 <script
>postId
=(with-html-stream-output (:stream stream
) (json:encode-json post-id stream
))</script
>
1299 <script
>alignmentForumPost
=(if (cdr (assoc :af post
)) "true" "false")</script
>
1300 (when (logged-in-userid)
1301 (call-with-server-data 'process-vote-data
(format nil
"/karma-vote/post?post-id=~A" post-id
))))
1302 (retrieve-individual-comment (comment-thread-type)
1303 (let* ((comments (case comment-thread-type
1304 (:comment
(get-post-comments post-id
))
1305 (:answer
(get-post-answers post-id
))))
1306 (target-comment (find comment-id comments
:key
(lambda (c) (cdr (assoc :--id c
))) :test
#'string
=)))
1307 (values comments target-comment
))))
1309 (let ((comment-thread-type (if (string= comment-link-type
"answer") :answer
:comment
)))
1310 (multiple-value-bind (comments target-comment
) (retrieve-individual-comment comment-thread-type
)
1311 (unless target-comment
1312 ;; If the comment was not found, try as an answer, or vice versa.
1313 (setf comment-thread-type
(if (eq comment-thread-type
:comment
) :answer
:comment
)
1314 (values comments target-comment
) (retrieve-individual-comment comment-thread-type
))
1315 (unless target-comment
1316 (error 'lw2-not-found-error
)))
1317 (let* ((*comment-individual-link
* t
)
1318 (display-name (get-username (cdr (assoc :user-id target-comment
))))
1320 ((and (eq comment-thread-type
:answer
)
1321 (not (cdr (assoc :parent-comment-id target-comment
))))
1323 (t "comments on"))))
1324 (emit-page (out-stream :title
(format nil
"~A ~A ~A" display-name verb-phrase title
)
1325 :content-class
"individual-thread-page comment-thread-page"
1326 :social-description
(when-let (x (cdr (assoc :html-body target-comment
))) (extract-excerpt x
))
1327 :extra-head
#'extra-head
)
1329 (format out-stream
"<h1 class=\"post-title\">~A ~A <a href=\"~A\">~A</a></h1>"
1330 (encode-entities display-name
)
1332 (generate-item-link :post post-id
)
1333 (clean-text-to-html title
:hyphenation nil
)))
1334 (output-comments out-stream
"comment" comments target-comment
:chrono chrono
:preview preview
)))))
1335 (let ((post-sequences (get-post-sequences post-id
)))
1336 (emit-page (out-stream :title title
1337 :content-class
(format nil
"post-page comment-thread-page~{ ~A~}"
1338 (list-cond ((cdr (assoc :question post
)) "question-post-page")
1339 (post-sequences "in-sequence")
1340 ((not show-comments
) "no-comments")))
1341 :social-description
(when-let (x (cdr (assoc :html-body post
))) (extract-excerpt x
))
1342 :extra-head
#'extra-head
)
1345 (error-explanation-case (error-to-html condition
)
1346 (lw2-not-allowed-error
1347 <p
>This probably means the post has been deleted or moved back to the author
's drafts.
</p
>)))
1349 (post-body-to-html post
)))
1350 (when (and lw2-auth-token
(equal (logged-in-userid) (cdr (assoc :user-id post
))))
1351 (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>"
1352 (cdr (assoc :--id post
))))
1353 (alist-bind (fm-crosspost foreign-post
) post
1354 (alist-bind (is-crosspost hosted-here
) fm-crosspost
1356 (if-let (crosspost-site-host (backend-magnum-crosspost-site *current-backend
*))
1357 (let* ((*current-site
* (find-site crosspost-site-host
))
1358 (crosspost-site-title (main-site-title *current-site
*)))
1359 (alist-bind (comment-count base-score
) foreign-post
1360 <a class
="crosspost" href
=(generate-item-link :post foreign-post
:absolute t
)>Crossposted
(if hosted-here
"to" "from") (progn crosspost-site-title
)
1361 \ \
((safe (pretty-number (or base-score
0) "point")), (safe (pretty-number (or comment-count
0) "comment"))\
)</a
>))
1362 (error "Could not retrieve crossposted post. magnum-crosspost-site not configured.")))))
1363 (post-nav-links post post-sequences
)
1364 (activate-client-trigger "postLoaded")
1366 (write-string "<script> </script>" out-stream
)
1367 (finish-output out-stream
)
1368 (with-error-html-block ()
1369 ;; Temporary hack to support nominations
1370 (let* ((real-comments (get-post-comments post-id
))
1371 (answers (when (cdr (assoc :question post
))
1372 (get-post-answers post-id
)))
1373 (posted-at (and (typep *current-backend
* 'backend-lw2
)
1374 (cdr (assoc :posted-at post
))))
1375 (posted-timestamp (and posted-at
(local-time:parse-timestring posted-at
)))
1376 (now (local-time:now
))
1377 (nominations-open nil
)
1378 (reviews-eligible (timerange "2020-01-01" posted-timestamp
"2021-01-01"))
1379 (reviews-open (and reviews-eligible
(timerange "2021-12-14" now
"2022-01-11"))))
1380 (labels ((top-level-property (comment property
)
1381 (or (cdr (assoc property comment
))
1382 (cdr (assoc property
(cdr (assoc :top-level-comment comment
)))))))
1383 (multiple-value-bind (normal-comments nominations reviews
)
1384 (loop for comment in real-comments
1385 if
(top-level-property comment
:nominated-for-review
)
1386 collect comment into nominations
1387 else if
(top-level-property comment
:reviewing-for-review
)
1388 collect comment into reviews
1390 collect comment into normal-comments
1391 finally
(return (values normal-comments nominations reviews
)))
1392 (unless (or nominations reviews
)
1393 (setf normal-comments real-comments
)) ;for caching
1394 (loop for
(name comments open
) in
(list-cond ((or nominations nominations-open
)
1395 (list "nomination" nominations nominations-open
))
1396 ((or reviews reviews-open
)
1397 (list "review" reviews reviews-open
))
1398 ((cdr (assoc :question post
))
1399 (list "answer" answers t
))
1401 (list "comment" normal-comments t
)))
1402 do
(output-comments out-stream name comments nil
1404 :overcomingbias-sort
(cdr (assoc :comment-sort-order post
)) :chrono chrono
:preview preview
))))))))))))))
1406 (post-comment :post-id post-id
:need-auth need-auth
))))
1408 (defparameter *edit-post-template
* (compile-template* "edit-post.html"))
1410 (define-page view-edit-post
"/edit-post" (title url section tags post-id link-post
)
1413 (let* ((csrf-token (make-csrf-token))
1414 (post-body (if post-id
(get-post-body post-id
:auth-token
(hunchentoot:cookie-in
"lw2-auth-token"))))
1415 (section (or section
(loop for
(sym . sec
) in
'((:draft .
"drafts") (:meta .
"meta") (:frontpage-date .
"frontpage"))
1416 if
(cdr (assoc sym post-body
)) return sec
1417 finally
(return "all")))))
1418 (emit-page (out-stream :title
(if post-id
"Edit Post" "New Post") :content-class
"edit-post-page")
1419 (render-template* *edit-post-template
* out-stream
1420 :csrf-token csrf-token
1421 :title
(cdr (assoc :title post-body
))
1422 :url
(cdr (assoc :url post-body
))
1423 :question
(cdr (assoc :question post-body
))
1424 :tags-supported
(typep *current-backend
* 'backend-accordius
)
1425 :tags
(when (and post-id
(typep *current-backend
* 'backend-accordius
)) (do-wl-rest-query (format nil
"posts/~a/update_tagset/" post-id
) '()))
1427 :section-list
(loop for
(name desc
) in
'(("all" "All") ("meta" "Meta") ("frontpage" "Frontpage") ("drafts" "Drafts"))
1428 when
(or (string= name section
) (member name
'("drafts" "all") :test
#'string
=))
1429 collect
(alist :name name
:desc desc
:selected
(string= name section
)))
1430 :lesswrong-misc
(typep *current-backend
* 'backend-lw2-misc-features
)
1431 :submit-to-frontpage
(if post-id
(cdr (assoc :submit-to-frontpage post-body
)) t
)
1432 :markdown-source
(or (and post-id
(markdown-source :post post-id
(cdr (assoc :html-body post-body
)))) "")))))
1433 (:post
(text question submit-to-frontpage
)
1434 (let ((lw2-auth-token *current-auth-token
*)
1435 (url (if (string= url
"") nil url
)))
1436 (assert lw2-auth-token
)
1439 (t :body
(postprocess-markdown text
))
1440 (t :title
(or (nonempty-string title
) "Untitled"))
1441 (link-post :url url
)
1442 (t :meta
(or (string= section
"meta") :false
))
1443 ((not post-id
) :is-event nil
)
1444 (t :draft
(or (string= section
"drafts") :false
))
1445 ((typep *current-backend
* 'backend-lw2-misc-features
) :submit-to-frontpage
(and submit-to-frontpage t
))
1446 ((not post-id
) :question
(if question t
:false
))))
1449 ((not link-post
) :url t
)))
1452 (do-lw2-post-edit lw2-auth-token post-id post-data post-unset
)
1453 (do-lw2-post lw2-auth-token post-data
)))
1454 (new-post-id (cdr (assoc :--id new-post-data
))))
1455 (assert new-post-id
)
1456 (when (typep *current-backend
* 'backend-accordius
)
1457 (do-wl-rest-mutate :post
1458 (format nil
"posts/~a/update_tagset/" post-id
)
1461 (setf (markdown-source :post new-post-id
(cdr (assoc :html-body new-post-data
))) text
)
1462 (ignore-errors (get-post-body post-id
:force-revalidate t
))
1463 (redirect (if (js-true (cdr (assoc :draft post-data
)))
1464 (concatenate 'string
(generate-item-link :post new-post-data
) "?need-auth=y")
1465 (generate-item-link :post new-post-data
))))))))
1467 (define-json-endpoint (view-karma-vote forum-site
"/karma-vote")
1468 (let ((auth-token *current-auth-token
*))
1470 (:post
(target target-type
(vote-json :real-name
"vote"))
1471 (let ((vote (safe-decode-json vote-json
)))
1472 (multiple-value-bind (current-vote result
)
1473 (do-lw2-vote auth-token target-type target vote
)
1474 (alist-bind (vote-count base-score af af-base-score extended-score
) result
1475 (let ((vote-buttons (vote-buttons base-score
1477 :af-score
(and af af-base-score
)
1478 :vote-count
(+ vote-count
(if (member (cdr (assoc :karma current-vote
)) '(nil "neutral") :test
#'equal
)
1481 :extended-score extended-score
))
1482 (out (make-hash-table)))
1483 (loop for
(axis . axis-vote
) in current-vote
1484 do
(setf (gethash axis out
) (list* axis-vote
(gethash axis vote-buttons
))))
1487 (delete-easy-handler 'view-karma-vote
)
1489 (define-json-endpoint (view-user-status login-site
"/current-user-status")
1490 (let ((auth-token *current-auth-token
*))
1493 (if (lw2-graphql-query (graphql-query-string "currentUser" nil
'(:--id
)) :auth-token auth-token
)
1494 (sethash (make-hash-table)
1495 "notifications" (check-notifications (logged-in-userid) auth-token
)
1496 "alignmentForumAllowed" (member "alignmentForum" (cdr (assoc :groups
(get-user :user-id
(logged-in-userid)))) :test
#'string
=))
1497 (with-cache-transaction
1498 (cache-del "auth-token-to-userid" auth-token
)
1499 (cache-del "auth-token-to-username" auth-token
)))))))
1501 (hunchentoot:define-easy-handler
(view-check-notifications :uri
"/check-notifications") (format)
1503 (setf (hunchentoot:content-type
*) "application/json")
1504 (if *current-auth-token
*
1505 (let ((notifications-status (check-notifications (logged-in-userid) *current-auth-token
* :full
(string= format
"push"))))
1506 (json:encode-json-to-string notifications-status
)))))
1508 (hunchentoot:define-easy-handler
(view-ignore-user :uri
"/ignore-user") ((csrf-token :request-type
:post
) (target-id :request-type
:post
) (state :request-type
:post
) return
)
1510 (check-csrf-token csrf-token
)
1511 (let ((user-id (logged-in-userid)))
1512 (unless user-id
(error "Not logged in."))
1513 (with-cache-transaction
1514 (let ((ignore-hash (get-ignore-hash user-id
)))
1515 (if (string= state
"ignore")
1516 (setf (gethash target-id ignore-hash
) t
)
1517 (remhash target-id ignore-hash
))
1518 (cache-put "user-ignore-list" user-id ignore-hash
:value-type
:json
))))
1520 (redirect return
))))
1522 (client-defun comment-controls (&key standalone parent-comment-id parent-answer-id edit-comment-id
)
1524 <form method
="post" id
="conversation-form" class
="aligned-form">
1525 <div class
="textarea-container">
1526 <textarea name
="text" oninput
="enableBeforeUnload();"></textarea
>
1527 <span class
="markdown-reference-link">You can use
<a href
="http://commonmark.org/help/" target
="_blank">Markdown
</a
> here.
</span
>
1528 <button type
="button" class
="guiedit-mobile-auxiliary-button guiedit-mobile-help-button">Help
</button
>
1529 <button type
="button" class
="guiedit-mobile-auxiliary-button guiedit-mobile-exit-button">Exit
</button
>
1532 (macrolet ((hidden-var (name)
1533 `(when ,name
<input type
="hidden" name
=,(string-downcase name
) value
=,name
>)))
1534 (hidden-var parent-comment-id
)
1535 (hidden-var parent-answer-id
)
1536 (hidden-var edit-comment-id
))
1537 <input name
="csrf-token" value
=(make-csrf-token) type
="hidden">
1538 <input value
="Submit" type
="submit">
1542 <div class
="posting-controls standalone with-markdown-editor" onsubmit
="disableBeforeUnload();">(with-html-stream-output (inner))</div
>
1545 (define-json-endpoint (view-karma-vote-shortform shortform-site
"/karma-vote/shortform")
1546 (let ((auth-token *current-auth-token
*))
1548 (:get
((offset :type fixnum
:default
0))
1549 (sethash (make-hash-table)
1550 "Comment" (get-shortform-votes auth-token
:offset offset
))))))
1552 (define-component view-comments-index
(index-type)
1553 (:http-args
((offset :type fixnum
)
1554 (limit :type fixnum
)
1555 (view :member
'(nil :alignment-forum
))))
1558 (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.
1559 (shortform (eq index-type
:shortform
))
1560 (with-voting (not (null (and shortform
(logged-in-userid))))))
1561 (multiple-value-bind (title query-view top-nav
)
1563 (shortform (values "Shortform" "shortform" (if (logged-in-userid) (lambda () (comment-controls :standalone t
)))))
1564 (t (values (case view
(:alignment-forum
"Alignment Forum recent comments") (t "Recent comments")) "allRecentComments" nil
)))
1565 (multiple-value-bind (recent-comments total last-modified
)
1566 (if (or (not (eq index-type
:recent-comments
)) offset limit view
(/= (user-pref :items-per-page
) 20))
1567 (let ((*use-alignment-forum
* (eq view
:alignment-forum
)))
1568 (lw2-graphql-query (lw2-query-string :comment
:list
1569 (remove nil
(alist :view query-view
1570 :limit
(or limit
(user-pref :items-per-page
)) :offset offset
)
1572 :context
(if shortform
:shortform
:index
)
1573 :with-total want-total
)))
1574 (get-recent-comments :with-total want-total
))
1575 (handle-last-modified last-modified
)
1577 (view-items-index recent-comments
1579 :extra-head
(lambda ()
1581 (call-with-server-data 'process-vote-data
(format nil
"/karma-vote/shortform?offset=~A" (or offset
0)))))
1582 :content-class
(if shortform
"index-page shortform-index-page comment-thread-page" "index-page comment-index-page")
1583 :pagination
(pagination-nav-bars :offset
(or offset
0) :with-next
(not want-total
) :total
(if want-total total
))
1584 :top-nav
(lambda () (page-toolbar-to-html :title title
) (when top-nav
(funcall top-nav
)))
1585 :alternate-html
(if (eq index-type
:shortform
)
1587 (let ((*enable-voting
* with-voting
))
1588 <div class
="comments">
1589 (comment-tree-to-html *html-output
*
1590 (make-comment-parent-hash
1591 (flatten-shortform-comments recent-comments
)))
1594 (post-comment :shortform t
))))
1596 (define-component-routes forum-site
(view-recent-comments (standard-route :uri
"/recentcomments") () (view-comments-index :recent-comments
)))
1597 (define-component-routes shortform-site
(view-shortform (standard-route :uri
"/shortform") () (view-comments-index :shortform
)))
1599 (delete-easy-handler 'view-recent-comments
)
1601 (defun tag-to-html (tag &key skip-headline
)
1602 (schema-bind (:tag tag
:auto
:context
:body
)
1603 (alist-bind (edited-at html user-id
) description
1604 (unless skip-headline
1605 <h1 class
="post-title">(safe (clean-text-to-html name
))</h1
>
1606 <div class
="post-meta">
1607 <span
>(if core
"Core ")(if wiki-only
"Wiki" "Tag")</span
>
1608 (when (and (nonempty-string edited-at
) (nonempty-string user-id
))
1609 <span
>Last edit
: (pretty-time-html edited-at
)
1610 \ by
<a class
="author" href
=("/users/~A" (get-user-slug user-id
))>(get-username user-id
)</a
>
1614 <div class
="tag-description body-text">(with-html-stream-output (:stream stream
) (let ((*memoized-output-stream
* stream
)) (clean-html* html
)))</div
>))))
1616 (defun tag-list-to-html (tags)
1617 <ul class
="tag-list">
1618 (iter (for tag in tags
)
1619 (schema-bind (:tag tag
:auto
:context
:index
)
1620 <li
><a class
="post-title-link" href
=("/tag/~A" slug
)>(safe (clean-text-to-html name
))(if wiki-only
1622 (if post-count
(format nil
" (~A)" post-count
)))</a
></li
>))
1625 (define-json-endpoint (view-user-autocomplete forum-site
"/-user-autocomplete")
1628 (lw2-search-query q
:indexes
'("test_users")))))
1630 (define-json-endpoint (view-karma-vote-tag forum-site
"/karma-vote/tag")
1631 (let ((auth-token *current-auth-token
*))
1633 (:get
(tag-id post-id
)
1634 (hash-cond (make-hash-table)
1635 (tag-id "Post" (get-tag-post-votes tag-id auth-token
))
1636 (tag-id "Comment" (get-tag-comments-votes tag-id auth-token
))
1637 (post-id "Tag" (get-post-tag-votes post-id auth-token
)))))))
1639 (define-component view-tag
(slug tail
)
1640 (:http-args
((sort :default
:relevant
:member
'(:relevant
:new
:old
))))
1641 (when (nonempty-string tail
)
1642 (redirect (format nil
"/tag/~A" slug
))
1644 (let ((tag (first (lw2-graphql-query (lw2-query-string :tag
:list
(alist :view
"tagBySlug" :slug slug
) :context
:body
)))))
1646 (error 'lw2-not-found-error
))
1649 (let* ((posts (get-tag-posts slug
))
1650 (posts (if (eq sort
:relevant
) posts
(sort-items posts sort
))))
1651 (schema-bind (:tag tag
:auto
:context
:body
)
1653 (view-items-index posts
1654 :title
(format nil
"~A tag" name
)
1655 :extra-head
(lambda ()
1656 (when-let (canonical-source (and (always-canonical *current-site
*)
1657 (main-site-link *current-site
* :tag slug
)))
1658 <link rel
="canonical" href
=canonical-source
>)
1659 (when (logged-in-userid)
1660 (call-with-server-data 'process-vote-data
(format nil
"/karma-vote/tag?tag-id=~A" tag-id
))))
1662 (page-toolbar-to-html :title name
:rss
(not wiki-only
))
1664 (when (and posts
(not *preview
*))
1665 (sublevel-nav-to-html '(:relevant
:new
:old
)
1669 :extra-class
"sort")))
1670 :content-class
"index-page tag-index-page"
1671 :alternate-html
(lambda ()
1673 (write-index-items-to-html *html-output
* posts
))
1674 (when (typep *current-backend
* 'backend-lw2-tags-comments
)
1675 (finish-output *html-output
*)
1676 (let ((*enable-voting
* (not (null (logged-in-userid))))
1677 (comments (lw2-graphql-query (lw2-query-string :comment
:list
(alist :view
"tagDiscussionComments" :tag-id tag-id
)))))
1678 (output-comments *html-output
* "comment" comments nil
:replies-open t
)))))))))
1680 (schema-bind (:tag tag
(tag-id))
1682 (post-comment :tag-id tag-id
)))))))
1684 (define-component-routes forum-site
(view-tag (regex-route :regex
"^/(?:tag|topics)/([^/?]+)(/[^/?]*)?") (slug tail
) (view-tag slug tail
)))
1686 (define-route 'ea-forum-viewer-site
'regex-route
:name
'view-tags-redirect
:regex
"^/tag/" :handler
(lambda () (redirect (ppcre:regex-replace
"^/tag/" (hunchentoot:request-uri
*) "/topics/"))))
1688 (define-component view-tags-index
()
1690 (multiple-value-bind (all-tags portal
)
1691 (lw2-graphql-query-multi
1692 (list (lw2-query-string* :tag
:list
(alist :view
"allTagsAlphabetical"))
1693 (lw2-query-string* :tag
:list
(alist :view
"tagBySlug" :slug
"portal") :context
:body
)))
1695 (iter (for tag in all-tags
)
1696 (schema-bind (:tag tag
(core))
1697 (when core
(collect tag
)))))
1698 (title (if (typep *current-site
* 'lesswrong-viewer-site
) "Concepts Portal" "Tags Portal")))
1700 (emit-page (out-stream :title title
)
1702 <h1 class
="post-title">(safe title
)</h1
>
1703 (tag-to-html (first portal
) :skip-headline t
)
1705 (iter (for (title . tags
) in
(alist "Core Tags" core-tags
"All Tags" all-tags
))
1707 <h1
>(safe title
)</h1
>
1708 (tag-list-to-html tags
))))))))
1710 (define-component-routes forum-site
(view-tags-index (standard-route :uri
"/tags") () (view-tags-index)))
1711 (define-component-routes forum-site
(view-tags-index-alt (standard-route :uri
"/topics") () (view-tags-index)))
1713 (define-route 'forum-site
'standard-route
:name
'view-tags-index-redirect
:uri
"/tags/all" :handler
(lambda () (redirect "/tags")))
1714 (define-route 'forum-site
'standard-route
:name
'view-tags-index-redirect
:uri
"/topics/all" :handler
(lambda () (redirect "/topics")))
1716 (define-route 'alternate-frontend-site
'standard-route
:name
'view-tags-voting-redirect
:uri
"/tagVoting" :handler
(lambda () (main-site-redirect "/tagVoting")))
1717 (define-route 'alternate-frontend-site
'standard-route
:name
'view-tags-dashboard-redirect
:uri
"/tags/dashboard" :handler
(lambda () (main-site-redirect "/tags/dashboard")))
1719 (hunchentoot:define-easy-handler
(view-push-register :uri
"/push/register") ()
1721 (let* ((data (call-with-safe-json (lambda ()
1722 (json:decode-json-from-string
1723 (hunchentoot:raw-post-data
:force-text t
:external-format
:utf-8
)))))
1724 (subscription (cdr (assoc :subscription data
)))
1725 (cancel (cdr (assoc :cancel data
))))
1728 (make-subscription *current-auth-token
*
1729 (cdr (assoc :endpoint subscription
))
1730 (cdr (assoc :expires
*current-auth-status
*)))
1731 (send-notification (cdr (assoc :endpoint subscription
)) :ttl
120))
1733 (delete-subscription *current-auth-token
*)))
1736 (hunchentoot:define-easy-handler
(view-inbox-redirect :uri
"/push/go-inbox") ()
1738 (redirect (format nil
"/users/~A?show=inbox" *current-user-slug
*))))
1740 (define-page view-user
(:regex
"^/users/(.*?)(?:$|\\?)|^/user" user-slug
) (id
1741 (offset :type fixnum
:default
0)
1742 (show :member
'(:all
:posts
:comments
:drafts
:conversations
:inbox
) :default
:all
)
1743 (sort :member
'(:top
:new
:old
) :default
:new
))
1744 (let* ((auth-token (if (eq show
:inbox
) *current-auth-token
*))
1746 (let ((ui (get-user (cond (user-slug :user-slug
) (id :user-id
)) (or user-slug id
) :auth-token auth-token
)))
1747 (if (and (not (cdr (assoc :deleted ui
))) (cdr (assoc :--id ui
)))
1749 (error 'lw2-user-not-found-error
))))
1750 (user-id (cdr (assoc :--id user-info
)))
1751 (own-user-page (logged-in-userid user-id
))
1752 (display-name (if user-slug
(cdr (assoc :display-name user-info
)) user-id
))
1753 (show-text (if (not (eq show
:all
)) (string-capitalize show
)))
1754 (title (format nil
"~A~@['s ~A~]" display-name show-text
))
1755 (sort-type (case sort
(:top
:score
) (:new
:date
) (:old
:date-reverse
))))
1756 (multiple-value-bind (items total last-modified
)
1759 (get-user-page-items user-id
:posts
:offset offset
:limit
(+ 1 (user-pref :items-per-page
)) :sort-type sort-type
))
1761 (get-user-page-items user-id
:comments
:offset offset
:limit
(+ 1 (user-pref :items-per-page
)) :sort-type sort-type
))
1763 (get-user-page-items user-id
:posts
:drafts t
:offset offset
:limit
(+ 1 (user-pref :items-per-page
)) :auth-token
(hunchentoot:cookie-in
"lw2-auth-token")))
1765 (let ((conversations
1766 (lw2-graphql-query (lw2-query-string :conversation
:list
1767 (alist :view
"userConversations" :limit
(+ 1 (user-pref :items-per-page
)) :offset offset
:user-id user-id
)
1768 :fields
'(:--id
:created-at
:title
(:participants
:display-name
:slug
) :----typename
))
1769 :auth-token
(hunchentoot:cookie-in
"lw2-auth-token"))))
1770 (lw2-graphql-query-map
1772 (lw2-query-string* :message
:total
(alist :view
"messagesConversation" :conversation-id
(cdr (assoc :--id c
)))))
1774 :postprocess
(lambda (c result
)
1775 (acons :messages-total result c
))
1776 :auth-token
(hunchentoot:cookie-in
"lw2-auth-token"))))
1778 (error-explanation-case
1780 (let ((notifications (get-notifications :user-id user-id
:offset offset
:auth-token
(hunchentoot:cookie-in
"lw2-auth-token")))
1781 (last-check (ignore-errors (local-time:parse-timestring
(cdr (assoc :last-notifications-check user-info
))))))
1782 (labels ((check-new (key obj
)
1783 (if (ignore-errors (local-time:timestamp
< last-check
(local-time:parse-timestring
(cdr (assoc key obj
)))))
1784 (acons :highlight-new t obj
)
1786 (check-replied (comment)
1787 (let* ((post-id (cdr (assoc :post-id comment
)))
1788 (comment-id (cdr (assoc :--id comment
)))
1789 (reply-comment-id (check-comment-replied comment-id user-id
)))
1790 (if reply-comment-id
1791 (acons :replied
(list :post post-id
:comment-id reply-comment-id
) comment
)
1793 (lw2-graphql-query-map
1795 (alexandria:switch
((cdr (assoc :document-type n
)) :test
#'string
=)
1797 (lw2-query-string* :comment
:single
1798 (alist :document-id
(cdr (assoc :document-id n
)))
1801 (lw2-query-string* :post
:single
(alist :document-id
(cdr (assoc :document-id n
)))))
1803 (lw2-query-string* :message
:single
(alist :document-id
(cdr (assoc :document-id n
)))
1804 :fields
*messages-index-fields
*))
1808 :postprocess
(lambda (n result
)
1810 (funcall (if (string= (cdr (assoc :document-type n
)) "comment") #'check-replied
#'identity
)
1812 (alexandria:switch
((cdr (assoc :document-type n
)) :test
#'string
=)
1813 ("comment" :posted-at
)
1815 ("message" :created-at
))
1818 :auth-token auth-token
)))
1820 (hunchentoot:cookie-in
"lw2-auth-token")
1822 (alist :last-notifications-check
(timestamp-to-graphql (local-time:now
)))))
1823 (lw2-not-allowed-error
1824 <p
>This may mean your login token has expired or become invalid. You can try
<a href
="/login">logging in again
</a
>.
</p
>)))
1826 (get-user-page-items user-id
:both
:offset offset
:limit
(+ 1 (user-pref :items-per-page
)) :sort-type sort-type
)))
1827 (handle-last-modified last-modified
)
1828 (let ((with-next (> (length items
) (+ (if (eq show
:all
) offset
0) (user-pref :items-per-page
))))
1829 (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
1830 (view-items-index interleave
:title title
1831 :content-class
(format nil
"user-page~@[ ~A-user-page~]~:[~; own-user-page~]" (string-downcase show
) own-user-page
)
1832 :current-uri
(format nil
"/users/~A" user-slug
)
1834 :pagination
(pagination-nav-bars :offset offset
:total total
:with-next
(if (not total
) with-next
))
1835 :need-auth
(eq show
:drafts
) :section
(if (eq show
:drafts
) "drafts" nil
)
1837 (page-toolbar-to-html :title title
1838 :enable-push-notifications
(eq show
:inbox
)
1839 :rss
(not (member show
'(:drafts
:conversations
:inbox
)))
1840 :new-post
(if (eq show
:drafts
) "drafts" t
)
1841 :new-conversation
(if own-user-page t user-slug
)
1842 :ignore
(if (and (logged-in-userid) (not own-user-page
))
1844 (let ((ignored (gethash user-id
*current-ignore-hash
*)))
1845 <form method
="post" action
="/ignore-user">
1846 <button class
=("button ~A" (if ignored
"unignore-button" "ignore-button"))>(if ignored
"Unignore user" "Ignore user")</button
>
1847 <input type
="hidden" name
="csrf-token" value
=(make-csrf-token)>
1848 <input type
="hidden" name
="target-id" value
=user-id
>
1849 <input type
="hidden" name
="state" value
=(if ignored
"unignore" "ignore")>
1850 <input type
="hidden" name
="return" value
=(hunchentoot:request-uri
*)>
1852 :logout own-user-page
)
1853 (alist-bind ((actual-id string
:--id
)
1854 (actual-slug string
:slug
)
1855 (karma (or null fixnum
))
1856 (af-karma (or null fixnum
)))
1858 <h1 class
="page-main-heading"
1859 (when (not own-user-page
)
1860 (format nil
"data-~:[~;anti-~]~:*kibitzer-redirect=~:[/users/~*~A~;/user?id=~A~]"
1861 user-slug actual-id actual-slug
))>
1862 (progn display-name
)
1863 (let ((full-name (get-user-full-name user-id
)))
1864 (when (and user-slug
(stringp full-name
) (> (length full-name
) 0))
1865 <span class
="user-full-name">\
((progn full-name
)\
)</span
>))
1867 <div class
="user-stats">
1869 <span class
="karma-type">
1870 <span class
="karma-total">(if user-slug
(pretty-number (or karma
0)) "##")</span
>(if af-karma
" (LW),")
1873 <span class
="karma-type">
1874 <span class
="karma-total af-karma-total">(if user-slug
(pretty-number (or af-karma
0)) "##")</span
> \
(AF\
)
1877 (when-let (html-bio (cdr (assoc :html-bio user-info
)))
1878 <div class
="user-bio body-text">
1879 (with-html-stream-output (:stream stream
)
1880 (let ((*memoized-output-stream
* stream
))
1881 (clean-html* html-bio
)))
1883 (sublevel-nav-to-html `(:all
:posts
:comments
1885 '(:drafts
:conversations
:inbox
)))
1888 (when (member show
'(:all
:posts
:comments
))
1889 (sublevel-nav-to-html '(:new
:top
:old
)
1893 :extra-class
"sort"))))))))
1895 (defparameter *conversation-template
* (compile-template* "conversation.html"))
1897 (define-page view-conversation
"/conversation" (id to subject
)
1901 ((and id to
) (error "This is an invalid URL."))
1903 (multiple-value-bind (conversation messages
)
1904 (get-conversation-messages id
(hunchentoot:cookie-in
"lw2-auth-token"))
1905 (let ((conversation (rectify-conversation conversation
)))
1906 (view-items-index (nreverse messages
) :content-class
"conversation-page" :need-auth t
:title
(encode-entities (cdr (assoc :title conversation
)))
1907 :top-nav
(lambda () (render-template* *conversation-template
* *html-output
*
1908 :conversation conversation
:csrf-token
(make-csrf-token)))))))
1910 (emit-page (out-stream :title
"New conversation" :content-class
"conversation-page")
1911 (render-template* *conversation-template
* out-stream
1914 :csrf-token
(make-csrf-token))))))
1915 (:post
((text :required t
))
1917 (let ((participant-ids (list (logged-in-userid) (cdar (lw2-graphql-query (lw2-query-string :user
:single
(alist :slug to
) :fields
'(:--id
)))))))
1918 (do-create-conversation (hunchentoot:cookie-in
"lw2-auth-token") (alist :participant-ids participant-ids
:title subject
))))))
1919 (do-create-message (hunchentoot:cookie-in
"lw2-auth-token") id text
)
1920 (redirect (format nil
"/conversation?id=~A" id
))))))
1922 (defun search-result-markdown-to-html (item)
1923 (cons (cons :html-body
1924 (handler-case (nth-value 1 (cl-markdown:markdown
(cdr (assoc :body item
)) :stream nil
))
1925 (serious-condition () "[Error while processing search result]")))
1928 (define-page view-search
"/search" ((q :required t
))
1929 (let ((*current-search-query
* q
)
1930 (link (presentable-link q
:search
))
1931 (title (format nil
"~@[~A - ~]Search" q
)))
1932 (declare (special *current-search-query
*))
1935 (multiple-value-bind (tags posts comments
) (lw2-search-query q
)
1936 (let ((tags (map 'list
(lambda (tag)
1937 (alist* :----typename
"Tag" tag
))
1939 (view-items-index (nconc
1940 (map 'list
(lambda (post) (if (cdr (assoc :comment-count post
)) post
(alist* :comment-count
0 post
))) posts
)
1941 (map 'list
#'search-result-markdown-to-html comments
))
1943 (page-toolbar-to-html :title title
:rss t
)
1946 (tag-list-to-html tags
)))
1947 :content-class
"search-results-page" :current-uri
"/search"
1950 (define-page view-login
"/login" (return cookie-check
1951 (login-username :request-type
:post
) (login-password :request-type
:post
)
1952 (signup-username :request-type
:post
) (signup-email :request-type
:post
) (signup-password :request-type
:post
) (signup-password2 :request-type
:post
))
1954 ((emit-login-page (&key error-message
)
1955 (let ((csrf-token (make-csrf-token)))
1956 (emit-page (out-stream :title
"Log in" :current-uri
"/login" :content-class
"login-page" :robots
"noindex, nofollow")
1958 (format out-stream
"<div class=\"error-box\">~A</div>" error-message
))
1959 (with-outputs (out-stream) "<div class=\"login-container\">")
1960 (output-form out-stream
"post" (format nil
"/login~@[?return=~A~]" (if return
(url-rewrite:url-encode return
))) "login-form" "Log in" csrf-token
1961 '(("login-username" "Username" "text" "username")
1962 ("login-password" "Password" "password" "current-password"))
1964 :end-html
(when (typep *current-backend
* 'backend-websocket-login
) ;other backends not supported yet
1965 "<a href=\"/reset-password\">Forgot password</a>"))
1966 (output-form out-stream
"post" (format nil
"/login~@[?return=~A~]" (if return
(url-rewrite:url-encode return
))) "signup-form" "Create account" csrf-token
1967 '(("signup-username" "Username" "text" "username")
1968 ("signup-email" "Email" "text" "email")
1969 ("signup-password" "Password" "password" "new-password")
1970 ("signup-password2" "Confirm password" "password" "new-password"))
1972 (when-let (main-site-title (main-site-title *current-site
*))
1973 (when (typep *current-site
* 'ea-forum-viewer-site
)
1974 <div class
="error-box"><span style
="font-weight:bold">WARNING
:</span
> EA Forum recently switched to a new single sign-on system. Accounts created with the new system do not currently work with GreaterWrong.\
1975 Accounts created before the new system and accounts created through GreaterWrong continue to work.
</div
>)
1976 (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>"
1978 (format out-stream
"</div>"))))
1979 (finish-login (username user-id auth-token error-message
&optional expires
)
1982 (set-cookie "lw2-auth-token" auth-token
:max-age
(if expires
(+ (- expires
(get-unix-time)) (* 24 60 60)) (1- (expt 2 31))))
1983 (if expires
(set-cookie "lw2-status" (json:encode-json-to-string
(alist :expires expires
))))
1984 (cache-put "auth-token-to-userid" auth-token user-id
)
1985 (cache-put "auth-token-to-username" auth-token username
)
1986 (redirect (if (and return
(ppcre:scan
"^/[^/]" return
)) return
"/")))
1988 (emit-login-page :error-message error-message
)))))
1990 ((not (or cookie-check
(hunchentoot:cookie-in
"session-token")))
1991 (set-cookie "session-token" (base64:usb8-array-to-base64-string
(ironclad:make-random-salt
)))
1992 (redirect (format nil
"/login?~@[return=~A&~]cookie-check=y" (if return
(url-rewrite:url-encode return
)))))
1994 (if (hunchentoot:cookie-in
"session-token")
1995 (redirect (format nil
"/login~@[?return=~A~]" (if return
(url-rewrite:url-encode return
))))
1996 (emit-page (out-stream :title
"Log in" :current-uri
"/login")
1997 (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
))))))
2000 ((or (string= login-username
"") (string= login-password
"")) (emit-login-page :error-message
"Please enter a username and password"))
2001 ((lw2.dnsbl
:dnsbl-check
(hunchentoot:real-remote-addr
)) (emit-login-page :error-message
"Your IP address is blacklisted."))
2002 (t (multiple-value-call #'finish-login login-username
(do-login login-username login-password
)))))
2005 ((not (every (lambda (x) (not (string= x
""))) (list signup-username signup-email signup-password signup-password2
)))
2006 (emit-login-page :error-message
"Please fill in all fields"))
2007 ((not (string= signup-password signup-password2
))
2008 (emit-login-page :error-message
"Passwords do not match"))
2009 ((lw2.dnsbl
:dnsbl-check
(hunchentoot:real-remote-addr
)) (emit-login-page :error-message
"Your IP address is blacklisted."))
2010 (t (multiple-value-call #'finish-login signup-username
(do-lw2-create-user signup-username signup-email signup-password
)))))
2012 (emit-login-page)))))
2014 (define-page view-logout
"/logout" ()
2017 (set-cookie "lw2-auth-token" "" :max-age
0)
2018 (do-logout *current-auth-token
*)
2021 (defparameter *reset-password-template
* (compile-template* "reset-password.html"))
2023 (define-page view-reset-password
"/reset-password" ((email :request-type
:post
) (reset-link :request-type
:post
) (password :request-type
:post
) (password2 :request-type
:post
))
2024 (labels ((emit-rpw-page (&key message message-type step
)
2025 (let ((csrf-token (make-csrf-token)))
2026 (emit-page (out-stream :title
"Reset password" :content-class
"reset-password" :robots
"noindex, nofollow")
2027 (render-template* *reset-password-template
* out-stream
2028 :csrf-token csrf-token
2029 :reset-link reset-link
2031 :message-type message-type
2035 (multiple-value-bind (ret error
)
2036 (do-lw2-forgot-password email
)
2037 (declare (ignore ret
))
2039 (emit-rpw-page :step
1 :message error
:message-type
"error")
2040 (emit-rpw-page :step
1 :message
"Password reset email sent." :message-type
"success"))))
2042 (ppcre:register-groups-bind
(reset-token) ("(?:reset-password/|^)([^/#]+)$" reset-link
)
2045 (emit-rpw-page :step
2 :message
"Invalid password reset link." :message-type
"error"))
2046 ((not (string= password password2
))
2047 (emit-rpw-page :step
2 :message
"Passwords do not match." :message-type
"error"))
2049 (multiple-value-bind (user-id auth-token error-message
) (do-lw2-reset-password reset-token password
)
2050 (declare (ignore user-id auth-token
))
2052 (error-message (emit-rpw-page :step
2 :message error-message
:message-type
"error"))
2054 (with-error-page (emit-page (out-stream :title
"Reset password" :content-class
"reset-password")
2055 (format out-stream
"<h1>Password reset complete</h1><p>You can now <a href=\"/login\">log in</a> with your new password.</p>"))))))))))
2059 (define-page view-library
"/library"
2060 ((view :member
'(:featured
:community
) :default
:featured
))
2063 (lw2-query-string :sequence
:list
2064 (alist :view
(case view
2065 (:featured
"curatedSequences")
2066 (:community
"communitySequences")))
2067 :fields
'(:--id
:created-at
:user-id
:title
:----typename
)))))
2070 :title
"Sequences Library"
2071 :content-class
"sequences-page"
2072 :current-uri
"/library"
2074 (sublevel-nav-to-html '(:featured
:community
)
2078 :extra-class
"sequences-view")))))
2080 (define-page view-sequence
(:regex
"^/s(?:equences)?/([^/?#]+)(?:/?$|\\?)" sequence-id
) ()
2081 (let ((sequence (get-sequence sequence-id
)))
2082 (alist-bind ((title string
))
2084 (emit-page (out-stream
2086 :content-class
"sequence-page")
2087 (sequence-to-html sequence
)))))
2089 (define-component view-collection
(collection-id) ()
2090 (let ((collection (get-collection collection-id
)))
2092 (emit-page (out-stream :title
(cdr (assoc :title collection
)) :content-class
"sequence-page collection-page")
2093 (collection-to-html collection
)))))
2095 (define-component-routes lesswrong-viewer-site
(view-sequences (standard-route :uri
"/sequences") () (view-collection "oneQyj4pw77ynzwAF")))
2096 (define-component-routes lesswrong-viewer-site
(view-codex (standard-route :uri
"/codex") () (view-collection "2izXHCrmJ684AnZ5X")))
2097 (define-component-routes lesswrong-viewer-site
(view-hpmor (standard-route :uri
"/hpmor") () (view-collection "ywQvGBSojSQZTMpLh")))
2098 (define-component-routes ea-forum-viewer-site
(view-handbook (standard-route :uri
"/handbook") () (view-collection "MobebwWs2o86cS9Rd")))
2100 (define-component-routes forum-site
(view-tags-index (standard-route :uri
"/tags") () (view-tags-index)))
2102 (define-page view-archive
(:regex
"^/archive(?:/(\\d{4})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))"
2103 (year :type
(mod 10000))
2104 (month :type
(integer 1 12))
2105 (day :type
(integer 1 31)))
2106 ((offset :type fixnum
:default
0))
2107 (local-time:with-decoded-timestamp
(:day current-day
:month current-month
:year current-year
:timezone local-time
:+utc-zone
+) (local-time:now
)
2108 (local-time:with-decoded-timestamp
(:day earliest-day
:month earliest-month
:year earliest-year
:timezone local-time
:+utc-zone
+) (earliest-post-time)
2109 (labels ((url-elements (&rest url-elements
)
2110 (declare (dynamic-extent url-elements
))
2111 (format nil
"/~{~A~^/~}" url-elements
))
2113 (let ((out-stream *html-output
*))
2114 (with-outputs (out-stream) "<div class=\"archive-nav\"><div class=\"archive-nav-years\">")
2115 (link-if-not out-stream
(not (or year month day
)) (url-elements "archive") "archive-nav-item-year" "All")
2116 (loop for y from earliest-year to current-year
2117 do
(link-if-not out-stream
(eq y year
) (url-elements "archive" y
) "archive-nav-item-year" y
))
2118 (format out-stream
"</div>")
2120 (format out-stream
"<div class=\"archive-nav-months\">")
2121 (link-if-not out-stream
(not month
) (url-elements "archive" year
) "archive-nav-item-month" "All")
2122 (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)
2123 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
)))
2124 (format out-stream
"</div>"))
2126 (format out-stream
"<div class=\"archive-nav-days\">")
2127 (link-if-not out-stream
(not day
) (url-elements "archive" year month
) "archive-nav-item-day" "All")
2128 (loop for d from
(if (and (= (or year current-year
) earliest-year
) (= (or month current-month
) earliest-month
)) earliest-day
1)
2129 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
)))
2130 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
))
2131 (format out-stream
"</div>"))
2132 (format out-stream
"</div>"))))
2133 (multiple-value-bind (posts total
)
2134 (lw2-graphql-query (lw2-query-string :post
:list
2135 (alist :view
(if day
"new" "top") :limit
51 :offset offset
2136 :after
(if (and year
(not day
)) (format nil
"~A-~A-~A" (or year earliest-year
) (or month
1) (or day
1)))
2137 :before
(if year
(format nil
"~A-~A-~A" (or year current-year
) (or month
12)
2138 (or day
(local-time:days-in-month
(or month
12) (or year current-year
))))))))
2139 (emit-page (out-stream :title
"Archive" :current-uri
"/archive" :content-class
"archive-page"
2140 :top-nav
#'archive-nav
2141 :pagination
(pagination-nav-bars :items-per-page
50 :offset offset
:total total
:with-next
(if total nil
(> (length posts
) 50))))
2142 (write-index-items-to-html out-stream
(firstn posts
50) :empty-message
"No posts for the selected period.")))))))
2144 (define-page view-about
"/about" ()
2145 (emit-page (out-stream :title
"About" :current-uri
"/about" :content-class
"about-page")
2146 (alexandria:with-input-from-file
(in-stream "www/about.html" :element-type
'(unsigned-byte 8))
2147 (alexandria:copy-stream in-stream out-stream
))))
2149 (define-page misc-pages
(:regex
"^/misc-pages/.+") ()
2150 (let ((pathname (hunchentoot:request-pathname
)))
2151 (unless (probe-file pathname
)
2152 (error 'lw2-not-found-error
))
2153 (emit-page (out-stream :title
"Misc page" :content-class
"misc-page")
2154 (alexandria:with-input-from-file
(in-stream pathname
:element-type
'(unsigned-byte 8))
2155 (alexandria:copy-stream in-stream out-stream
)))))
2157 (define-page view-generated-script
(:regex
"^/generated/([^/]+)\\.js" (name :type string
)) ()
2158 (when-let ((package (find-package (string-upcase name
))))
2159 (setf (hunchentoot:header-out
"Content-Type") "text/javascript")
2160 (let ((stream (make-flexi-stream (hunchentoot:send-headers
) :external-format
:utf-8
)))
2161 (write-package-client-scripts package stream
))))
2163 (hunchentoot:define-easy-handler
2167 (multiple-value-bind (match? strings
) (ppcre:scan-to-strings
"^/proxy-assets/([0-9A-Za-z]+)(-inverted)?$" (hunchentoot:script-name r
) :sharedp t
)
2168 (when-let* ((base-filename (and match?
(svref strings
0)))
2169 (image-data (cache-get "cached-images" base-filename
:value-type
:json
)))
2170 (let ((inverted (svref strings
1)))
2171 (alist-bind ((mime-type simple-string
)) image-data
2172 (setf (hunchentoot:header-out
"X-Content-Type-Options") "nosniff"
2173 (hunchentoot:header-out
"Cache-Control") #.
(format nil
"public, max-age=~A, immutable" 600))
2174 (hunchentoot:handle-static-file
(concatenate 'string
"www/proxy-assets/" base-filename
(if inverted
"-inverted" "")) mime-type
)