Fix comment delete button appearing on comments with children.
[lw2-viewer.git] / lw2.lisp
blob0235543e3eacbae090e038cd0abc69d7a3d11e86
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
4 #:lw2.csrf
5 #:lw2.graphql
6 #:lw2.conditions
7 #:lw2.routes
8 #:lw2.response
9 #:lw2.schema-type
10 #:lw2.interface-utils
11 #:lw2.user-context
12 #:lw2.web-push
13 #:lw2.comment-threads
14 #:lw2.data-viewers.post
15 #:lw2.data-viewers.comment
16 #:lw2.client-script
17 #:lw2.resources)
18 (:import-from #:alexandria #:with-gensyms #:once-only #:ensure-list #:when-let #:when-let* #:if-let #:alist-hash-table)
19 (:import-from #:collectors #:with-collector)
20 (:import-from #:ppcre #:regex-replace-all)
21 (:unintern
22 #:define-regex-handler #:*fonts-stylesheet-uri* #:generate-fonts-link
23 #:user-nav-bar #:*primary-nav* #:*secondary-nav* #:*nav-bars*
24 #:begin-html #:end-html
25 #:*fonts-stylesheet-uris* #:*fonts-redirect-data* #:*fonts-redirect-lock* #:*fonts-redirect-thread*
26 #:postprocess-conversation-title
27 #:map-output
28 #:*earliest-post*
29 #:*extra-external-scripts* #:*extra-inline-scripts*
30 #:site-stylesheets #:site-inline-scripts #:site-scripts #:site-external-scripts #:site-head-elements
31 #:unwrap-stream
32 #:sort-comments
33 #:*html-head*
34 #:with-open-tag)
35 (:recycle #:lw2-viewer #:lw2.backend))
37 (in-package #:lw2-viewer)
39 (named-readtables:in-readtable html-reader)
41 (add-template-directory (asdf:system-relative-pathname "lw2-viewer" "templates/"))
43 (define-cache-database 'backend-lw2-legacy
44 "auth-token-to-userid" "auth-token-to-username" "user-ignore-list")
46 (defvar *read-only-mode* nil)
47 (defvar *read-only-default-message* "Due to a system outage, you cannot log in or post at this time.")
49 (defparameter *default-prefs* (alist :items-per-page 20 :default-sort "new"))
50 (defvar *current-prefs* nil)
52 (defun get-post-sequences (post-id)
53 (when-let (sequence-ids (get-post-sequence-ids post-id))
54 (with-collector (col)
55 (dolist (sequence-id sequence-ids)
56 (let* ((sequence (get-sequence sequence-id))
57 (posts (sequence-post-ids sequence)))
58 (multiple-value-bind (prev next)
59 (loop for prev = nil then (car current)
60 for current on posts
61 when (string= (car current) post-id)
62 return (values prev (second current)))
63 (when (or prev next)
64 (col (list sequence
65 (and prev (get-sequence-post sequence prev))
66 (and next (get-sequence-post sequence next))))))))
67 (col))))
69 (defun rectify-post-relations (post-relations)
70 (remove-if-not (lambda (pr) (cdr (assoc :--id (cdr (first pr))))) post-relations))
72 (defun post-nav-links (post post-sequences)
73 <nav class="post-nav-links">
74 (schema-bind (:post post (target-post-relations source-post-relations) :context :body)
75 (let ((target-post-relations (rectify-post-relations target-post-relations))
76 (source-post-relations (rectify-post-relations source-post-relations)))
77 (when (or target-post-relations source-post-relations)
78 <div class="related-posts">
79 (dolist (relations `((,source-post-relations "Parent question")
80 (,target-post-relations "Sub-question")))
81 (destructuring-bind (related-posts relation-type) relations
82 (when related-posts
83 <div class="related-post-group">
84 <div class="related-post-type">("~A~A" relation-type (if (second related-posts) "s" ""))</div>
85 (dolist (post-relation related-posts)
86 (post-headline-to-html (or (cdr (assoc :source-post post-relation))
87 (cdr (assoc :target-post post-relation)))))
88 </div>)))
89 </div>)))
90 (loop for (sequence prev next) in post-sequences do
91 (progn
92 <div class="post-nav-item sequence">
93 <a class="post-nav sequence-title" href=("/s/~A" (cdr (assoc :--id sequence)))>
94 <span class="post-nav-label">Part of the sequence:</span>
95 <span class="post-nav-title">(safe (clean-text-to-html (cdr (assoc :title sequence))))</span>
96 </a>
97 (labels ((post-nav-link (direction post)
98 <a class=("post-nav ~A" (string-downcase direction)) href=(generate-item-link :post post)>
99 <span class="post-nav-label">(case direction (:prev "Previous: ") (:next "Next: "))</span>
100 <span class="post-nav-title">(safe (clean-text-to-html (cdr (assoc :title post))))</span>
101 </a>))
102 (when prev (post-nav-link :prev prev))
103 (when next (post-nav-link :next next)))
104 </div>))
105 </nav>)
107 (defun rectify-conversation (conversation)
108 (alist-bind ((title (or null string)))
109 conversation
110 (if (or (null title) (string= title ""))
111 (acons :title "[Untitled conversation]" conversation)
112 conversation)))
114 (defun conversation-message-to-html (out-stream message)
115 (alist-bind ((user-id string)
116 (created-at string)
117 (highlight-new boolean)
118 (conversation list)
119 (content list)
120 (contents list)
121 (html-body (or string null)))
122 message
123 (let ((conversation (rectify-conversation conversation)))
124 (multiple-value-bind (pretty-time js-time) (pretty-time created-at)
125 (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\">"
126 (if highlight-new " comment-item-highlight" "")
127 (encode-entities (get-user-slug user-id))
128 (encode-entities (get-username user-id))
129 js-time
130 pretty-time
131 (pretty-time-js)
132 (encode-entities (cdr (assoc :--id conversation)))
133 (encode-entities (cdr (assoc :title conversation)))))
134 (labels ((ws (html-body) (let ((*memoized-output-stream* out-stream)) (clean-html* html-body))))
135 (cond
136 (contents (ws (cdr (assoc :html contents))))
137 (html-body (ws html-body))
138 (t (format out-stream "~{<p>~A</p>~}" (loop for block in (cdr (assoc :blocks content)) collect (encode-entities (cdr (assoc :text block))))))))
139 (format out-stream "</div></div>"))))
141 (defun conversation-index-to-html (out-stream conversation)
142 (alist-bind ((conversation-id string :--id)
143 (title (or null string))
144 (created-at (or null string))
145 (participants list)
146 (messages-total fixnum))
147 (rectify-conversation conversation)
148 (multiple-value-bind (pretty-time js-time) (if created-at (pretty-time created-at) (values "[Error]" 0))
149 (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>"
150 (encode-entities conversation-id)
151 (encode-entities title)
152 (loop for p in participants
153 collect (list (encode-entities (cdr (assoc :slug p))) (encode-entities (cdr (assoc :display-name p)))))
154 (pretty-number messages-total "message")
155 js-time
156 pretty-time
157 (pretty-time-js)))))
159 (defun collection-to-contents (collection &optional (heading-level 1) (used-anchors (make-hash-table :test 'equal)))
160 (alist-bind ((title (or string null)))
161 collection
162 (let ((subcollections (cdr
163 (find-if (lambda (x) (member (car x) '(:books :sequences :chapters) :test #'eq))
164 collection)))
165 contents-head contents-tail)
166 (labels ((add-contents (c)
167 (when c
168 (if contents-head
169 (setf (cdr contents-tail) c)
170 (setf contents-head c))
171 (setf contents-tail (last c)))))
172 (cond
173 ((and title (not (cdr (assoc :books collection))))
174 (add-contents (list (list heading-level title (title-to-anchor title used-anchors))))
175 (dolist (subcollection subcollections)
176 (add-contents (collection-to-contents subcollection (1+ heading-level) used-anchors))))
177 (:otherwise
178 (dolist (subcollection subcollections)
179 (add-contents (collection-to-contents subcollection heading-level used-anchors)))))
180 contents-head))))
182 (defun collection-to-html (collection &optional (heading-level 1) (used-anchors (make-hash-table :test 'equal)))
183 (alist-bind ((title (or string null))
184 (subtitle (or string null))
185 (number (or fixnum null))
186 (contents list)
187 (posts list))
188 collection
189 (let* ((subcollections (cdr
190 (find-if (lambda (x) (member (car x) '(:books :sequences :chapters) :test #'eq))
191 collection)))
192 (html-body (cdr (assoc :html contents))))
193 (cond
194 ((or html-body title posts)
195 <section>
196 (when (or html-body title)
197 <div class="body-text sequence-text">
198 (when title
199 (with-html-stream-output (:stream stream)
200 (format stream "<h~A id=\"~A\" class=\"sequence-chapter\">~@[~A. ~]~A</h~A>"
201 heading-level
202 (title-to-anchor title used-anchors)
203 number
204 (clean-text-to-html title)
205 heading-level)))
206 (when (assoc :books collection)
207 (contents-to-html (collection-to-contents collection) 1 *html-output*))
208 (when subtitle
209 <div class="sequence-subtitle">(safe (clean-text-to-html subtitle))</div>)
210 (when html-body
211 (with-html-stream-output (:stream stream)
212 (let ((*memoized-output-stream* stream)) (clean-html* html-body))))
213 </div>)
214 (if posts
215 (dolist (post posts)
216 (post-headline-to-html post))
217 (dolist (subcollection subcollections)
218 (collection-to-html subcollection (1+ heading-level) used-anchors)))
219 </section>)
220 (:otherwise
221 (dolist (subcollection subcollections)
222 (collection-to-html subcollection heading-level used-anchors)))))))
224 (defun sequence-to-html (sequence)
225 (labels ((contents-to-html (contents &key title subtitle number)
226 (let ((html-body (cdr (assoc :html contents))))
227 (when (or html-body title subtitle)
228 <div class="body-text sequence-text">
229 (when title
230 <h1 class="sequence-chapter">(safe (format nil "~@[~A. ~]~A" number (clean-text-to-html title :hyphenation nil)))</h1>)
231 (when subtitle
232 <div class="sequence-subtitle">(clean-text-to-html subtitle)</div>)
233 (with-html-stream-output (:stream stream)
234 (when html-body
235 (let ((*memoized-output-stream* stream)) (clean-html* html-body))))
236 </div>)))
237 (chapter-to-html (chapter)
238 (alist-bind ((title (or string null))
239 (subtitle (or string null))
240 (number (or fixnum null))
241 (contents list)
242 (posts list))
243 chapter
244 <section>
245 (with-html-stream-output
246 (contents-to-html contents :title title :subtitle subtitle :number number)
247 <section>
248 (with-html-stream-output
249 (dolist (post posts)
250 (post-headline-to-html post)))
251 </section>)
252 </section>)))
253 (alist-bind ((sequence-id string :--id)
254 (title string)
255 (created-at string)
256 (user-id string)
257 (chapters list)
258 (contents list))
259 sequence
260 (multiple-value-bind (pretty-time js-time) (pretty-time created-at)
261 <article>
262 (if chapters
263 <h1 class="post-title">(safe (clean-text-to-html title :hyphenation nil))</h1>
264 <h1 class="listing"><a href=("/s/~A" sequence-id)>(safe (clean-text-to-html title :hyphenation nil))</a></h1>)
265 <div class="post-meta">
266 <a class=("author~{ ~A~}" (list-cond ((logged-in-userid user-id) "own-user-author")))
267 href=("/users/~A" (get-user-slug user-id))
268 data-userid=user-id>
269 (get-username user-id)
270 </a>
271 <div class="date" data-js-date=js-time>
272 (safe pretty-time)
273 (safe (pretty-time-js))
274 </div>
275 </div>
276 (with-html-stream-output
277 (when chapters
278 (contents-to-html contents)
279 (dolist (chapter chapters)
280 (chapter-to-html chapter))))
281 </article>))))
283 (defun comment-post-interleave (list &key limit offset (sort-by :date))
284 (multiple-value-bind (sort-fn sort-key)
285 (ecase sort-by
286 (:date (values #'local-time:timestamp> (lambda (x) (local-time:parse-timestring (cdr (assoc :posted-at x))))))
287 (:date-reverse (values #'local-time:timestamp< (lambda (x) (local-time:parse-timestring (cdr (assoc :posted-at x))))))
288 (:score (values #'> (lambda (x) (cdr (assoc :base-score x))))))
289 (let ((sorted (sort list sort-fn :key sort-key)))
290 (loop for end = (if (or limit offset) (+ (or limit 0) (or offset 0)))
291 for x in sorted
292 for count from 0
293 until (and end (>= count end))
294 when (or (not offset) (>= count offset))
295 collect x))))
297 (defun identify-item (x)
298 (typecase x
299 (cons
300 (if-let (typename (cdr (assoc :----typename x)))
301 (find-symbol (string-upcase typename) (find-package :keyword))
302 (cond
303 ((assoc :message x)
304 :notification)
305 ((assoc :comment-count x)
306 :post)
308 :comment))))
309 (condition :condition)))
311 (defun write-index-items-to-html (out-stream items &key need-auth (empty-message "No entries.") skip-section)
312 (if items
313 (dolist (x items)
314 (with-error-html-block ()
315 (ecase (identify-item x)
316 (:condition
317 (error-to-html x))
318 (:notification
319 (format out-stream "<p>~A</p>" (cdr (assoc :message x))))
320 (:message
321 (format out-stream "<ul class=\"comment-thread\"><li class=\"comment-item depth-odd\">")
322 (unwind-protect
323 (conversation-message-to-html out-stream x)
324 (format out-stream "</li></ul>")))
325 (:conversation
326 (conversation-index-to-html out-stream x))
327 (:post
328 (post-headline-to-html x :need-auth (or need-auth (cdr (assoc :draft x))) :skip-section skip-section))
329 (:comment
330 (comment-thread-to-html out-stream
331 (lambda () (comment-item-to-html out-stream x :with-post-title t))))
332 (:sequence
333 (sequence-to-html x)))))
334 (format out-stream "<div class=\"listing-message\">~A</div>" empty-message)))
336 (defun write-index-items-to-rss (out-stream items &key title need-auth)
337 (let ((full-title (format nil "~@[~A - ~]~A" title (site-title *current-site*)))
338 (items (firstn (sort-items items :new) 20)))
339 (xml-emitter:with-rss2 (out-stream :encoding "UTF-8")
340 (xml-emitter:rss-channel-header full-title (site-uri *current-site*) :description full-title)
341 (labels ((emit-item (item &key title link (guid (cdr (assoc :--id item))) (author (get-username (cdr (assoc :user-id item))))
342 (date (pretty-time (cdr (assoc :posted-at item)) :format local-time:+rfc-1123-format+)) body)
343 (xml-emitter:rss-item
344 title
345 :link link
346 :author author
347 :pubDate date
348 :guid guid
349 :description body)))
350 (dolist (item items)
351 (ecase (identify-item item)
352 (:post
353 (let ((author (get-username (cdr (assoc :user-id item))))
354 (is-event (cdr (assoc :is-event item))))
355 (emit-item item
356 :title (clean-text (format nil "~A by ~A" (cdr (assoc :title item)) author))
357 :author author
358 :link (generate-post-auth-link item :absolute t :need-auth need-auth :item-subtype (if is-event "event" "post"))
359 :body (clean-html (or (cdr (assoc :html-body (get-post-body (cdr (assoc :--id item)) :revalidate nil))) "") :post-id (cdr (assoc :--id item))))))
360 (:comment
361 (schema-bind (:comment item (comment-id post-id user-id html-body))
362 (when post-id ; XXX fixme
363 (emit-item item
364 :title (format nil "Comment by ~A on ~A" (get-username user-id) (get-post-title post-id))
365 :link (generate-item-link :post post-id :comment-id comment-id :absolute t)
366 :body (clean-html html-body)))))))))))
368 (defun search-bar-to-html (out-stream)
369 (declare (special *current-search-query*))
370 (let ((query (and (boundp '*current-search-query*) (hunchentoot:escape-for-html *current-search-query*))))
371 (format out-stream "<form action=\"/search\" class=\"nav-inner\"><input name=\"q\" type=\"search\" ~@[value=\"~A\"~] autocomplete=\"off\" accesskey=\"s\" title=\"Search [s]~@[&#10;Tip: Paste a ~A URL here to jump to that page.~]\"><button>Search</button></form>" query (main-site-title *current-site*))))
373 (defun inbox-to-html (out-stream user-slug &optional new-messages)
374 (let* ((target-uri (format nil "/users/~A?show=inbox" user-slug))
375 (as-link (string= (hunchentoot:request-uri*) target-uri)))
376 (multiple-value-bind (nm-class nm-text)
377 (if new-messages (values "new-messages" "New messages") (values "no-messages" "Inbox"))
378 (format out-stream "<~:[a href=\"~A\"~;span~*~] id=\"inbox-indicator\" class=\"~A\" accesskey=\"o\" title=\"~A~:[ [o]~;~]\">~A</a>"
379 as-link target-uri nm-class nm-text as-link nm-text))))
381 (defmethod site-nav-bars ((site site))
382 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
383 ("about" "/about" "About" :accesskey "t")
384 ("search" "/search" "Search" :html search-bar-to-html)
385 user-nav-item))
386 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
387 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
389 (defmethod site-nav-bars ((site lesswrong-viewer-site))
390 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
391 ("sequences" "/library" "Sequences" :description "Sequences" :accesskey "q")
392 ("about" "/about" "About" :accesskey "t")
393 ("search" "/search" "Search" :html search-bar-to-html)
394 user-nav-item))
395 (:tertiary-bar (("questions" "/index?view=questions" "Questions")
396 ("events" "/index?view=events" "Events")
397 ("shortform" "/shortform" "Shortform" :description "Latest Shortform posts")
398 ("alignment-forum" "/index?view=alignment-forum" "Alignment Forum")
399 ("alignment-forum-comments" "/recentcomments?view=alignment-forum" "AF Comments")))
400 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
401 ("featured" "/index?view=featured" "Featured" :description "Latest featured posts" :accesskey "f")
402 ("all" "/index?view=all" "All" :description "Latest posts from all sections" :accesskey "a")
403 ("tags" "/tags" "Tags" :description "All tags" :accesskey "v")
404 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
406 (defmethod site-nav-bars ((site ea-forum-viewer-site))
407 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
408 ("about" "/about" "About" :accesskey "t")
409 ("search" "/search" "Search" :html search-bar-to-html)
410 user-nav-item))
411 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
412 ("all" "/index?view=all" "All" :description "Latest posts from all sections" :accesskey "a")
413 ("tags" "/tags" "Wiki" :description "Wiki pages and tags" :accesskey "v")
414 ("shortform" "/shortform" "Shortform" :description "Latest Shortform posts")
415 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
417 (defmethod site-nav-bars ((site progress-forum-viewer-site))
418 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
419 ("about" "/about" "About" :accesskey "t")
420 ("search" "/search" "Search" :html search-bar-to-html)
421 user-nav-item))
422 (:tertiary-bar (("questions" "/index?view=questions" "Questions")
423 ("events" "/index?view=events" "Events")
424 ("shortform" "/shortform" "Shortform" :description "Latest Shortform posts")))
425 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
426 ("featured" "/index?view=featured" "Featured" :description "Latest featured posts" :accesskey "f")
427 ("all" "/index?view=all" "All" :description "Latest posts from all sections" :accesskey "a")
428 ("tags" "/tags" "Tags" :description "All tags" :accesskey "v")
429 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
431 (defun prepare-nav-bar (nav-bar current-uri)
432 (list (first nav-bar)
433 (map 'list (lambda (item) (if (listp item) item (funcall item current-uri)))
434 (second nav-bar))))
436 (defun nav-item-active (item current-uri)
437 (when item
438 (destructuring-bind (id uri name &key description html accesskey nofollow trailing-html override-uri) item
439 (declare (ignore id name description html accesskey nofollow trailing-html))
440 (string= (or override-uri uri) current-uri))))
442 (defun nav-bar-active (nav-bar current-uri)
443 (some (lambda (x) (nav-item-active x current-uri)) (second nav-bar)))
445 (defun nav-bar-inner (out-stream items &optional current-uri)
446 (maplist (lambda (items)
447 (let ((item (first items)))
448 (destructuring-bind (id uri name &key description html accesskey nofollow trailing-html override-uri) item
449 (declare (ignore override-uri))
450 (let* ((item-active (nav-item-active item current-uri))
451 (nav-class (format nil "nav-item ~:[nav-inactive~;nav-current~]~:[~; nav-item-last-before-current~]"
452 item-active (and (not item-active) (nav-item-active (cadr items) current-uri)))))
453 (format out-stream "<span id=\"nav-item-~A\" class=\"~A\" ~@[title=\"~A\"~]>"
454 id nav-class description)
455 (if html
456 (funcall html out-stream)
457 (link-if-not out-stream item-active uri "nav-inner" name :accesskey accesskey :nofollow nofollow))
458 (if trailing-html
459 (funcall trailing-html out-stream))
460 (format out-stream "</span>")))))
461 items))
463 (defun nav-bar-outer (out-stream class nav-bar &optional current-uri)
464 (format out-stream "<nav id=\"~A\" class=\"nav-bar~@[ ~A~]\">" (string-downcase (first nav-bar)) class)
465 (nav-bar-inner out-stream (second nav-bar) current-uri)
466 (format out-stream "</nav>"))
468 (defun nav-bar-to-html (out-stream class current-uri)
469 (let* ((nav-bars (map 'list (lambda (x) (prepare-nav-bar x current-uri)) (site-nav-bars *current-site*)))
470 (active-bar (or (find-if (lambda (x) (nav-bar-active x current-uri)) nav-bars) (car (last nav-bars))))
471 (inactive-bars (remove active-bar nav-bars)))
472 (dolist (bar inactive-bars)
473 (nav-bar-outer out-stream (format nil "~@[~A ~]inactive-bar" class) bar current-uri))
474 (nav-bar-outer out-stream (format nil "~@[~A ~]active-bar" class) active-bar current-uri)))
476 (defun user-nav-item (&optional current-uri)
477 (if *read-only-mode*
478 `("login" "/login" "Read Only Mode" :html ,(lambda (out-stream)
479 (format out-stream "<span class=\"nav-inner\" title=\"~A\">[Read Only Mode]</span>"
480 (typecase *read-only-mode*
481 (string *read-only-mode*)
482 (t *read-only-default-message*)))))
483 (if-let (username (logged-in-username))
484 (let ((user-slug (encode-entities (logged-in-user-slug))))
485 `("login" ,(format nil "/users/~A" user-slug) ,(plump:encode-entities username) :description "User page" :accesskey "u"
486 :trailing-html ,(lambda (out-stream) (inbox-to-html out-stream user-slug))))
487 `("login" "/login" "Log In"
488 :html ,(lambda (out-stream)
489 (write-string "<form action='/login' id='login-button-form'><input type='hidden' name='return' value='" out-stream)
490 (encode-entities current-uri out-stream)
491 (write-string "'></form><button class='nav-inner' form='login-button-form' accesskey='u'>Log In</button>" out-stream))))))
493 (defun sublevel-nav-to-html (options current &key default (base-uri (hunchentoot:request-uri*)) (param-name "show") (remove-params '("offset")) extra-class)
494 (declare (type (or null string) extra-class))
495 (let ((out-stream *html-output*))
496 (format out-stream "<nav class=\"sublevel-nav~@[ ~A~]\">" extra-class)
497 (loop for item in options
498 do (destructuring-bind (param-value &key (text (string-capitalize param-value)) description) (if (atom item) (list item) item)
499 (let* ((param-value (string-downcase param-value))
500 (selected (string-equal current param-value))
501 (class (if selected "sublevel-item selected" "sublevel-item")))
502 (link-if-not out-stream selected (apply #'replace-query-params base-uri param-name (unless (string-equal param-value default) param-value)
503 (loop for x in remove-params nconc (list x nil)))
504 class text :title description))))
505 (format out-stream "</nav>")))
507 (defmacro set-script-variables (&rest clauses)
508 (with-gensyms (out-stream name value)
509 `(with-html-stream-output (:stream ,out-stream)
510 ,.(loop for clause in clauses
511 collect (destructuring-bind (name-form value-form) clause
512 `(let ((,name ,name-form)
513 (,value ,value-form))
514 (declare (dynamic-extent ,name ,value))
515 (write-string ,name ,out-stream)
516 (write-string "=" ,out-stream)
517 (json:encode-json ,value ,out-stream)
518 (write-string #.(format nil ";~%") ,out-stream)))))))
520 (defun html-body (out-stream fn &key title description social-description current-uri content-class robots extra-head)
521 (macrolet ((for-resource-type ((resource-type &rest args) &body body)
522 (with-gensyms (resource)
523 `(dolist (,resource page-resources)
524 (when (eq (first ,resource) ,resource-type)
525 (destructuring-bind ,args (rest ,resource)
526 ,@body))))))
527 (with-html-stream-output
528 (let* ((session-token (hunchentoot:cookie-in "session-token"))
529 (csrf-token (and session-token (make-csrf-token session-token)))
530 (hide-nav-bars (truthy-string-p (hunchentoot:get-parameter "hide-nav-bars")))
531 (preview *preview*)
532 (page-resources (nreverse *page-resources*))
533 (site-domain (site-domain *current-site*)))
534 (setf *page-resources* nil)
535 (write-string "<!DOCTYPE html><html lang=\"en-US\"><head>
536 <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
537 <meta name=\"HandheldFriendly\" content=\"True\" />"
538 out-stream)
539 (with-delimited-writer (out-stream delimit :begin "<script>" :end "</script>")
540 (when site-domain
541 (delimit)
542 (set-script-variables ("document.domain" site-domain))) ; Requires origin-agent-cluster header, see below
543 (unless preview
544 (delimit)
545 (when (typep *current-site* 'login-site)
546 (set-script-variables
547 ("loggedInUserId" (or (logged-in-userid) ""))
548 ("loggedInUserDisplayName" (or (logged-in-username) ""))
549 ("loggedInUserSlug" (or (logged-in-user-slug) ""))))
550 (set-script-variables
551 ("applicationServerKey" (get-vapid-public-key))
552 ("GW" (alist "useFancyFeatures" (not (typep *current-site* 'arbital-site))
553 "secureCookies" (to-boolean (site-secure *current-site*))
554 "csrfToken" csrf-token
555 "assets" (alist "popup.svg" (generate-versioned-link "/assets/popup.svg"))
556 "sites" (if site-domain
557 (loop for site in *sites*
558 when (let ((sd (site-domain site))) (and sd (string-equal sd site-domain)))
559 collect (cons (site-host site) t))
560 (alist (site-host *current-site*) t)))))
561 (for-resource-type (:inline-script script-text)
562 (write-string ";" out-stream)
563 (write-string script-text out-stream))))
564 (unless preview
565 (funcall lw2.resources::*script-tags* out-stream)
566 (for-resource-type (:script uri)
567 (format out-stream "<script src=\"~A\"></script>" uri))
568 (funcall lw2.resources::*async-script-tags* out-stream)
569 (for-resource-type (:async-script uri)
570 (format out-stream "<script src=\"~A\" async></script>" uri)))
571 (funcall lw2.resources::*style-tags* out-stream)
572 (for-resource-type (:stylesheet uri &key media class)
573 (format out-stream "<link rel=\"stylesheet\" href=\"~A\"~@[ media=\"~A\"~]~@[ class=\"~A\"~]>" uri media class))
574 (generate-fonts-html-headers (site-fonts-source *current-site*))
575 (format out-stream "<link rel=\"shortcut icon\" href=\"~A\">"
576 (generate-versioned-link "/assets/favicon.ico"))
577 (format out-stream "<title>~@[~A - ~]~A</title>~@[<meta name=\"description\" content=\"~A\">~]~@[<meta name=\"robots\" content=\"~A\">~]"
578 (if title (encode-entities title))
579 (site-title *current-site*)
580 description
581 robots)
582 (unless preview
583 (when title
584 <meta property="og:title" content=title>)
585 (when social-description
586 <meta property="og:description" content=social-description>
587 <meta property="og:type" content="article">))
588 (with-delimited-writer (out-stream delimit :begin "<style>" :between #.(format nil "~%") :end "</style>")
589 (unless (and (typep *current-site* 'login-site) (logged-in-userid))
590 (delimit)
591 (write-string "button.vote { display: none }" out-stream))
592 (when *memoized-output-without-hyphens*
593 ;; The browser has been detected as having bugs related to soft-hyphen characters.
594 ;; But there is some hope that it could still do hyphenation by itself.
595 (delimit)
596 (write-string ".body-text { hyphens: auto; -ms-hyphens: auto; -webkit-hyphens: auto; }" out-stream)))
597 (when preview
598 (format out-stream "<base target='_top'>"))
599 (when extra-head (funcall extra-head))
600 (format out-stream "</head>")
601 (unwind-protect
602 (progn
603 (format out-stream "<body class=\"~{~A~^ ~}\"><div id=\"content\"~@[ class=\"~{~A~^ ~}\"~]>"
604 (let* ((theme (nonempty-string (hunchentoot:cookie-in "theme")))
605 (dark-mode (nonempty-string (hunchentoot:cookie-in "dark-mode"))))
606 (list-cond (t (format nil "theme-~A" (or theme "default")))
607 (dark-mode (format nil "force-~A-mode" dark-mode))))
608 (list-cond (content-class content-class)
609 (hide-nav-bars "no-nav-bars")
610 (preview "preview")))
611 (unless (or hide-nav-bars preview)
612 (nav-bar-to-html out-stream "nav-bar-top" (or current-uri (replace-query-params (hunchentoot:request-uri*) "offset" nil "sort" nil)))
613 (when (and (typep *current-site* 'login-site) (logged-in-userid))
614 (call-with-server-data 'process-user-status "/current-user-status")))
615 (activate-client-trigger "navBarLoaded")
616 (funcall fn))
617 (format out-stream "</div></body></html>"))))))
619 (defun replace-query-params (uri &rest params)
620 (let* ((quri (quri:uri uri))
621 (old-params (quri:uri-query-params quri))
622 (new-params (loop with out = old-params
623 for (param value) on params by #'cddr
624 do (if value
625 (if-let (old-cons (assoc param out :test #'equal))
626 (setf (cdr old-cons) value)
627 (setf out (nconc out (list (cons param value)))))
628 (setf out (remove-if (lambda (x) (equal (car x) param)) out)))
629 finally (return out))))
630 (if new-params
631 (setf (quri:uri-query-params quri) new-params)
632 (setf (quri:uri-query quri) nil))
633 (quri:render-uri quri)))
635 (defun pagination-nav-bars (&key offset total with-next (items-per-page (user-pref :items-per-page)))
636 (if *preview*
637 (lambda (out-stream fn)
638 (declare (ignore out-stream))
639 (funcall fn))
640 (lambda (out-stream fn)
641 (labels ((pages-to-end (n) (< (+ offset (* items-per-page n)) total)))
642 (let* ((with-next (if total (pages-to-end 1) with-next))
643 (next (if (and offset with-next) (+ offset items-per-page)))
644 (prev (if (and offset (>= offset items-per-page)) (- offset items-per-page)))
645 (request-uri (hunchentoot:request-uri*))
646 (first-uri (if (and prev (> prev 0)) (replace-query-params request-uri "offset" nil)))
647 (prev-uri (if prev (replace-query-params request-uri "offset" (if (= prev 0) nil prev))))
648 (next-uri (if next (replace-query-params request-uri "offset" next)))
649 (last-uri (if (and total offset (pages-to-end 2))
650 (replace-query-params request-uri "offset" (- total (mod (- total 1) items-per-page) 1)))))
651 (if (or next prev last-uri)
652 (labels ((write-item (uri class title accesskey)
653 (format out-stream "<a href=\"~A\" class=\"button nav-item-~A~:[ disabled~;~]\" title=\"~A [~A]\" accesskey=\"~A\"></a>"
654 (or uri "#") class uri title accesskey accesskey)))
655 (format out-stream "<nav id='top-nav-bar'>")
656 (write-item first-uri "first" "First page" "\\")
657 (write-item prev-uri "prev" "Previous page" "[")
658 (format out-stream "<span class='page-number'><span class='page-number-label'>Page</span> ~A</span>" (+ 1 (/ (or offset 0) items-per-page)))
659 (write-item next-uri "next" "Next page" "]")
660 (write-item last-uri "last" "Last page" "/")
661 (format out-stream "</nav>")))
662 (funcall fn)
663 (nav-bar-outer out-stream nil (list :bottom-bar
664 (list-cond
665 (first-uri `("first" ,first-uri "Back to first"))
666 (prev-uri `("prev" ,prev-uri "Previous" :nofollow t))
667 (t `("top" "#top" "Back to top"))
668 (next-uri `("next" ,next-uri "Next" :nofollow t))
669 (last-uri `("last" ,last-uri "Last" :nofollow t)))))
670 (format out-stream "<script>document.querySelectorAll('#bottom-bar').forEach(bb => { bb.classList.add('decorative'); });</script>"))))))
672 (defun decode-json-as-hash-table (json-source)
673 (let (current-hash-table current-key)
674 (declare (special current-hash-table current-key))
675 (json:bind-custom-vars
676 (:beginning-of-object (lambda () (setf current-hash-table (make-hash-table :test 'equal)))
677 :object-key (lambda (x) (setf current-key x))
678 :object-value (lambda (x) (setf (gethash current-key current-hash-table) x))
679 :end-of-object (lambda () current-hash-table)
680 :aggregate-scope '(current-hash-table current-key))
681 (json:decode-json-from-source json-source))))
683 (defun get-ignore-hash (&optional (user-id (logged-in-userid)))
684 (if-let (ignore-json (and user-id (cache-get "user-ignore-list" user-id)))
685 (decode-json-as-hash-table ignore-json)
686 (make-hash-table :test 'equal)))
688 (defmacro with-outputs ((out-stream) &body body)
689 (with-gensyms (stream-sym)
690 (let ((out-body (map 'list (lambda (x) `(princ ,x ,stream-sym)) body)))
691 `(let ((,stream-sym ,out-stream))
692 ,.out-body))))
694 (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)
695 (declare (ignore return-code))
696 (ignore-errors
697 (log-conditions
698 (html-body out-stream
699 (lambda ()
700 (when top-nav (funcall top-nav))
701 (funcall pagination out-stream fn))
702 :title title :description description :social-description social-description :current-uri current-uri :content-class content-class :robots robots :extra-head extra-head))))
704 (defun set-cookie (key value &key (max-age (- (expt 2 31) 1)) (path "/"))
705 (hunchentoot:set-cookie key :value value :path path :max-age max-age :secure (site-secure *current-site*)))
707 (defun set-default-headers (return-code)
708 (setf (hunchentoot:content-type*) "text/html; charset=utf-8"
709 (hunchentoot:return-code*) return-code
710 (hunchentoot:header-out :link) (let ((output
711 (with-output-to-string (stream)
712 (with-delimited-writer (stream delimit :between ",")
713 (funcall lw2.resources::*link-header* stream delimit)))))
714 (when (> (length output) 0)
715 output)))
716 (unless lw2.resources::*push-option* (set-cookie "push" "t" :max-age (* 4 60 60))))
718 (defun user-pref (key)
719 (or (cdr (assoc key *current-prefs*))
720 (cdr (assoc key *default-prefs*))))
722 (defun set-user-pref (key value)
723 (assert (boundp 'hunchentoot:*reply*))
724 (if value
725 (setf *current-prefs* (remove-duplicates (acons key value *current-prefs*) :key #'car :from-end t))
726 (setf *current-prefs* (remove key *current-prefs* :key #'car)))
727 (set-cookie "prefs" (quri:url-encode (json:encode-json-to-string *current-prefs*))))
729 (defmacro emit-page ((out-stream &rest args &key (return-code 200) &allow-other-keys) &body body)
730 (once-only (return-code)
731 `(progn
732 (set-default-headers ,return-code)
733 (with-response-stream (,out-stream)
734 (dynamic-flet ((fn () ,@body))
735 (call-with-emit-page ,out-stream
736 #'fn
737 ,@args))))))
739 (defmethod call-with-backend-context ((backend backend-token-login) (request (eql t)) fn)
740 (let ((*current-auth-status* (safe-decode-json (hunchentoot:cookie-in "lw2-status"))))
741 (multiple-value-bind (*current-auth-token* *current-userid* *current-username*)
742 (let* ((auth-token (hunchentoot:cookie-in "lw2-auth-token"))
743 (expires (cdr (assoc :expires *current-auth-status*))))
744 (when (and (nonempty-string auth-token)
745 (not *read-only-mode*)
746 (or (null expires)
747 (and (integerp expires) (<= (get-unix-time) (- expires (* 60 60 24))))))
748 (with-cache-readonly-transaction
749 (values
750 auth-token
751 (cache-get "auth-token-to-userid" auth-token)
752 (cache-get "auth-token-to-username" auth-token)))))
753 (let ((*current-user-slug* (and *current-userid* (get-user-slug *current-userid*)))
754 (*enable-rate-limit* (if *current-userid* nil *enable-rate-limit*)))
755 (funcall fn)))))
757 (defmethod call-with-site-context ((site ignore-list-site) (request (eql t)) fn)
758 (call-next-method
759 site request
760 (lambda ()
761 (let ((*current-ignore-hash* (get-ignore-hash)))
762 (funcall fn)))))
764 (defun call-with-error-page (fn)
765 (with-response-context ()
766 (let* ((*current-prefs* (safe-decode-json (hunchentoot:cookie-in "prefs")))
767 (*preview* (string-equal (hunchentoot:get-parameter "format") "preview")))
768 (multiple-value-bind (*revalidate-default* *force-revalidate-default*)
769 (cond ((ppcre:scan "(?:^|,?)\\s*(?:no-cache|max-age=0)(?:$|,)" (hunchentoot:header-in* :cache-control))
770 (values t t))
771 (*preview*
772 (values nil nil))
774 (values t nil)))
775 (when (not *revalidate-default*)
776 (setf (hunchentoot:header-out :cache-control) (format nil "public, max-age=~A" (* 5 60))
777 (hunchentoot:header-out :vary) "cookie"))
778 (when (site-domain *current-site*)
779 (setf (hunchentoot:header-out :origin-agent-cluster) "?0")) ; Allow document.domain in Chrome: https://developer.chrome.com/blog/immutable-document-domain/
780 (let ((*memoized-output-without-hyphens*
781 ;; Soft hyphen characters mess up middle-click paste and screen readers, so try to identify whether they are necessary.
782 ;; See https://caniuse.com/?search=hyphens
783 (if-let ((ua (hunchentoot:header-in* :user-agent)))
784 (regex-case ua
785 (" Chrome/(\\d+)"
786 (declare (regex-groups-min 1))
787 (or (> (parse-integer (reg 0)) 87)
788 (ppcre:scan "Macintosh|Android" ua)))
789 (" Edge/(\\d+)"
790 (declare (regex-groups-min 1))
791 (> 19 (parse-integer (reg 0))))
792 (t t))
793 t)))
794 (with-page-resources
795 (catch 'abort-response
796 (handler-bind
797 ((fatal-error (lambda (condition)
798 (abort-response-if-unrecoverable condition)
799 (let ((error-html (with-output-to-string (*html-output*) (error-to-html condition))))
800 (emit-page (out-stream :title "Error" :return-code (condition-http-return-code condition) :content-class "error-page")
801 (write-string error-html out-stream)
802 (when (eq (hunchentoot:request-method*) :post)
803 <form method="post" class="error-retry-form">
804 (loop for (key . value) in (hunchentoot:post-parameters*)
805 do <input type="hidden" name=key value=value>)
806 <input type="submit" value="Retry">
807 </form>))
808 (return-from call-with-error-page)))))
809 (log-conditions
810 (if (or (eq (hunchentoot:request-method*) :post)
811 (not (and (boundp '*test-acceptor*) (boundp '*hunchentoot-taskmaster*)))) ; TODO fix this hack
812 (funcall fn)
813 (sb-sys:with-deadline (:seconds (expt 1.3
814 (min (round (log 30 1.3))
815 (- (hunchentoot:taskmaster-max-thread-count (symbol-value '*hunchentoot-taskmaster*))
816 (hunchentoot:acceptor-requests-in-progress (symbol-value '*test-acceptor*))))))
817 (funcall fn))))))))))))
819 (defmacro with-error-page (&body body)
820 `(dynamic-flet ((fn () ,@body)) (call-with-error-page #'fn)))
822 (defun output-form (out-stream method action id heading csrf-token fields button-label &key textarea end-html)
823 (format out-stream "<form method=\"~A\" action=\"~A\" id=\"~A\"><h1>~A</h1>" method action id heading)
824 (loop for (id label type . params) in fields
825 do (format out-stream "<label for=\"~A\">~A:</label>" id label)
826 do (cond
827 ((string= type "select")
828 (destructuring-bind (option-list &optional default) params
829 (format out-stream "<select name=\"~A\">" id)
830 (loop for (value label) in option-list
831 do (format out-stream "<option value=\"~A\"~:[~; selected~]>~A</option>" value (string= default value) label))
832 (format out-stream "</select>")))
834 (destructuring-bind (&optional (autocomplete "off") default) params
835 (format out-stream "<input type=\"~A\" name=\"~A\" autocomplete=\"~A\"~@[ value=\"~A\"~]>" type id autocomplete (and default (encode-entities default))))))
836 do (format out-stream ""))
837 (if textarea
838 (destructuring-bind (ta-name ta-contents) textarea
839 (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))))
840 (format out-stream "<input type=\"hidden\" name=\"csrf-token\" value=\"~A\"><input type=\"submit\" value=\"~A\">~@[~A~]</form>"
841 csrf-token button-label end-html))
843 (defun page-toolbar-to-html (&key title new-post new-conversation logout (rss t) ignore enable-push-notifications)
844 (unless *preview*
845 (let ((out-stream *html-output*)
846 (liu (logged-in-userid)))
847 (format out-stream "<div class=\"page-toolbar~@[ hide-until-init~]\">" enable-push-notifications)
848 (when logout
849 (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>"
850 (make-csrf-token)))
851 (when ignore
852 (funcall ignore))
853 (when enable-push-notifications
854 (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>"
855 (find-subscription *current-auth-token*)))
856 (when (and new-conversation liu)
857 (multiple-value-bind (text to)
858 (typecase new-conversation (string (values "Send private message" new-conversation)) (t "New conversation"))
859 (format out-stream "<a class=\"new-private-message button\" href=\"/conversation~@[?to=~A~]\">~A</a>"
860 to text)))
861 (when (and new-post liu)
862 (format out-stream "<a class=\"new-post button\" href=\"/edit-post~@[?section=~A~]\" accesskey=\"n\" title=\"Create new post [n]\">New post</a>"
863 (typecase new-post (string new-post) (t nil))))
864 (when (and title rss)
865 (format out-stream "<a class=\"rss\" rel=\"alternate\" type=\"application/rss+xml\" title=\"~A RSS feed\" href=\"~A\">RSS</a>"
866 title (replace-query-params (hunchentoot:request-uri*) "offset" nil "format" "rss")))
867 (format out-stream "</div>"))))
869 (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)
870 (alexandria:switch ((hunchentoot:get-parameter "format") :test #'string=)
871 ("rss"
872 (setf (hunchentoot:content-type*) "application/rss+xml; charset=utf-8")
873 (with-response-stream (out-stream)
874 (write-index-items-to-rss out-stream items :title title)))
876 (emit-page (out-stream :title (if hide-title nil title) :description (site-description *current-site*) :content-class content-class
877 :current-uri current-uri :robots (if (hunchentoot:get-parameter :offset) "noindex, nofollow")
878 :pagination pagination :top-nav top-nav :extra-head extra-head)
879 (if alternate-html
880 (funcall alternate-html)
881 (write-index-items-to-html out-stream items
882 :need-auth need-auth
883 :skip-section section))))))
885 (defun link-if-not (stream linkp url class text &key accesskey nofollow title)
886 (declare (dynamic-extent linkp url text))
887 (if (not linkp)
888 (format stream "<a href=\"~A\" class=\"~A\"~@[ accesskey=\"~A\"~]~:[~; rel=\"nofollow\"~]~@[ title=\"~A\"~]>~A</a>" url class accesskey nofollow title text)
889 (format stream "<span class=\"~A\"~@[ title=\"~A\"~]>~A</span>" class title text)))
891 (defgeneric main-site-link (site item-type item-designator &key)
892 (:method ((site lw2-frontend-site) (item-type (eql :post)) (post-id string) &key slug comment-id direct-comment-link)
893 (merge-uris
894 (format nil "/posts/~A/~A~[~;#~A~;?commentId=~A~]" post-id slug (if comment-id (if direct-comment-link 2 1) 0) comment-id)
895 (main-site-uri *current-site*)))
896 (:method ((site lw2-frontend-site) (item-type (eql :tag)) (slug string) &key comment-id direct-comment-link)
897 (when (not (and comment-id direct-comment-link))
898 (merge-uris
899 (format nil "/tag/~A~@[/discussion#~A~]" slug comment-id)
900 (main-site-uri *current-site*)))))
902 (defun postprocess-markdown (markdown)
903 (if (typep *current-site* 'alternate-frontend-site)
904 (regex-replace-body
905 ((concatenate 'string (regex-replace-all "\\." (site-uri *current-site*) "\\.") "posts/([^/ ]{17})/([^/# ]*)(?:(#comment-|/comment/|/answer/)([^/ ]{17}))?")
906 markdown)
907 (main-site-link *current-site*
908 :post (reg 0) :slug (reg 1) :comment-id (reg 3)
909 :direct-comment-link (and (reg 3) (reg 2) (string= "/" (reg 2) :end2 1))))
910 markdown))
912 (defun redirect (uri &key (type :see-other) preserve-query)
913 (setf (hunchentoot:return-code*) (ecase type (:see-other 303) (:permanent 301))
914 (hunchentoot:header-out "Location") (if-let ((query (and preserve-query (hunchentoot:query-string*))))
915 (quri:render-uri (quri:make-uri :defaults uri :query query))
916 uri)))
918 (defun main-site-redirect (uri &key (type :see-other))
919 (redirect (merge-uris uri (main-site-uri *current-site*)) :type type))
921 (defmacro request-method (&body method-clauses)
922 (with-gensyms (request-method)
923 `(let ((,request-method (hunchentoot:request-method*)))
924 (cond
925 ,.(loop for method-body in method-clauses
926 collect (destructuring-bind (method args &body inner-body) method-body
927 `(,(if (eq method :get) `(member ,request-method '(:get :head)) `(eq ,request-method ,method))
928 ,(make-binding-form (mapcar (lambda (x) (append (ensure-list x) `(:request-type ,method))) args)
929 inner-body))))))))
931 (defmacro define-page (name path-specifier additional-vars &body body)
932 (labels ((make-lambda (args)
933 (loop for a in args
934 collect (if (atom a) a (first a)))))
935 (multiple-value-bind (path-specifier-form path-bindings-wrapper specifier-vars)
936 (if (stringp path-specifier)
937 (values path-specifier #'identity)
938 (destructuring-bind (specifier-type specifier-body &rest specifier-args) path-specifier
939 (ecase specifier-type
940 (:function
941 (values `(lambda (r) (funcall ,specifier-body (hunchentoot:request-uri r)))
942 (if specifier-args
943 (lambda (body) `(ignorable-multiple-value-bind ,(make-lambda specifier-args) (funcall ,specifier-body (hunchentoot:request-uri*)) ,body))
944 #'identity)
945 specifier-args))
946 (:regex
947 (let ((fn `(lambda (r) (ppcre:scan-to-strings ,specifier-body (hunchentoot:request-uri r)))))
948 (values fn
949 (lambda (body)
950 (with-gensyms (result-vector)
951 `(let ((,result-vector (nth-value 1 (funcall ,fn hunchentoot:*request*))))
952 (declare (type simple-vector ,result-vector)
953 (ignorable ,result-vector))
954 (let
955 ,(loop for v in (make-lambda specifier-args) as x from 0 collecting `(,v (if (> (length ,result-vector) ,x) (aref ,result-vector ,x))))
956 ,body))))
957 specifier-args))))))
958 `(hunchentoot:define-easy-handler (,name :uri ,path-specifier-form) ()
959 (with-error-page
960 (block nil
961 ,(funcall path-bindings-wrapper
962 (make-binding-form (append (mapcar (lambda (x) (append (ensure-list x) '(:passthrough t))) specifier-vars) additional-vars)
963 body))))))))
965 (define-component sort-widget (&key (sort-options '((:new :description "Sort by date posted")
966 (:hot :description "Sort by time-weighted score")
967 (:active :description "Sort by date posted or last comment")
968 (:old :description "Sort by date posted, oldest first")))
969 (pref :default-sort) (param-name "sort") (html-class "sort"))
970 (:http-args ((sort :real-name param-name :member (mapcar (lambda (x) (if (listp x) (first x) x)) sort-options))
971 (sortedby :real-name "sortedBy" :type string)
972 &without-csrf-check))
973 (if sortedby
974 (progn
975 (renderer () nil)
976 sortedby)
977 (let ((sort-string (if sort (string-downcase sort))))
978 (if sort-string
979 (set-user-pref :default-sort sort-string))
980 (renderer ()
981 (sublevel-nav-to-html sort-options
982 (user-pref pref)
983 :param-name param-name
984 :extra-class html-class))
985 (or sort-string (user-pref pref)))))
987 (defun handle-last-modified (last-modified)
988 (when last-modified
989 (let ((last-modified (max last-modified (load-time-value (get-universal-time)))))
990 (setf (hunchentoot:header-out :last-modified) (hunchentoot:rfc-1123-date last-modified)
991 (hunchentoot:header-out :vary) "cookie")
992 (hunchentoot:handle-if-modified-since last-modified))))
994 (define-component view-index ()
995 (:http-args ((view :member '(:all :new :frontpage :featured :alignment-forum :questions :nominations :reviews :events) :default :frontpage)
996 before after
997 (offset :type fixnum)
998 (limit :type fixnum :default (user-pref :items-per-page))
999 (karma-threshold :type fixnum)
1000 &without-csrf-check))
1001 (when (eq view :new) (redirect (replace-query-params (hunchentoot:request-uri*) "view" "all" "all" nil) :type :permanent) (return))
1002 (component-value-bind ((sort-string sort-widget))
1003 (multiple-value-bind (posts total last-modified)
1004 (get-posts-index :view (string-downcase view) :before before :after after :offset offset :limit (1+ limit) :sort sort-string :karma-threshold karma-threshold)
1005 (handle-last-modified last-modified)
1006 (let ((page-title (format nil "~@(~A posts~)" view)))
1007 (renderer ()
1008 (view-items-index (firstn posts limit)
1009 :section view :title page-title :hide-title (eq view :frontpage)
1010 :pagination (pagination-nav-bars :offset (or offset 0) :total total :with-next (and (not total) (> (length posts) limit)))
1011 :content-class (format nil "index-page ~(~A~)-index-page" view)
1012 :top-nav (lambda ()
1013 (page-toolbar-to-html :title page-title
1014 :new-post (if (eq view :meta) "meta" t))
1015 (funcall sort-widget))))))))
1017 (defmacro route-component (name lambda-list &rest args)
1018 `(lambda ,lambda-list
1019 (with-error-page
1020 (component-value-bind ((() (,name ,@args)))
1021 (when ,name
1022 (funcall ,name))))))
1024 (defmacro define-component-routes (site-class &rest clauses)
1025 `(progn
1026 ,@(iter
1027 (for clause in clauses)
1028 (destructuring-bind (name (route-class &rest route-args) route-bindings (component-name &rest component-args)) clause
1029 (collect `(define-route ',site-class ',route-class
1030 :name ',name ,@route-args
1031 :handler (route-component ,component-name ,route-bindings ,@component-args)))))))
1033 (define-component-routes forum-site
1034 (view-root (standard-route :uri "/") () (view-index))
1035 (view-index (standard-route :uri "/index") () (view-index)))
1037 (hunchentoot:define-easy-handler
1038 (view-site-routes
1039 :uri (lambda (req)
1040 (declare (ignore req))
1041 (with-site-context ((let ((host (or (hunchentoot:header-in* :x-forwarded-host) (hunchentoot:header-in* :host))))
1042 (or (find-site host)
1043 (error "Unknown site: ~A" host))))
1044 (call-route-handler *current-site* (hunchentoot:script-name*)))))
1045 nil)
1047 (define-page view-post "/post" ((id :required t))
1048 (redirect (generate-item-link :post id) :type :permanent))
1050 (define-page view-post-lw1-link (:function #'match-lw1-link) ()
1051 (redirect (convert-lw1-link (hunchentoot:script-name*)) :preserve-query t :type :permanent))
1053 (define-page view-post-ea1-link (:function #'match-ea1-link) ()
1054 (redirect (convert-ea1-link (hunchentoot:script-name*)) :preserve-query t :type :permanent))
1056 (define-page view-post-lw2-slug-link (:function #'match-lw2-slug-link) ()
1057 (redirect (convert-lw2-slug-link (hunchentoot:request-uri*)) :type :see-other))
1059 (define-page view-post-lw2-sequence-link (:function #'match-lw2-sequence-link) ()
1060 (redirect (convert-lw2-sequence-link (hunchentoot:request-uri*)) :type :see-other))
1062 (define-page view-feed "/feed" ()
1063 (redirect "/?format=rss" :type :permanent))
1065 (define-page view-allposts "/allPosts" ()
1066 (redirect (format nil "/index~@[?~A~]" (hunchentoot:query-string*)) :type :see-other))
1068 (define-page view-nominations "/nominations" ()
1069 (redirect "/index?view=nominations" :type :see-other))
1071 (define-page view-reviews "/reviews" ()
1072 (redirect "/index?view=reviews" :type :see-other))
1074 (define-page view-review-voting "/reviewVoting" ()
1075 (redirect "https://www.lesswrong.com/reviewVoting" :type :see-other))
1077 (define-page view-coronavirus-link-database "/coronavirus-link-database" ()
1078 (redirect "https://www.lesswrong.com/coronavirus-link-database" :type :see-other))
1080 (defun post-comment (&key need-auth ((:post-id post-id-real)) ((:tag-id tag-id-real)) shortform)
1081 (request-method
1082 (: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)
1083 (let ((lw2-auth-token *current-auth-token*))
1084 (assert lw2-auth-token)
1085 (let* ((post-id (or post-id-real post-id))
1086 (tag-id (or tag-id-real tag-id))
1087 (question (when post-id (cdr (assoc :question (get-post-body post-id :auth-token lw2-auth-token)))))
1088 (new-comment-result
1089 (cond
1090 (text
1091 (let ((comment-data
1092 (list-cond
1093 (t :body (postprocess-markdown text))
1094 ((and post-id (not (or edit-comment-id (and shortform (not parent-comment-id))))) :post-id post-id)
1095 ((and tag-id (not edit-comment-id)) :tag-id tag-id)
1096 (parent-comment-id :parent-comment-id parent-comment-id)
1097 (answer :answer t)
1098 (nomination :nominated-for-review "2020")
1099 (nomination-review :reviewing-for-review "2020")
1100 (parent-answer-id :parent-answer-id parent-answer-id)
1101 (af :af t)
1102 ((and shortform (not parent-comment-id)) :shortform t))))
1103 (if edit-comment-id
1104 (do-lw2-comment-edit lw2-auth-token edit-comment-id comment-data)
1105 (do-lw2-comment lw2-auth-token comment-data))))
1106 (retract-comment-id
1107 (do-lw2-comment-edit lw2-auth-token retract-comment-id '((:retracted . t))))
1108 (unretract-comment-id
1109 (do-lw2-comment-edit lw2-auth-token unretract-comment-id '((:retracted . :false))))
1110 (delete-comment-id
1111 (do-lw2-comment-remove lw2-auth-token delete-comment-id :reason "Comment deleted by its author.")
1112 nil))))
1113 (when post-id
1114 (ignore-errors
1115 (get-post-comments post-id :force-revalidate t)
1116 (when question
1117 (get-post-answers post-id :force-revalidate t))))
1118 (when text
1119 (alist-bind ((new-comment-id simple-string :--id)
1120 (new-comment-html simple-string :html-body))
1121 new-comment-result
1122 (mark-comment-replied (alist* :parent-comment-id parent-comment-id :user-id *current-userid* new-comment-result))
1123 (setf (markdown-source :comment new-comment-id new-comment-html) text)
1124 (redirect (merge-uris (quri:make-uri :fragment (format nil "comment-~A" new-comment-id)
1125 :query (list-cond (need-auth "need-auth" "y")))
1126 (hunchentoot:request-uri*))))))))))
1128 (define-json-endpoint (view-karma-vote-post forum-site "/karma-vote/post")
1129 (let ((auth-token *current-auth-token*))
1130 (request-method
1131 (:get (post-id)
1132 (hash-cond (make-hash-table)
1133 (post-id "Post" (sethash (make-hash-table) post-id (get-post-vote post-id auth-token)))
1134 (post-id "Comment" (get-post-comments-votes post-id auth-token))
1135 (post-id "Tag" (get-post-tag-votes post-id auth-token)))))))
1137 (define-page view-post-lw2-link (:function #'match-lw2-link post-id comment-id * comment-link-type post-type)
1138 (need-auth
1139 chrono
1140 (show-comments :real-name "comments" :type boolean :default t)
1141 (format :type string))
1142 (request-method
1143 (:get ()
1144 (when (hunchentoot:get-parameter "commentId")
1145 (redirect (format nil "~A/comment/~A" (generate-item-link :post post-id) comment-id))
1146 (return))
1147 (let* ((lw2-auth-token *current-auth-token*)
1148 (preview (string-equal format "preview"))
1149 (show-comments (and (not preview) show-comments))
1150 (*enable-voting* (not (null (logged-in-userid)))))
1151 (multiple-value-bind (post title condition)
1152 (handler-case (nth-value 0 (get-post-body post-id :auth-token (and need-auth lw2-auth-token)))
1153 (serious-condition (c)
1154 (setf *enable-voting* nil)
1155 (values nil "[missing post]" c))
1156 (:no-error (post)
1157 (values post (cdr (assoc :title post)) nil)))
1158 (let* ((is-event (cdr (assoc :is-event post)))
1159 (correct-subtype (if is-event "event" "post")))
1160 (when (string/= post-type correct-subtype)
1161 (redirect (generate-item-link :post post :comment-id comment-id :item-subtype correct-subtype))
1162 (return)))
1163 (labels ((extra-head ()
1164 (when-let (canonical-source (or (and (not comment-id)
1165 (cdr (assoc :canonical-source post)))
1166 (and (always-canonical *current-site*)
1167 (main-site-link *current-site* :post post-id :slug (cdr (assoc :slug post))
1168 :comment-id comment-id :direct-comment-link t))))
1169 <link rel="canonical" href=canonical-source>)
1170 <script>postId=(with-html-stream-output (:stream stream) (json:encode-json post-id stream))</script>
1171 <script>alignmentForumPost=(if (cdr (assoc :af post)) "true" "false")</script>
1172 (when (logged-in-userid)
1173 (call-with-server-data 'process-vote-data (format nil "/karma-vote/post?post-id=~A" post-id))))
1174 (retrieve-individual-comment (comment-thread-type)
1175 (let* ((comments (case comment-thread-type
1176 (:comment (get-post-comments post-id))
1177 (:answer (get-post-answers post-id))))
1178 (target-comment (find comment-id comments :key (lambda (c) (cdr (assoc :--id c))) :test #'string=)))
1179 (values comments target-comment))))
1180 (if comment-id
1181 (let ((comment-thread-type (if (string= comment-link-type "answer") :answer :comment)))
1182 (multiple-value-bind (comments target-comment) (retrieve-individual-comment comment-thread-type)
1183 (unless target-comment
1184 ;; If the comment was not found, try as an answer, or vice versa.
1185 (setf comment-thread-type (if (eq comment-thread-type :comment) :answer :comment)
1186 (values comments target-comment) (retrieve-individual-comment comment-thread-type))
1187 (unless target-comment
1188 (error 'lw2-not-found-error)))
1189 (let* ((*comment-individual-link* t)
1190 (display-name (get-username (cdr (assoc :user-id target-comment))))
1191 (verb-phrase (cond
1192 ((and (eq comment-thread-type :answer)
1193 (not (cdr (assoc :parent-comment-id target-comment))))
1194 "answers")
1195 (t "comments on"))))
1196 (emit-page (out-stream :title (format nil "~A ~A ~A" display-name verb-phrase title)
1197 :content-class "individual-thread-page comment-thread-page"
1198 :social-description (when-let (x (cdr (assoc :html-body target-comment))) (extract-excerpt x))
1199 :extra-head #'extra-head)
1200 (unless preview
1201 (format out-stream "<h1 class=\"post-title\">~A ~A <a href=\"~A\">~A</a></h1>"
1202 (encode-entities display-name)
1203 verb-phrase
1204 (generate-item-link :post post-id)
1205 (clean-text-to-html title :hyphenation nil)))
1206 (output-comments out-stream "comment" comments target-comment :chrono chrono :preview preview)))))
1207 (let ((post-sequences (get-post-sequences post-id))
1208 (debate-responses (when (cdr (assoc :debate post))
1209 (get-post-debate-responses post-id))))
1210 (emit-page (out-stream :title title
1211 :content-class (format nil "post-page comment-thread-page~{ ~A~}"
1212 (list-cond ((cdr (assoc :question post)) "question-post-page")
1213 (post-sequences "in-sequence")
1214 ((not show-comments) "no-comments")))
1215 :social-description (when-let (x (cdr (assoc :html-body post))) (extract-excerpt x))
1216 :extra-head #'extra-head)
1217 (cond
1218 (condition
1219 (error-explanation-case (error-to-html condition)
1220 (lw2-not-allowed-error
1221 <p>This probably means the post has been deleted or moved back to the author's drafts.</p>)))
1223 (post-body-to-html (acons :debate-responses debate-responses post))))
1224 (when (and lw2-auth-token (equal (logged-in-userid) (cdr (assoc :user-id post))))
1225 (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>"
1226 (cdr (assoc :--id post))))
1227 (alist-bind (fm-crosspost foreign-post) post
1228 (alist-bind (is-crosspost hosted-here) fm-crosspost
1229 (when is-crosspost
1230 (if-let (crosspost-site-host (backend-magnum-crosspost-site *current-backend*))
1231 (let* ((*current-site* (find-site crosspost-site-host))
1232 (crosspost-site-title (main-site-title *current-site*)))
1233 (alist-bind (comment-count base-score) foreign-post
1234 <a class="crosspost" href=(generate-item-link :post foreign-post :absolute t)>Crossposted (if hosted-here "to" "from") (progn crosspost-site-title)
1235 \ \((safe (pretty-number (or base-score 0) "point")), (safe (pretty-number (or comment-count 0) "comment"))\)</a>))
1236 (error "Could not retrieve crossposted post. magnum-crosspost-site not configured.")))))
1237 (post-nav-links post post-sequences)
1238 (activate-client-trigger "postLoaded")
1239 (when show-comments
1240 (write-string "<script> </script>" out-stream)
1241 (finish-output out-stream)
1242 (with-error-html-block ()
1243 ;; Temporary hack to support nominations
1244 (let* ((real-comments (get-post-comments post-id))
1245 (answers (when (cdr (assoc :question post))
1246 (get-post-answers post-id)))
1247 (posted-at (and (typep *current-backend* 'backend-lw2)
1248 (cdr (assoc :posted-at post))))
1249 (posted-timestamp (and posted-at (local-time:parse-timestring posted-at)))
1250 (now (local-time:now))
1251 (nominations-open nil)
1252 (reviews-eligible (timerange "2020-01-01" posted-timestamp "2021-01-01"))
1253 (reviews-open (and reviews-eligible (timerange "2021-12-14" now "2022-01-11"))))
1254 (labels ((top-level-property (comment property)
1255 (or (cdr (assoc property comment))
1256 (cdr (assoc property (cdr (assoc :top-level-comment comment)))))))
1257 (multiple-value-bind (normal-comments nominations reviews)
1258 (loop for comment in real-comments
1259 if (top-level-property comment :nominated-for-review)
1260 collect comment into nominations
1261 else if (top-level-property comment :reviewing-for-review)
1262 collect comment into reviews
1263 else
1264 collect comment into normal-comments
1265 finally (return (values normal-comments nominations reviews)))
1266 (unless (or nominations reviews)
1267 (setf normal-comments real-comments)) ;for caching
1268 (loop for (name comments open) in (list-cond ((or nominations nominations-open)
1269 (list "nomination" nominations nominations-open))
1270 ((or reviews reviews-open)
1271 (list "review" reviews reviews-open))
1272 ((cdr (assoc :question post))
1273 (list "answer" answers t))
1275 (list "comment" normal-comments t)))
1276 do (output-comments out-stream name comments nil
1277 :replies-open open
1278 :overcomingbias-sort (cdr (assoc :comment-sort-order post)) :chrono chrono :preview preview))))))))))))))
1279 (:post ()
1280 (post-comment :post-id post-id :need-auth need-auth))))
1282 (defparameter *edit-post-template* (compile-template* "edit-post.html"))
1284 (define-page view-edit-post "/edit-post" (title url section tags post-id link-post)
1285 (request-method
1286 (:get ()
1287 (let* ((csrf-token (make-csrf-token))
1288 (post-body (if post-id (get-post-body post-id :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1289 (section (or section (loop for (sym . sec) in '((:draft . "drafts") (:meta . "meta") (:frontpage-date . "frontpage"))
1290 if (cdr (assoc sym post-body)) return sec
1291 finally (return "all")))))
1292 (emit-page (out-stream :title (if post-id "Edit Post" "New Post") :content-class "edit-post-page")
1293 (render-template* *edit-post-template* out-stream
1294 :csrf-token csrf-token
1295 :title (cdr (assoc :title post-body))
1296 :url (cdr (assoc :url post-body))
1297 :question (cdr (assoc :question post-body))
1298 :tags-supported (typep *current-backend* 'backend-accordius)
1299 :tags (when (and post-id (typep *current-backend* 'backend-accordius)) (do-wl-rest-query (format nil "posts/~a/update_tagset/" post-id) '()))
1300 :post-id post-id
1301 :section-list (loop for (name desc) in '(("all" "All") ("meta" "Meta") ("frontpage" "Frontpage") ("drafts" "Drafts"))
1302 when (or (string= name section) (member name '("drafts" "all") :test #'string=))
1303 collect (alist :name name :desc desc :selected (string= name section)))
1304 :lesswrong-misc (typep *current-backend* 'backend-lw2-misc-features)
1305 :submit-to-frontpage (if post-id (cdr (assoc :submit-to-frontpage post-body)) t)
1306 :markdown-source (or (and post-id (markdown-source :post post-id (cdr (assoc :html-body post-body)))) "")))))
1307 (:post (text question submit-to-frontpage)
1308 (let ((lw2-auth-token *current-auth-token*)
1309 (url (if (string= url "") nil url)))
1310 (assert lw2-auth-token)
1311 (let* ((post-data
1312 (list-cond
1313 (t :body (postprocess-markdown text))
1314 (t :title (or (nonempty-string title) "Untitled"))
1315 (link-post :url url)
1316 (t :meta (or (string= section "meta") :false))
1317 ((not post-id) :is-event nil)
1318 (t :draft (or (string= section "drafts") :false))
1319 ((typep *current-backend* 'backend-lw2-misc-features) :submit-to-frontpage (and submit-to-frontpage t))
1320 ((not post-id) :question (if question t :false))))
1321 (post-unset
1322 (list-cond
1323 ((not link-post) :url t)))
1324 (new-post-data
1325 (if post-id
1326 (do-lw2-post-edit lw2-auth-token post-id post-data post-unset)
1327 (do-lw2-post lw2-auth-token post-data)))
1328 (new-post-id (cdr (assoc :--id new-post-data))))
1329 (assert new-post-id)
1330 (when (typep *current-backend* 'backend-accordius)
1331 (do-wl-rest-mutate :post
1332 (format nil "posts/~a/update_tagset/" post-id)
1333 (alist "tags" tags)
1334 lw2-auth-token))
1335 (setf (markdown-source :post new-post-id (cdr (assoc :html-body new-post-data))) text)
1336 (ignore-errors (get-post-body post-id :force-revalidate t))
1337 (redirect (if (js-true (cdr (assoc :draft post-data)))
1338 (concatenate 'string (generate-item-link :post new-post-data) "?need-auth=y")
1339 (generate-item-link :post new-post-data))))))))
1341 (define-json-endpoint (view-karma-vote forum-site "/karma-vote")
1342 (let ((auth-token *current-auth-token*))
1343 (request-method
1344 (:post (target target-type (vote-json :real-name "vote"))
1345 (let ((vote (safe-decode-json vote-json)))
1346 (multiple-value-bind (current-vote result)
1347 (do-lw2-vote auth-token target-type target vote)
1348 (alist-bind (vote-count base-score af af-base-score extended-score) result
1349 (let ((vote-buttons (vote-buttons base-score
1350 :as-text t
1351 :af-score (and af af-base-score)
1352 :vote-count (+ vote-count (if (member (cdr (assoc :karma current-vote)) '(nil "neutral") :test #'equal)
1355 :extended-score extended-score))
1356 (out (make-hash-table)))
1357 (loop for (axis . axis-vote) in current-vote
1358 do (setf (gethash axis out) (list* axis-vote (gethash axis vote-buttons))))
1359 out))))))))
1361 (delete-easy-handler 'view-karma-vote)
1363 (define-json-endpoint (view-user-status login-site "/current-user-status")
1364 (let ((auth-token *current-auth-token*))
1365 (request-method
1366 (:get ()
1367 (if (lw2-graphql-query (graphql-query-string "currentUser" nil '(:--id)) :auth-token auth-token)
1368 (sethash (make-hash-table)
1369 "notifications" (check-notifications (logged-in-userid) auth-token)
1370 "alignmentForumAllowed" (member "alignmentForum" (cdr (assoc :groups (get-user :user-id (logged-in-userid)))) :test #'string=))
1371 (with-cache-transaction
1372 (cache-del "auth-token-to-userid" auth-token)
1373 (cache-del "auth-token-to-username" auth-token)))))))
1375 (hunchentoot:define-easy-handler (view-check-notifications :uri "/check-notifications") (format)
1376 (with-error-page
1377 (setf (hunchentoot:content-type*) "application/json")
1378 (if *current-auth-token*
1379 (let ((notifications-status (check-notifications (logged-in-userid) *current-auth-token* :full (string= format "push"))))
1380 (json:encode-json-to-string notifications-status)))))
1382 (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)
1383 (with-error-page
1384 (check-csrf-token csrf-token)
1385 (let ((user-id (logged-in-userid)))
1386 (unless user-id (error "Not logged in."))
1387 (with-cache-transaction
1388 (let ((ignore-hash (get-ignore-hash user-id)))
1389 (if (string= state "ignore")
1390 (setf (gethash target-id ignore-hash) t)
1391 (remhash target-id ignore-hash))
1392 (cache-put "user-ignore-list" user-id ignore-hash :value-type :json))))
1393 (when return
1394 (redirect return))))
1396 (client-defun comment-controls (&key standalone parent-comment-id parent-answer-id edit-comment-id)
1397 (flet ((inner ()
1398 <form method="post" id="conversation-form" class="aligned-form">
1399 <div class="textarea-container">
1400 <textarea name="text" oninput="enableBeforeUnload();"></textarea>
1401 <span class="markdown-reference-link">You can use <a href="http://commonmark.org/help/" target="_blank">Markdown</a> here.</span>
1402 <button type="button" class="guiedit-mobile-auxiliary-button guiedit-mobile-help-button">Help</button>
1403 <button type="button" class="guiedit-mobile-auxiliary-button guiedit-mobile-exit-button">Exit</button>
1404 </div>
1405 <div>
1406 (macrolet ((hidden-var (name)
1407 `(when ,name <input type="hidden" name=,(string-downcase name) value=,name>)))
1408 (hidden-var parent-comment-id)
1409 (hidden-var parent-answer-id)
1410 (hidden-var edit-comment-id))
1411 <input name="csrf-token" value=(make-csrf-token) type="hidden">
1412 <input value="Submit" type="submit">
1413 </div>
1414 </form>))
1415 (if standalone
1416 <div class="posting-controls standalone with-markdown-editor" onsubmit="disableBeforeUnload();">(with-html-stream-output (inner))</div>
1417 (inner))))
1419 (define-json-endpoint (view-karma-vote-shortform shortform-site "/karma-vote/shortform")
1420 (let ((auth-token *current-auth-token*))
1421 (request-method
1422 (:get ((offset :type fixnum :default 0))
1423 (sethash (make-hash-table)
1424 "Comment" (get-shortform-votes auth-token :offset offset))))))
1426 (define-component view-comments-index (index-type)
1427 (:http-args ((offset :type fixnum)
1428 (limit :type fixnum)
1429 (view :member '(nil :alignment-forum))))
1430 (request-method
1431 (:get ()
1432 (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.
1433 (shortform (eq index-type :shortform))
1434 (with-voting (not (null (and shortform (logged-in-userid))))))
1435 (multiple-value-bind (title query-view top-nav)
1436 (cond
1437 (shortform (values "Shortform" "shortform" (if (logged-in-userid) (lambda () (comment-controls :standalone t)))))
1438 (t (values (case view (:alignment-forum "Alignment Forum recent comments") (t "Recent comments")) "allRecentComments" nil)))
1439 (multiple-value-bind (recent-comments total last-modified)
1440 (if (or (not (eq index-type :recent-comments)) offset limit view (/= (user-pref :items-per-page) 20))
1441 (let ((*use-alignment-forum* (eq view :alignment-forum)))
1442 (lw2-graphql-query (lw2-query-string :comment :list
1443 (remove nil (alist :view query-view
1444 :limit (or limit (user-pref :items-per-page)) :offset offset)
1445 :key #'cdr)
1446 :context (if shortform :shortform :index)
1447 :with-total want-total)))
1448 (get-recent-comments :with-total want-total))
1449 (handle-last-modified last-modified)
1450 (renderer ()
1451 (view-items-index recent-comments
1452 :title title
1453 :extra-head (lambda ()
1454 (when with-voting
1455 (call-with-server-data 'process-vote-data (format nil "/karma-vote/shortform?offset=~A" (or offset 0)))))
1456 :content-class (if shortform "index-page shortform-index-page comment-thread-page" "index-page comment-index-page")
1457 :pagination (pagination-nav-bars :offset (or offset 0) :with-next (not want-total) :total (if want-total total))
1458 :top-nav (lambda () (page-toolbar-to-html :title title) (when top-nav (funcall top-nav)))
1459 :alternate-html (if (eq index-type :shortform)
1460 (lambda ()
1461 (let ((*enable-voting* with-voting))
1462 <div class="comments">
1463 (comment-tree-to-html *html-output*
1464 (make-comment-parent-hash
1465 (flatten-shortform-comments recent-comments)))
1466 </div>)))))))))
1467 (:post ()
1468 (post-comment :shortform t))))
1470 (define-component-routes forum-site (view-recent-comments (standard-route :uri "/recentcomments") () (view-comments-index :recent-comments)))
1471 (define-component-routes shortform-site (view-shortform (standard-route :uri "/shortform") () (view-comments-index :shortform)))
1473 (delete-easy-handler 'view-recent-comments)
1475 (defun tag-to-html (tag &key skip-headline)
1476 (schema-bind (:tag tag :auto :context :body)
1477 (alist-bind (edited-at html user-id) description
1478 (unless skip-headline
1479 <h1 class="post-title">(safe (clean-text-to-html name))</h1>
1480 <div class="post-meta">
1481 <span>(if core "Core ")(if wiki-only "Wiki" "Tag")</span>
1482 (when (and (nonempty-string edited-at) (nonempty-string user-id))
1483 <span>Last edit: (pretty-time-html edited-at)
1484 \ by <a class="author" href=("/users/~A" (get-user-slug user-id))>(get-username user-id)</a>
1485 </span>)
1486 </div>)
1487 (when html
1488 <div class="tag-description body-text">(with-html-stream-output (:stream stream) (let ((*memoized-output-stream* stream)) (clean-html* html)))</div>))))
1490 (defun tag-list-to-html (tags)
1491 <ul class="tag-list">
1492 (iter (for tag in tags)
1493 (schema-bind (:tag tag :auto :context :index)
1494 <li><a class="post-title-link" href=("/tag/~A" slug)>(safe (clean-text-to-html name))(if wiki-only
1495 " (wiki)"
1496 (if post-count (format nil " (~A)" post-count)))</a></li>))
1497 </ul>)
1499 (define-json-endpoint (view-user-autocomplete forum-site "/-user-autocomplete")
1500 (request-method
1501 (:get (q)
1502 (lw2-search-query q :indexes '(:users)))))
1504 (define-json-endpoint (view-karma-vote-tag forum-site "/karma-vote/tag")
1505 (let ((auth-token *current-auth-token*))
1506 (request-method
1507 (:get (tag-id post-id)
1508 (hash-cond (make-hash-table)
1509 (tag-id "Post" (get-tag-post-votes tag-id auth-token))
1510 (tag-id "Comment" (get-tag-comments-votes tag-id auth-token))
1511 (post-id "Tag" (get-post-tag-votes post-id auth-token)))))))
1513 (define-component view-tag (slug tail)
1514 (:http-args ((sort :default :relevant :member '(:relevant :new :old))))
1515 (when (nonempty-string tail)
1516 (redirect (format nil "/tag/~A" slug))
1517 (return))
1518 (let ((tag (first (lw2-graphql-query (lw2-query-string :tag :list (alist :view "tagBySlug" :slug slug) :context :body)))))
1519 (unless tag
1520 (error 'lw2-not-found-error))
1521 (request-method
1522 (:get ()
1523 (let* ((posts (get-tag-posts slug))
1524 (posts (if (eq sort :relevant) posts (sort-items posts sort))))
1525 (schema-bind (:tag tag :auto :context :body)
1526 (renderer ()
1527 (view-items-index posts
1528 :title (format nil "~A tag" name)
1529 :extra-head (lambda ()
1530 (when-let (canonical-source (and (always-canonical *current-site*)
1531 (main-site-link *current-site* :tag slug)))
1532 <link rel="canonical" href=canonical-source>)
1533 (when (logged-in-userid)
1534 (call-with-server-data 'process-vote-data (format nil "/karma-vote/tag?tag-id=~A" tag-id))))
1535 :top-nav (lambda ()
1536 (page-toolbar-to-html :title name :rss (not wiki-only))
1537 (tag-to-html tag)
1538 (when (and posts (not *preview*))
1539 (sublevel-nav-to-html '(:relevant :new :old)
1540 sort
1541 :default :relevant
1542 :param-name "sort"
1543 :extra-class "sort")))
1544 :content-class "index-page tag-index-page"
1545 :alternate-html (lambda ()
1546 (unless wiki-only
1547 (write-index-items-to-html *html-output* posts))
1548 (when (typep *current-backend* 'backend-lw2-tags-comments)
1549 (finish-output *html-output*)
1550 (let ((*enable-voting* (not (null (logged-in-userid))))
1551 (comments (lw2-graphql-query (lw2-query-string :comment :list (alist :view "tagDiscussionComments" :tag-id tag-id)))))
1552 (output-comments *html-output* "comment" comments nil :replies-open t)))))))))
1553 (:post ()
1554 (schema-bind (:tag tag (tag-id))
1555 (renderer ()
1556 (post-comment :tag-id tag-id)))))))
1558 (define-component-routes forum-site (view-tag (regex-route :regex "^/(?:tag|topics)/([^/?]+)(/[^/?]*)?") (slug tail) (view-tag slug tail)))
1560 (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/"))))
1562 (define-component view-tags-index ()
1563 (:http-args ())
1564 (multiple-value-bind (all-tags portal)
1565 (lw2-graphql-query-multi
1566 (list (lw2-query-string* :tag :list (alist :view "allTagsAlphabetical"))
1567 (lw2-query-string* :tag :list (alist :view "tagBySlug" :slug "portal") :context :body)))
1568 (let ((core-tags
1569 (iter (for tag in all-tags)
1570 (schema-bind (:tag tag (core))
1571 (when core (collect tag)))))
1572 (title (if (typep *current-site* 'lesswrong-viewer-site) "Concepts Portal" "Tags Portal")))
1573 (renderer ()
1574 (emit-page (out-stream :title title)
1575 <article>
1576 <h1 class="post-title">(safe title)</h1>
1577 (tag-to-html (first portal) :skip-headline t)
1578 </article>
1579 (iter (for (title . tags) in (alist "Core Tags" core-tags "All Tags" all-tags))
1580 (progn
1581 <h1>(safe title)</h1>
1582 (tag-list-to-html tags))))))))
1584 (define-component-routes forum-site (view-tags-index (standard-route :uri "/tags") () (view-tags-index)))
1585 (define-component-routes forum-site (view-tags-index-alt (standard-route :uri "/topics") () (view-tags-index)))
1587 (define-route 'forum-site 'standard-route :name 'view-tags-index-redirect :uri "/tags/all" :handler (lambda () (redirect "/tags")))
1588 (define-route 'forum-site 'standard-route :name 'view-tags-index-redirect :uri "/topics/all" :handler (lambda () (redirect "/topics")))
1590 (define-route 'alternate-frontend-site 'standard-route :name 'view-tags-voting-redirect :uri "/tagVoting" :handler (lambda () (main-site-redirect "/tagVoting")))
1591 (define-route 'alternate-frontend-site 'standard-route :name 'view-tags-dashboard-redirect :uri "/tags/dashboard" :handler (lambda () (main-site-redirect "/tags/dashboard")))
1593 (hunchentoot:define-easy-handler (view-push-register :uri "/push/register") ()
1594 (with-error-page
1595 (let* ((data (call-with-safe-json (lambda ()
1596 (json:decode-json-from-string
1597 (hunchentoot:raw-post-data :force-text t :external-format :utf-8)))))
1598 (subscription (cdr (assoc :subscription data)))
1599 (cancel (cdr (assoc :cancel data))))
1600 (cond
1601 (subscription
1602 (make-subscription *current-auth-token*
1603 (cdr (assoc :endpoint subscription))
1604 (cdr (assoc :expires *current-auth-status*)))
1605 (send-notification (cdr (assoc :endpoint subscription)) :ttl 120))
1606 (cancel
1607 (delete-subscription *current-auth-token*)))
1608 nil)))
1610 (hunchentoot:define-easy-handler (view-inbox-redirect :uri "/push/go-inbox") ()
1611 (with-error-page
1612 (redirect (format nil "/users/~A?show=inbox" *current-user-slug*))))
1614 (define-page view-user (:regex "^/users/(.*?)(?:$|\\?)|^/user" user-slug) (id
1615 (offset :type fixnum :default 0)
1616 (show :member '(:all :posts :comments :drafts :conversations :inbox) :default :all)
1617 (sort :member '(:top :new :old) :default :new))
1618 (let* ((auth-token (if (eq show :inbox) *current-auth-token*))
1619 (user-info
1620 (let* ((ui (get-user (cond (user-slug :user-slug) (id :user-id)) (or user-slug id) :auth-token auth-token))
1621 (canonical-slug (cdr (assoc :slug ui))))
1622 (when (and user-slug
1623 canonical-slug
1624 (not (string-equal user-slug canonical-slug)))
1625 (return-from view-user (redirect (format nil "/users/~A" canonical-slug))))
1626 (if (and (not (cdr (assoc :deleted ui))) (cdr (assoc :--id ui)))
1628 (error 'lw2-user-not-found-error))))
1629 (user-id (cdr (assoc :--id user-info)))
1630 (own-user-page (logged-in-userid user-id))
1631 (display-name (if user-slug (cdr (assoc :display-name user-info)) user-id))
1632 (show-text (if (not (eq show :all)) (string-capitalize show)))
1633 (title (format nil "~A~@['s ~A~]" display-name show-text))
1634 (sort-type (case sort (:top :score) (:new :date) (:old :date-reverse))))
1635 (multiple-value-bind (items total last-modified)
1636 (case show
1637 (:posts
1638 (get-user-page-items user-id :posts :offset offset :limit (+ 1 (user-pref :items-per-page)) :sort-type sort-type))
1639 (:comments
1640 (get-user-page-items user-id :comments :offset offset :limit (+ 1 (user-pref :items-per-page)) :sort-type sort-type))
1641 (:drafts
1642 (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")))
1643 (:conversations
1644 (let ((conversations
1645 (lw2-graphql-query (lw2-query-string :conversation :list
1646 (alist :view "userConversations" :limit (+ 1 (user-pref :items-per-page)) :offset offset :user-id user-id)
1647 :fields '(:--id :created-at :title (:participants :display-name :slug) :----typename))
1648 :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1649 (lw2-graphql-query-map
1650 (lambda (c)
1651 (lw2-query-string* :message :total (alist :view "messagesConversation" :conversation-id (cdr (assoc :--id c)))))
1652 conversations
1653 :postprocess (lambda (c result)
1654 (acons :messages-total result c))
1655 :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1656 (:inbox
1657 (error-explanation-case
1658 (prog1
1659 (let ((notifications (get-notifications :user-id user-id :offset offset :auth-token (hunchentoot:cookie-in "lw2-auth-token")))
1660 (last-check (ignore-errors (local-time:parse-timestring (cdr (assoc :last-notifications-check user-info))))))
1661 (labels ((check-new (key obj)
1662 (if (ignore-errors (local-time:timestamp< last-check (local-time:parse-timestring (cdr (assoc key obj)))))
1663 (acons :highlight-new t obj)
1664 obj))
1665 (check-replied (comment)
1666 (let* ((post-id (cdr (assoc :post-id comment)))
1667 (comment-id (cdr (assoc :--id comment)))
1668 (reply-comment-id (check-comment-replied comment-id user-id)))
1669 (if reply-comment-id
1670 (acons :replied (list :post post-id :comment-id reply-comment-id) comment)
1671 comment))))
1672 (lw2-graphql-query-map
1673 (lambda (n)
1674 (alexandria:switch ((cdr (assoc :document-type n)) :test #'string=)
1675 ("comment"
1676 (lw2-query-string* :comment :single
1677 (alist :document-id (cdr (assoc :document-id n)))
1678 :context :index))
1679 ("post"
1680 (lw2-query-string* :post :single (alist :document-id (cdr (assoc :document-id n)))))
1681 ("message"
1682 (lw2-query-string* :message :single (alist :document-id (cdr (assoc :document-id n)))
1683 :fields *messages-index-fields*))
1685 (values n t))))
1686 notifications
1687 :postprocess (lambda (n result)
1688 (if result
1689 (funcall (if (string= (cdr (assoc :document-type n)) "comment") #'check-replied #'identity)
1690 (check-new
1691 (alexandria:switch ((cdr (assoc :document-type n)) :test #'string=)
1692 ("comment" :posted-at)
1693 ("post" :posted-at)
1694 ("message" :created-at))
1695 result))
1697 :auth-token auth-token)))
1698 (do-user-edit
1699 (hunchentoot:cookie-in "lw2-auth-token")
1700 user-id
1701 (alist :last-notifications-check (timestamp-to-graphql (local-time:now)))))
1702 (lw2-not-allowed-error
1703 <p>This may mean your login token has expired or become invalid. You can try <a href="/login">logging in again</a>.</p>)))
1705 (get-user-page-items user-id :both :offset offset :limit (+ 1 (user-pref :items-per-page)) :sort-type sort-type)))
1706 (handle-last-modified last-modified)
1707 (let ((with-next (> (length items) (+ (if (eq show :all) offset 0) (user-pref :items-per-page))))
1708 (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
1709 (view-items-index interleave :title title
1710 :content-class (format nil "user-page~@[ ~A-user-page~]~:[~; own-user-page~]" (string-downcase show) own-user-page)
1711 :current-uri (format nil "/users/~A" user-slug)
1712 :section :personal
1713 :pagination (pagination-nav-bars :offset offset :total total :with-next (if (not total) with-next))
1714 :need-auth (eq show :drafts) :section (if (eq show :drafts) "drafts" nil)
1715 :top-nav (lambda ()
1716 (page-toolbar-to-html :title title
1717 :enable-push-notifications (eq show :inbox)
1718 :rss (not (member show '(:drafts :conversations :inbox)))
1719 :new-post (if (eq show :drafts) "drafts" t)
1720 :new-conversation (if own-user-page t user-slug)
1721 :ignore (if (and (logged-in-userid) (not own-user-page))
1722 (lambda ()
1723 (let ((ignored (gethash user-id *current-ignore-hash*)))
1724 <form method="post" action="/ignore-user">
1725 <button class=("button ~A" (if ignored "unignore-button" "ignore-button"))>(if ignored "Unignore user" "Ignore user")</button>
1726 <input type="hidden" name="csrf-token" value=(make-csrf-token)>
1727 <input type="hidden" name="target-id" value=user-id>
1728 <input type="hidden" name="state" value=(if ignored "unignore" "ignore")>
1729 <input type="hidden" name="return" value=(hunchentoot:request-uri*)>
1730 </form>)))
1731 :logout own-user-page)
1732 (alist-bind ((actual-id string :--id)
1733 (actual-slug string :slug)
1734 (karma (or null fixnum))
1735 (af-karma (or null fixnum)))
1736 user-info
1737 <h1 class="page-main-heading"
1738 (when (not own-user-page)
1739 (format nil "data-~:[~;anti-~]~:*kibitzer-redirect=~:[/users/~*~A~;/user?id=~A~]"
1740 user-slug actual-id actual-slug))>
1741 (progn display-name)
1742 (let ((full-name (get-user-full-name user-id)))
1743 (when (and user-slug (stringp full-name) (> (length full-name) 0))
1744 <span class="user-full-name">\((progn full-name)\)</span>))
1745 </h1>
1746 <div class="user-stats">
1747 Karma:
1748 <span class="karma-type">
1749 <span class="karma-total">(if user-slug (pretty-number (or karma 0)) "##")</span>(if af-karma " (LW),")
1750 </span>\
1751 (when af-karma
1752 <span class="karma-type">
1753 <span class="karma-total af-karma-total">(if user-slug (pretty-number (or af-karma 0)) "##")</span> \(AF\)
1754 </span>)
1755 </div>
1756 (when-let (html-bio (cdr (assoc :html-bio user-info)))
1757 <div class="user-bio body-text">
1758 (with-html-stream-output (:stream stream)
1759 (let ((*memoized-output-stream* stream))
1760 (clean-html* html-bio)))
1761 </div>))
1762 (sublevel-nav-to-html `(:all :posts :comments
1763 ,@(if own-user-page
1764 '(:drafts :conversations :inbox)))
1765 show
1766 :default :all)
1767 (when (member show '(:all :posts :comments))
1768 (sublevel-nav-to-html '(:new :top :old)
1769 sort
1770 :default :new
1771 :param-name "sort"
1772 :extra-class "sort"))))))))
1774 (defparameter *conversation-template* (compile-template* "conversation.html"))
1776 (define-page view-conversation "/conversation" (id to subject)
1777 (request-method
1778 (:get ()
1779 (cond
1780 ((and id to) (error "This is an invalid URL."))
1782 (multiple-value-bind (conversation messages)
1783 (get-conversation-messages id (hunchentoot:cookie-in "lw2-auth-token"))
1784 (let ((conversation (rectify-conversation conversation)))
1785 (view-items-index (nreverse messages) :content-class "conversation-page" :need-auth t :title (encode-entities (cdr (assoc :title conversation)))
1786 :top-nav (lambda () (render-template* *conversation-template* *html-output*
1787 :conversation conversation :csrf-token (make-csrf-token)))))))
1789 (emit-page (out-stream :title "New conversation" :content-class "conversation-page")
1790 (render-template* *conversation-template* out-stream
1791 :to to
1792 :subject subject
1793 :csrf-token (make-csrf-token))))))
1794 (:post ((text :required t))
1795 (let* ((id (or id
1796 (let ((participant-ids (list (logged-in-userid) (cdar (lw2-graphql-query (lw2-query-string :user :single (alist :slug to) :fields '(:--id)))))))
1797 (do-create-conversation (hunchentoot:cookie-in "lw2-auth-token") (alist :participant-ids participant-ids :title subject))))))
1798 (do-create-message (hunchentoot:cookie-in "lw2-auth-token") id text)
1799 (redirect (format nil "/conversation?id=~A" id))))))
1801 (define-page view-search "/search" ((q :required t)
1802 (sort :default :relevant :member '(:relevant :new :old)))
1803 (let ((*current-search-query* q)
1804 (link (presentable-link q :search))
1805 (title (format nil "~@[~A - ~]Search" q)))
1806 (declare (special *current-search-query*))
1807 (if link
1808 (redirect link)
1809 (multiple-value-bind (results tags) (lw2-search-query q)
1810 (let* ((sort (if (string= (hunchentoot:get-parameter "format") "rss")
1811 :new
1812 sort))
1813 (results (if (eq sort :relevant)
1814 results
1815 (sort-items results sort)))
1816 (results (if (hunchentoot:get-parameter "format")
1817 (firstn results 20)
1818 results)))
1819 (view-items-index results
1820 :top-nav (lambda ()
1821 (page-toolbar-to-html :title title :rss t)
1822 (sublevel-nav-to-html '(:relevant :new :old)
1823 sort
1824 :default :relevant
1825 :param-name "sort"
1826 :extra-class "sort")
1827 (when tags
1828 <h1>Tags</h1>
1829 (tag-list-to-html (firstn tags 20))))
1830 :content-class "index-page search-results-page" :current-uri "/search"
1831 :title title))))))
1833 (defgeneric view-login (backend))
1835 (defmethod view-login ((backend backend-password-login))
1836 (with-http-args (return cookie-check
1837 (login-username :request-type :post) (login-password :request-type :post)
1838 (signup-username :request-type :post) (signup-email :request-type :post) (signup-password :request-type :post) (signup-password2 :request-type :post))
1839 (labels
1840 ((emit-login-page (&key error-message)
1841 (let ((csrf-token (make-csrf-token)))
1842 (emit-page (out-stream :title "Log in" :current-uri "/login" :content-class "login-page" :robots "noindex, nofollow")
1843 (when error-message
1844 (format out-stream "<div class=\"error-box\">~A</div>" error-message))
1845 (with-outputs (out-stream) "<div class=\"login-container\">")
1846 (output-form out-stream "post" (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))) "login-form" "Log in" csrf-token
1847 '(("login-username" "Username" "text" "username")
1848 ("login-password" "Password" "password" "current-password"))
1849 "Log in"
1850 :end-html (when (typep *current-backend* 'backend-websocket-login) ;other backends not supported yet
1851 "<a href=\"/reset-password\">Forgot password</a>"))
1852 (output-form out-stream "post" (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))) "signup-form" "Create account" csrf-token
1853 '(("signup-username" "Username" "text" "username")
1854 ("signup-email" "Email" "text" "email")
1855 ("signup-password" "Password" "password" "new-password")
1856 ("signup-password2" "Confirm password" "password" "new-password"))
1857 "Create account")
1858 (if-let (main-site-title (main-site-title *current-site*))
1859 (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>"
1860 main-site-title))
1861 (format out-stream "</div>"))))
1862 (finish-login (username user-id auth-token error-message &optional expires)
1863 (cond
1864 (auth-token
1865 (set-cookie "lw2-auth-token" auth-token :max-age (if expires (+ (- expires (get-unix-time)) (* 24 60 60)) (1- (expt 2 31))))
1866 (if expires (set-cookie "lw2-status" (json:encode-json-to-string (alist :expires expires))))
1867 (cache-put "auth-token-to-userid" auth-token user-id)
1868 (cache-put "auth-token-to-username" auth-token username)
1869 (redirect (if (and return (ppcre:scan "^/[^/]" return)) return "/")))
1871 (emit-login-page :error-message error-message)))))
1872 (cond
1873 ((not (or cookie-check (hunchentoot:cookie-in "session-token")))
1874 (set-cookie "session-token" (base64:usb8-array-to-base64-string (ironclad:make-random-salt)))
1875 (redirect (format nil "/login?~@[return=~A&~]cookie-check=y" (if return (url-rewrite:url-encode return)))))
1876 (cookie-check
1877 (if (hunchentoot:cookie-in "session-token")
1878 (redirect (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))))
1879 (emit-page (out-stream :title "Log in" :current-uri "/login")
1880 (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))))))
1881 (login-username
1882 (cond
1883 ((or (string= login-username "") (string= login-password "")) (emit-login-page :error-message "Please enter a username and password"))
1884 ((lw2.dnsbl:dnsbl-check (hunchentoot:real-remote-addr)) (emit-login-page :error-message "Your IP address is blacklisted."))
1885 (t (multiple-value-call #'finish-login login-username (do-login login-username login-password)))))
1886 (signup-username
1887 (cond
1888 ((not (every (lambda (x) (not (string= x ""))) (list signup-username signup-email signup-password signup-password2)))
1889 (emit-login-page :error-message "Please fill in all fields"))
1890 ((not (string= signup-password signup-password2))
1891 (emit-login-page :error-message "Passwords do not match"))
1892 ((lw2.dnsbl:dnsbl-check (hunchentoot:real-remote-addr)) (emit-login-page :error-message "Your IP address is blacklisted."))
1893 (t (multiple-value-call #'finish-login signup-username (do-lw2-create-user signup-username signup-email signup-password)))))
1895 (emit-login-page))))))
1897 (defmethod view-logout ((backend backend-password-login))
1898 (request-method
1899 (:post ()
1900 (set-cookie "lw2-auth-token" "" :max-age 0)
1901 (do-logout *current-auth-token*)
1902 (redirect "/"))))
1904 (defparameter *reset-password-template* (compile-template* "reset-password.html"))
1906 (define-component basic-reset-password ()
1907 (:http-args ((email :request-type :post) (reset-link :request-type :post) (password :request-type :post) (password2 :request-type :post)))
1908 (renderer ()
1909 (labels ((emit-rpw-page (&key message message-type step)
1910 (let ((csrf-token (make-csrf-token)))
1911 (emit-page (out-stream :title "Reset password" :content-class "reset-password" :robots "noindex, nofollow")
1912 (render-template* *reset-password-template* out-stream
1913 :csrf-token csrf-token
1914 :reset-link reset-link
1915 :message message
1916 :message-type message-type
1917 :step step)))))
1918 (cond
1919 (email
1920 (multiple-value-bind (ret error)
1921 (do-lw2-forgot-password email)
1922 (declare (ignore ret))
1923 (if error
1924 (emit-rpw-page :step 1 :message error :message-type "error")
1925 (emit-rpw-page :step 1 :message "Password reset email sent." :message-type "success"))))
1926 (reset-link
1927 (ppcre:register-groups-bind (reset-token) ("(?:reset-password/|^)([^/#]+)$" reset-link)
1928 (cond
1929 ((not reset-token)
1930 (emit-rpw-page :step 2 :message "Invalid password reset link." :message-type "error"))
1931 ((not (string= password password2))
1932 (emit-rpw-page :step 2 :message "Passwords do not match." :message-type "error"))
1934 (multiple-value-bind (user-id auth-token error-message) (do-lw2-reset-password reset-token password)
1935 (declare (ignore user-id auth-token))
1936 (cond
1937 (error-message (emit-rpw-page :step 2 :message error-message :message-type "error"))
1939 (with-error-page (emit-page (out-stream :title "Reset password" :content-class "reset-password")
1940 (format out-stream "<h1>Password reset complete</h1><p>You can now <a href=\"/login\">log in</a> with your new password.</p>"))))))))))
1942 (emit-rpw-page))))))
1944 (define-route 'login-site 'standard-route :name 'view-login :uri "/login" :handler (lambda () (with-error-page (view-login *current-backend*))))
1945 (define-route 'login-site 'standard-route :name 'view-login-oauth2.0-callback :uri "/auth/callback" :handler (lambda () (with-error-page (view-login-oauth2.0-callback *current-backend*))))
1947 (define-route 'login-site 'standard-route :name 'view-logout :uri "/logout" :handler (lambda () (with-error-page (view-logout *current-backend*))))
1949 (define-component-routes login-site
1950 (basic-reset-password (standard-route :uri "/reset-password") () (basic-reset-password)))
1952 (defun oauth2.0-login-request-uri (backend path &optional query)
1953 (quri:render-uri
1954 (quri:merge-uris
1955 (quri:make-uri :path path :query query)
1956 (quri:uri (oauth2.0-login-uri backend)))))
1958 (defmethod view-login ((backend backend-oauth2.0-login))
1959 (with-http-args (return)
1960 (set-cookie "session-token" (base64:usb8-array-to-base64-string (ironclad:make-random-salt)))
1961 (redirect
1962 (oauth2.0-login-request-uri backend "authorize"
1963 (alist "response_type" "code"
1964 "client_id" (oauth2.0-client-id backend)
1965 "redirect_uri" (quri:render-uri (quri:merge-uris (quri:uri "/auth/callback") (quri:uri (site-uri *current-site*))))
1966 "scope" "openid profile email"
1967 "state" return)))))
1969 (defmethod view-login-oauth2.0-callback ((backend backend-oauth2.0-login))
1970 (with-http-args (code state)
1971 (let ((auth-response
1972 (call-with-http-response #'json:decode-json
1973 (oauth2.0-login-request-uri backend "oauth/token")
1974 :method :post
1975 :content (alist "grant_type" "authorization_code"
1976 "client_id" (oauth2.0-client-id backend)
1977 "client_secret" (oauth2.0-client-secret backend)
1978 "code" code
1979 "redirect_uri" (quri:render-uri (quri:merge-uris (quri:uri "/auth/callback") (quri:uri (site-uri *current-site*)))))
1980 :want-stream t :force-string t)))
1981 (alist-bind ((access-token (or null simple-string) :access--token)
1982 (error (or null simple-string))
1983 (error-description (or null simple-string) :error--description))
1984 auth-response
1985 (when error
1986 (error "Login error: ~A" (cdr (assoc :error--description auth-response))))
1987 (unless access-token
1988 (error "Login error: server did not provide an access token."))
1989 (let ((auth-token (do-login-with-oidc-access-token access-token)))
1990 (alist-bind ((user-id simple-string :--id)
1991 (username simple-string :display-name))
1992 (do-lw2-post-query
1993 auth-token (alist "query"
1994 (graphql-query-string :current-user nil '(:--id :display-name))))
1995 (cache-put "auth-token-to-userid" auth-token user-id)
1996 (cache-put "auth-token-to-username" auth-token username))
1997 (set-cookie "lw2-auth-token" auth-token :max-age (1- (expt 2 31)))
1998 (redirect (if (and state (ppcre:scan "^/[^/]" state)) state "/")))))))
2000 (defmethod view-logout ((backend backend-oauth2.0-login))
2001 (request-method
2002 (:post ()
2003 (set-cookie "lw2-auth-token" "" :max-age 0)
2004 (redirect
2005 (oauth2.0-login-request-uri backend "v2/logout" (alist "client_id" (oauth2.0-client-id backend)))))))
2007 (delete-easy-handler 'view-login)
2008 (delete-easy-handler 'view-logout)
2009 (delete-easy-handler 'view-reset-password)
2011 (define-page view-library "/library"
2012 ((view :member '(:featured :community) :default :featured))
2013 (let ((sequences
2014 (lw2-graphql-query
2015 (lw2-query-string :sequence :list
2016 (alist :view (case view
2017 (:featured "curatedSequences")
2018 (:community "communitySequences")))
2019 :fields '(:--id :created-at :user-id :title :----typename)))))
2020 (view-items-index
2021 sequences
2022 :title "Sequences Library"
2023 :content-class "sequences-page"
2024 :current-uri "/library"
2025 :top-nav (lambda ()
2026 (sublevel-nav-to-html '(:featured :community)
2027 view
2028 :default :featured
2029 :param-name "view"
2030 :extra-class "sequences-view")))))
2032 (define-page view-sequence (:regex "^/s(?:equences)?/([^/?#]+)(?:/?$|\\?)" sequence-id) ()
2033 (let ((sequence (get-sequence sequence-id)))
2034 (alist-bind ((title string))
2035 sequence
2036 (emit-page (out-stream
2037 :title title
2038 :content-class "sequence-page")
2039 (sequence-to-html sequence)))))
2041 (define-component view-collection (collection-id) ()
2042 (let ((collection (get-collection collection-id)))
2043 (renderer ()
2044 (emit-page (out-stream :title (cdr (assoc :title collection)) :content-class "sequence-page collection-page")
2045 (collection-to-html collection)))))
2047 (define-component-routes lesswrong-viewer-site (view-sequences (standard-route :uri "/sequences") () (view-collection "oneQyj4pw77ynzwAF")))
2048 (define-component-routes lesswrong-viewer-site (view-codex (standard-route :uri "/codex") () (view-collection "2izXHCrmJ684AnZ5X")))
2049 (define-component-routes lesswrong-viewer-site (view-hpmor (standard-route :uri "/hpmor") () (view-collection "ywQvGBSojSQZTMpLh")))
2050 (define-component-routes ea-forum-viewer-site (view-handbook (standard-route :uri "/handbook") () (view-collection "MobebwWs2o86cS9Rd")))
2052 (define-component-routes forum-site (view-tags-index (standard-route :uri "/tags") () (view-tags-index)))
2054 (define-page view-archive (:regex "^/archive(?:/(\\d{4})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))"
2055 (year :type (mod 10000))
2056 (month :type (integer 1 12))
2057 (day :type (integer 1 31)))
2058 ((offset :type fixnum :default 0))
2059 (local-time:with-decoded-timestamp (:day current-day :month current-month :year current-year :timezone local-time:+utc-zone+) (local-time:now)
2060 (local-time:with-decoded-timestamp (:day earliest-day :month earliest-month :year earliest-year :timezone local-time:+utc-zone+) (earliest-post-time)
2061 (labels ((url-elements (&rest url-elements)
2062 (declare (dynamic-extent url-elements))
2063 (format nil "/~{~A~^/~}" url-elements))
2064 (archive-nav ()
2065 (let ((out-stream *html-output*))
2066 (with-outputs (out-stream) "<div class=\"archive-nav\"><div class=\"archive-nav-years\">")
2067 (link-if-not out-stream (not (or year month day)) (url-elements "archive") "archive-nav-item-year" "All")
2068 (loop for y from earliest-year to current-year
2069 do (link-if-not out-stream (eq y year) (url-elements "archive" y) "archive-nav-item-year" y))
2070 (format out-stream "</div>")
2071 (when year
2072 (format out-stream "<div class=\"archive-nav-months\">")
2073 (link-if-not out-stream (not month) (url-elements "archive" year) "archive-nav-item-month" "All")
2074 (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)
2075 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)))
2076 (format out-stream "</div>"))
2077 (when month
2078 (format out-stream "<div class=\"archive-nav-days\">")
2079 (link-if-not out-stream (not day) (url-elements "archive" year month) "archive-nav-item-day" "All")
2080 (loop for d from (if (and (= (or year current-year) earliest-year) (= (or month current-month) earliest-month)) earliest-day 1)
2081 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)))
2082 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))
2083 (format out-stream "</div>"))
2084 (format out-stream "</div>"))))
2085 (multiple-value-bind (posts total)
2086 (lw2-graphql-query (lw2-query-string :post :list
2087 (alist :view (if day "new" "top") :limit 51 :offset offset
2088 :after (if (and year (not day)) (format nil "~A-~A-~A" (or year earliest-year) (or month 1) (or day 1)))
2089 :before (if year (format nil "~A-~A-~A" (or year current-year) (or month 12)
2090 (or day (local-time:days-in-month (or month 12) (or year current-year))))))))
2091 (emit-page (out-stream :title "Archive" :current-uri "/archive" :content-class "archive-page"
2092 :top-nav #'archive-nav
2093 :pagination (pagination-nav-bars :items-per-page 50 :offset offset :total total :with-next (if total nil (> (length posts) 50))))
2094 (write-index-items-to-html out-stream (firstn posts 50) :empty-message "No posts for the selected period.")))))))
2096 (define-page view-about "/about" ()
2097 (emit-page (out-stream :title "About" :current-uri "/about" :content-class "about-page")
2098 (alexandria:with-input-from-file (in-stream "www/about.html" :element-type '(unsigned-byte 8))
2099 (alexandria:copy-stream in-stream out-stream))))
2101 (define-page misc-pages (:regex "^/misc-pages/.+") ()
2102 (let ((pathname (hunchentoot:request-pathname)))
2103 (unless (probe-file pathname)
2104 (error 'lw2-not-found-error))
2105 (emit-page (out-stream :title "Misc page" :content-class "misc-page")
2106 (alexandria:with-input-from-file (in-stream pathname :element-type '(unsigned-byte 8))
2107 (alexandria:copy-stream in-stream out-stream)))))
2109 (define-page view-generated-script (:regex "^/generated/([^/]+)\\.js" (name :type string)) ()
2110 (when-let ((package (find-package (string-upcase name))))
2111 (setf (hunchentoot:header-out "Content-Type") "text/javascript")
2112 (let ((stream (make-flexi-stream (hunchentoot:send-headers) :external-format :utf-8)))
2113 (write-package-client-scripts package stream))))
2115 (hunchentoot:define-easy-handler
2116 (view-proxy-asset
2117 :uri (lambda (r)
2118 (with-error-page
2119 (multiple-value-bind (match? strings) (ppcre:scan-to-strings "^/proxy-assets/([0-9A-Za-z]+)(-inverted)?$" (hunchentoot:script-name r) :sharedp t)
2120 (when-let* ((base-filename (and match? (svref strings 0)))
2121 (image-data (cache-get "cached-images" base-filename :value-type :json)))
2122 (let ((inverted (svref strings 1)))
2123 (alist-bind ((mime-type simple-string)) image-data
2124 (setf (hunchentoot:header-out "X-Content-Type-Options") "nosniff"
2125 (hunchentoot:header-out "Cache-Control") #.(format nil "public, max-age=~A, immutable" 600))
2126 (hunchentoot:handle-static-file (concatenate 'string "www/proxy-assets/" base-filename (if inverted "-inverted" "")) mime-type)
2127 t)))))))
2128 nil)