Remove leading asterisks from link URLs.
[lw2-viewer.git] / lw2.lisp
blobb4d2c74b45512c4c2e6a4d3be2f0d2bba742e635
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 "GPTBot|ClaudeBot|GoogleOther|AmazonBot|facebookexternalhit" (hunchentoot:header-in* :user-agent))
770 ;; Low priority bots
771 (values nil nil))
772 ((ppcre:scan "(?:^|,?)\\s*(?:no-cache|max-age=0)(?:$|,)" (hunchentoot:header-in* :cache-control))
773 (values t t))
774 (*preview*
775 (values nil nil))
777 (values t nil)))
778 (when (not *revalidate-default*)
779 (setf (hunchentoot:header-out :cache-control) (format nil "public, max-age=~A" (* 5 60))
780 (hunchentoot:header-out :vary) "cookie"))
781 (when (site-domain *current-site*)
782 (setf (hunchentoot:header-out :origin-agent-cluster) "?0")) ; Allow document.domain in Chrome: https://developer.chrome.com/blog/immutable-document-domain/
783 (let ((*memoized-output-without-hyphens*
784 ;; Soft hyphen characters mess up middle-click paste and screen readers, so try to identify whether they are necessary.
785 ;; See https://caniuse.com/?search=hyphens
786 (if-let ((ua (hunchentoot:header-in* :user-agent)))
787 (regex-case ua
788 (" Chrome/(\\d+)"
789 (declare (regex-groups-min 1))
790 (or (> (parse-integer (reg 0)) 87)
791 (ppcre:scan "Macintosh|Android" ua)))
792 (" Edge/(\\d+)"
793 (declare (regex-groups-min 1))
794 (> 19 (parse-integer (reg 0))))
795 (t t))
796 t)))
797 (with-page-resources
798 (catch 'abort-response
799 (handler-bind
800 ((fatal-error (lambda (condition)
801 (abort-response-if-unrecoverable condition)
802 (let ((error-html (with-output-to-string (*html-output*) (error-to-html condition))))
803 (emit-page (out-stream :title "Error" :return-code (condition-http-return-code condition) :content-class "error-page")
804 (write-string error-html out-stream)
805 (when (eq (hunchentoot:request-method*) :post)
806 <form method="post" class="error-retry-form">
807 (loop for (key . value) in (hunchentoot:post-parameters*)
808 do <input type="hidden" name=key value=value>)
809 <input type="submit" value="Retry">
810 </form>))
811 (return-from call-with-error-page)))))
812 (log-conditions
813 (if (or (eq (hunchentoot:request-method*) :post)
814 (not (and (boundp '*test-acceptor*) (boundp '*hunchentoot-taskmaster*)))) ; TODO fix this hack
815 (funcall fn)
816 (sb-sys:with-deadline (:seconds (expt 1.3
817 (min (round (log 30 1.3))
818 (- (hunchentoot:taskmaster-max-thread-count (symbol-value '*hunchentoot-taskmaster*))
819 (hunchentoot:acceptor-requests-in-progress (symbol-value '*test-acceptor*))))))
820 (funcall fn))))))))))))
822 (defmacro with-error-page (&body body)
823 `(dynamic-flet ((fn () ,@body)) (call-with-error-page #'fn)))
825 (defun output-form (out-stream method action id heading csrf-token fields button-label &key textarea end-html)
826 (format out-stream "<form method=\"~A\" action=\"~A\" id=\"~A\"><h1>~A</h1>" method action id heading)
827 (loop for (id label type . params) in fields
828 do (format out-stream "<label for=\"~A\">~A:</label>" id label)
829 do (cond
830 ((string= type "select")
831 (destructuring-bind (option-list &optional default) params
832 (format out-stream "<select name=\"~A\">" id)
833 (loop for (value label) in option-list
834 do (format out-stream "<option value=\"~A\"~:[~; selected~]>~A</option>" value (string= default value) label))
835 (format out-stream "</select>")))
837 (destructuring-bind (&optional (autocomplete "off") default) params
838 (format out-stream "<input type=\"~A\" name=\"~A\" autocomplete=\"~A\"~@[ value=\"~A\"~]>" type id autocomplete (and default (encode-entities default))))))
839 do (format out-stream ""))
840 (if textarea
841 (destructuring-bind (ta-name ta-contents) textarea
842 (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))))
843 (format out-stream "<input type=\"hidden\" name=\"csrf-token\" value=\"~A\"><input type=\"submit\" value=\"~A\">~@[~A~]</form>"
844 csrf-token button-label end-html))
846 (defun page-toolbar-to-html (&key title new-post new-conversation logout (rss t) ignore enable-push-notifications)
847 (unless *preview*
848 (let ((out-stream *html-output*)
849 (liu (logged-in-userid)))
850 (format out-stream "<div class=\"page-toolbar~@[ hide-until-init~]\">" enable-push-notifications)
851 (when logout
852 (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>"
853 (make-csrf-token)))
854 (when ignore
855 (funcall ignore))
856 (when enable-push-notifications
857 (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>"
858 (find-subscription *current-auth-token*)))
859 (when (and new-conversation liu)
860 (multiple-value-bind (text to)
861 (typecase new-conversation (string (values "Send private message" new-conversation)) (t "New conversation"))
862 (format out-stream "<a class=\"new-private-message button\" href=\"/conversation~@[?to=~A~]\">~A</a>"
863 to text)))
864 (when (and new-post liu)
865 (format out-stream "<a class=\"new-post button\" href=\"/edit-post~@[?section=~A~]\" accesskey=\"n\" title=\"Create new post [n]\">New post</a>"
866 (typecase new-post (string new-post) (t nil))))
867 (when (and title rss)
868 (format out-stream "<a class=\"rss\" rel=\"alternate\" type=\"application/rss+xml\" title=\"~A RSS feed\" href=\"~A\">RSS</a>"
869 title (replace-query-params (hunchentoot:request-uri*) "offset" nil "format" "rss")))
870 (format out-stream "</div>"))))
872 (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)
873 (alexandria:switch ((hunchentoot:get-parameter "format") :test #'string=)
874 ("rss"
875 (setf (hunchentoot:content-type*) "application/rss+xml; charset=utf-8")
876 (with-response-stream (out-stream)
877 (write-index-items-to-rss out-stream items :title title)))
879 (emit-page (out-stream :title (if hide-title nil title) :description (site-description *current-site*) :content-class content-class
880 :current-uri current-uri :robots (if (hunchentoot:get-parameter :offset) "noindex, nofollow")
881 :pagination pagination :top-nav top-nav :extra-head extra-head)
882 (if alternate-html
883 (funcall alternate-html)
884 (write-index-items-to-html out-stream items
885 :need-auth need-auth
886 :skip-section section))))))
888 (defun link-if-not (stream linkp url class text &key accesskey nofollow title)
889 (declare (dynamic-extent linkp url text))
890 (if (not linkp)
891 (format stream "<a href=\"~A\" class=\"~A\"~@[ accesskey=\"~A\"~]~:[~; rel=\"nofollow\"~]~@[ title=\"~A\"~]>~A</a>" url class accesskey nofollow title text)
892 (format stream "<span class=\"~A\"~@[ title=\"~A\"~]>~A</span>" class title text)))
894 (defgeneric main-site-link (site item-type item-designator &key)
895 (:method ((site lw2-frontend-site) (item-type (eql :post)) (post-id string) &key slug comment-id direct-comment-link)
896 (merge-uris
897 (format nil "/posts/~A/~A~[~;#~A~;?commentId=~A~]" post-id slug (if comment-id (if direct-comment-link 2 1) 0) comment-id)
898 (main-site-uri *current-site*)))
899 (:method ((site lw2-frontend-site) (item-type (eql :tag)) (slug string) &key comment-id direct-comment-link)
900 (when (not (and comment-id direct-comment-link))
901 (merge-uris
902 (format nil "/tag/~A~@[/discussion#~A~]" slug comment-id)
903 (main-site-uri *current-site*)))))
905 (defun postprocess-markdown (markdown)
906 (if (typep *current-site* 'alternate-frontend-site)
907 (regex-replace-body
908 ((concatenate 'string (regex-replace-all "\\." (site-uri *current-site*) "\\.") "posts/([^/ ]{17})/([^/# ]*)(?:(#comment-|/comment/|/answer/)([^/ ]{17}))?")
909 markdown)
910 (main-site-link *current-site*
911 :post (reg 0) :slug (reg 1) :comment-id (reg 3)
912 :direct-comment-link (and (reg 3) (reg 2) (string= "/" (reg 2) :end2 1))))
913 markdown))
915 (defun redirect (uri &key (type :see-other) preserve-query)
916 (setf (hunchentoot:return-code*) (ecase type (:see-other 303) (:permanent 301))
917 (hunchentoot:header-out "Location") (if-let ((query (and preserve-query (hunchentoot:query-string*))))
918 (quri:render-uri (quri:make-uri :defaults uri :query query))
919 uri)))
921 (defun main-site-redirect (uri &key (type :see-other))
922 (redirect (merge-uris uri (main-site-uri *current-site*)) :type type))
924 (defmacro request-method (&body method-clauses)
925 (with-gensyms (request-method)
926 `(let ((,request-method (hunchentoot:request-method*)))
927 (cond
928 ,.(loop for method-body in method-clauses
929 collect (destructuring-bind (method args &body inner-body) method-body
930 `(,(if (eq method :get) `(member ,request-method '(:get :head)) `(eq ,request-method ,method))
931 ,(make-binding-form (mapcar (lambda (x) (append (ensure-list x) `(:request-type ,method))) args)
932 inner-body))))))))
934 (defmacro define-page (name path-specifier additional-vars &body body)
935 (labels ((make-lambda (args)
936 (loop for a in args
937 collect (if (atom a) a (first a)))))
938 (multiple-value-bind (path-specifier-form path-bindings-wrapper specifier-vars)
939 (if (stringp path-specifier)
940 (values path-specifier #'identity)
941 (destructuring-bind (specifier-type specifier-body &rest specifier-args) path-specifier
942 (ecase specifier-type
943 (:function
944 (values `(lambda (r) (funcall ,specifier-body (hunchentoot:request-uri r)))
945 (if specifier-args
946 (lambda (body) `(ignorable-multiple-value-bind ,(make-lambda specifier-args) (funcall ,specifier-body (hunchentoot:request-uri*)) ,body))
947 #'identity)
948 specifier-args))
949 (:regex
950 (let ((fn `(lambda (r) (ppcre:scan-to-strings ,specifier-body (hunchentoot:request-uri r)))))
951 (values fn
952 (lambda (body)
953 (with-gensyms (result-vector)
954 `(let ((,result-vector (nth-value 1 (funcall ,fn hunchentoot:*request*))))
955 (declare (type simple-vector ,result-vector)
956 (ignorable ,result-vector))
957 (let
958 ,(loop for v in (make-lambda specifier-args) as x from 0 collecting `(,v (if (> (length ,result-vector) ,x) (aref ,result-vector ,x))))
959 ,body))))
960 specifier-args))))))
961 `(hunchentoot:define-easy-handler (,name :uri ,path-specifier-form) ()
962 (with-error-page
963 (block nil
964 ,(funcall path-bindings-wrapper
965 (make-binding-form (append (mapcar (lambda (x) (append (ensure-list x) '(:passthrough t))) specifier-vars) additional-vars)
966 body))))))))
968 (define-component sort-widget (&key (sort-options '((:new :description "Sort by date posted")
969 (:hot :description "Sort by time-weighted score")
970 (:active :description "Sort by date posted or last comment")
971 (:old :description "Sort by date posted, oldest first")))
972 (pref :default-sort) (param-name "sort") (html-class "sort"))
973 (:http-args ((sort :real-name param-name :member (mapcar (lambda (x) (if (listp x) (first x) x)) sort-options))
974 (sortedby :real-name "sortedBy" :type string)
975 &without-csrf-check))
976 (if sortedby
977 (progn
978 (renderer () nil)
979 sortedby)
980 (let ((sort-string (if sort (string-downcase sort))))
981 (if sort-string
982 (set-user-pref :default-sort sort-string))
983 (renderer ()
984 (sublevel-nav-to-html sort-options
985 (user-pref pref)
986 :param-name param-name
987 :extra-class html-class))
988 (or sort-string (user-pref pref)))))
990 (defun handle-last-modified (last-modified)
991 (when last-modified
992 (let ((last-modified (max last-modified (load-time-value (get-universal-time)))))
993 (setf (hunchentoot:header-out :last-modified) (hunchentoot:rfc-1123-date last-modified)
994 (hunchentoot:header-out :vary) "cookie")
995 (hunchentoot:handle-if-modified-since last-modified))))
997 (define-component view-index ()
998 (:http-args ((view :member '(:all :new :frontpage :featured :alignment-forum :questions :nominations :reviews :events) :default :frontpage)
999 before after
1000 (offset :type fixnum)
1001 (limit :type fixnum :default (user-pref :items-per-page))
1002 (karma-threshold :type fixnum)
1003 &without-csrf-check))
1004 (when (eq view :new) (redirect (replace-query-params (hunchentoot:request-uri*) "view" "all" "all" nil) :type :permanent) (return))
1005 (component-value-bind ((sort-string sort-widget))
1006 (multiple-value-bind (posts total last-modified)
1007 (get-posts-index :view (string-downcase view) :before before :after after :offset offset :limit (1+ limit) :sort sort-string :karma-threshold karma-threshold)
1008 (handle-last-modified last-modified)
1009 (let ((page-title (format nil "~@(~A posts~)" view)))
1010 (renderer ()
1011 (view-items-index (firstn posts limit)
1012 :section view :title page-title :hide-title (eq view :frontpage)
1013 :pagination (pagination-nav-bars :offset (or offset 0) :total total :with-next (and (not total) (> (length posts) limit)))
1014 :content-class (format nil "index-page ~(~A~)-index-page" view)
1015 :top-nav (lambda ()
1016 (page-toolbar-to-html :title page-title
1017 :new-post (if (eq view :meta) "meta" t))
1018 (funcall sort-widget))))))))
1020 (defmacro route-component (name lambda-list &rest args)
1021 `(lambda ,lambda-list
1022 (with-error-page
1023 (component-value-bind ((() (,name ,@args)))
1024 (when ,name
1025 (funcall ,name))))))
1027 (defmacro define-component-routes (site-class &rest clauses)
1028 `(progn
1029 ,@(iter
1030 (for clause in clauses)
1031 (destructuring-bind (name (route-class &rest route-args) route-bindings (component-name &rest component-args)) clause
1032 (collect `(define-route ',site-class ',route-class
1033 :name ',name ,@route-args
1034 :handler (route-component ,component-name ,route-bindings ,@component-args)))))))
1036 (define-component-routes forum-site
1037 (view-root (standard-route :uri "/") () (view-index))
1038 (view-index (standard-route :uri "/index") () (view-index)))
1040 (hunchentoot:define-easy-handler
1041 (view-site-routes
1042 :uri (lambda (req)
1043 (declare (ignore req))
1044 (with-site-context ((let ((host (or (hunchentoot:header-in* :x-forwarded-host) (hunchentoot:header-in* :host))))
1045 (or (find-site host)
1046 (error "Unknown site: ~A" host))))
1047 (call-route-handler *current-site* (hunchentoot:script-name*)))))
1048 nil)
1050 (define-page view-post "/post" ((id :required t))
1051 (redirect (generate-item-link :post id) :type :permanent))
1053 (define-page view-post-lw1-link (:function #'match-lw1-link) ()
1054 (redirect (convert-lw1-link (hunchentoot:script-name*)) :preserve-query t :type :permanent))
1056 (define-page view-post-ea1-link (:function #'match-ea1-link) ()
1057 (redirect (convert-ea1-link (hunchentoot:script-name*)) :preserve-query t :type :permanent))
1059 (define-page view-post-lw2-slug-link (:function #'match-lw2-slug-link) ()
1060 (redirect (convert-lw2-slug-link (hunchentoot:request-uri*)) :type :see-other))
1062 (define-page view-post-lw2-sequence-link (:function #'match-lw2-sequence-link) ()
1063 (redirect (convert-lw2-sequence-link (hunchentoot:request-uri*)) :type :see-other))
1065 (define-page view-feed "/feed" ()
1066 (redirect "/?format=rss" :type :permanent))
1068 (define-page view-allposts "/allPosts" ()
1069 (redirect (format nil "/index~@[?~A~]" (hunchentoot:query-string*)) :type :see-other))
1071 (define-page view-nominations "/nominations" ()
1072 (redirect "/index?view=nominations" :type :see-other))
1074 (define-page view-reviews "/reviews" ()
1075 (redirect "/index?view=reviews" :type :see-other))
1077 (define-page view-review-voting "/reviewVoting" ()
1078 (redirect "https://www.lesswrong.com/reviewVoting" :type :see-other))
1080 (define-page view-coronavirus-link-database "/coronavirus-link-database" ()
1081 (redirect "https://www.lesswrong.com/coronavirus-link-database" :type :see-other))
1083 (defun post-comment (&key need-auth ((:post-id post-id-real)) ((:tag-id tag-id-real)) shortform)
1084 (request-method
1085 (: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)
1086 (let ((lw2-auth-token *current-auth-token*))
1087 (assert lw2-auth-token)
1088 (let* ((post-id (or post-id-real post-id))
1089 (tag-id (or tag-id-real tag-id))
1090 (question (when post-id (cdr (assoc :question (get-post-body post-id :auth-token lw2-auth-token)))))
1091 (new-comment-result
1092 (cond
1093 (text
1094 (let ((comment-data
1095 (list-cond
1096 (t :body (postprocess-markdown text))
1097 ((and post-id (not (or edit-comment-id (and shortform (not parent-comment-id))))) :post-id post-id)
1098 ((and tag-id (not edit-comment-id)) :tag-id tag-id)
1099 (parent-comment-id :parent-comment-id parent-comment-id)
1100 (answer :answer t)
1101 (nomination :nominated-for-review "2020")
1102 (nomination-review :reviewing-for-review "2020")
1103 (parent-answer-id :parent-answer-id parent-answer-id)
1104 (af :af t)
1105 ((and shortform (not parent-comment-id)) :shortform t))))
1106 (if edit-comment-id
1107 (do-lw2-comment-edit lw2-auth-token edit-comment-id comment-data)
1108 (do-lw2-comment lw2-auth-token comment-data))))
1109 (retract-comment-id
1110 (do-lw2-comment-edit lw2-auth-token retract-comment-id '((:retracted . t))))
1111 (unretract-comment-id
1112 (do-lw2-comment-edit lw2-auth-token unretract-comment-id '((:retracted . :false))))
1113 (delete-comment-id
1114 (do-lw2-comment-remove lw2-auth-token delete-comment-id :reason "Comment deleted by its author.")
1115 nil))))
1116 (when post-id
1117 (ignore-errors
1118 (get-post-comments post-id :force-revalidate t)
1119 (when question
1120 (get-post-answers post-id :force-revalidate t))))
1121 (when text
1122 (alist-bind ((new-comment-id simple-string :--id)
1123 (new-comment-html simple-string :html-body))
1124 new-comment-result
1125 (mark-comment-replied (alist* :parent-comment-id parent-comment-id :user-id *current-userid* new-comment-result))
1126 (setf (markdown-source :comment new-comment-id new-comment-html) text)
1127 (redirect (merge-uris (quri:make-uri :fragment (format nil "comment-~A" new-comment-id)
1128 :query (list-cond (need-auth "need-auth" "y")))
1129 (hunchentoot:request-uri*))))))))))
1131 (define-json-endpoint (view-karma-vote-post forum-site "/karma-vote/post")
1132 (let ((auth-token *current-auth-token*))
1133 (request-method
1134 (:get (post-id)
1135 (hash-cond (make-hash-table)
1136 (post-id "Post" (sethash (make-hash-table) post-id (get-post-vote post-id auth-token)))
1137 (post-id "Comment" (get-post-comments-votes post-id auth-token))
1138 (post-id "Tag" (get-post-tag-votes post-id auth-token)))))))
1140 (define-page view-post-lw2-link (:function #'match-lw2-link post-id comment-id * comment-link-type post-type)
1141 (need-auth
1142 chrono
1143 (show-comments :real-name "comments" :type boolean :default t)
1144 (format :type string))
1145 (request-method
1146 (:get ()
1147 (when (hunchentoot:get-parameter "commentId")
1148 (redirect (format nil "~A/comment/~A" (generate-item-link :post post-id) comment-id))
1149 (return))
1150 (let* ((lw2-auth-token *current-auth-token*)
1151 (preview (string-equal format "preview"))
1152 (show-comments (and (not preview) show-comments))
1153 (*enable-voting* (not (null (logged-in-userid)))))
1154 (multiple-value-bind (post title condition)
1155 (handler-case (nth-value 0 (get-post-body post-id :auth-token (and need-auth lw2-auth-token)))
1156 (serious-condition (c)
1157 (setf *enable-voting* nil)
1158 (values nil "[missing post]" c))
1159 (:no-error (post)
1160 (values post (cdr (assoc :title post)) nil)))
1161 (let* ((is-event (cdr (assoc :is-event post)))
1162 (correct-subtype (if is-event "event" "post")))
1163 (when (string/= post-type correct-subtype)
1164 (redirect (generate-item-link :post post :comment-id comment-id :item-subtype correct-subtype))
1165 (return)))
1166 (labels ((extra-head ()
1167 (when-let (canonical-source (or (and (not comment-id)
1168 (cdr (assoc :canonical-source post)))
1169 (and (always-canonical *current-site*)
1170 (main-site-link *current-site* :post post-id :slug (cdr (assoc :slug post))
1171 :comment-id comment-id :direct-comment-link t))))
1172 <link rel="canonical" href=canonical-source>)
1173 <script>postId=(with-html-stream-output (:stream stream) (json:encode-json post-id stream))</script>
1174 <script>alignmentForumPost=(if (cdr (assoc :af post)) "true" "false")</script>
1175 (when (logged-in-userid)
1176 (call-with-server-data 'process-vote-data (format nil "/karma-vote/post?post-id=~A" post-id))))
1177 (retrieve-individual-comment (comment-thread-type)
1178 (let* ((comments (case comment-thread-type
1179 (:comment (get-post-comments post-id))
1180 (:answer (get-post-answers post-id))))
1181 (target-comment (find comment-id comments :key (lambda (c) (cdr (assoc :--id c))) :test #'string=)))
1182 (values comments target-comment))))
1183 (if comment-id
1184 (let ((comment-thread-type (if (string= comment-link-type "answer") :answer :comment)))
1185 (multiple-value-bind (comments target-comment) (retrieve-individual-comment comment-thread-type)
1186 (unless target-comment
1187 ;; If the comment was not found, try as an answer, or vice versa.
1188 (setf comment-thread-type (if (eq comment-thread-type :comment) :answer :comment)
1189 (values comments target-comment) (retrieve-individual-comment comment-thread-type))
1190 (unless target-comment
1191 (error 'lw2-not-found-error)))
1192 (let* ((*comment-individual-link* t)
1193 (display-name (get-username (cdr (assoc :user-id target-comment))))
1194 (verb-phrase (cond
1195 ((and (eq comment-thread-type :answer)
1196 (not (cdr (assoc :parent-comment-id target-comment))))
1197 "answers")
1198 (t "comments on"))))
1199 (emit-page (out-stream :title (format nil "~A ~A ~A" display-name verb-phrase title)
1200 :content-class "individual-thread-page comment-thread-page"
1201 :social-description (when-let (x (cdr (assoc :html-body target-comment))) (extract-excerpt x))
1202 :extra-head #'extra-head)
1203 (unless preview
1204 (format out-stream "<h1 class=\"post-title\">~A ~A <a href=\"~A\">~A</a></h1>"
1205 (encode-entities display-name)
1206 verb-phrase
1207 (generate-item-link :post post-id)
1208 (clean-text-to-html title :hyphenation nil)))
1209 (output-comments out-stream "comment" comments target-comment :chrono chrono :preview preview)))))
1210 (let ((post-sequences (get-post-sequences post-id))
1211 (debate-responses (when (cdr (assoc :debate post))
1212 (get-post-debate-responses post-id))))
1213 (emit-page (out-stream :title title
1214 :content-class (format nil "post-page comment-thread-page~{ ~A~}"
1215 (list-cond ((cdr (assoc :question post)) "question-post-page")
1216 (post-sequences "in-sequence")
1217 ((not show-comments) "no-comments")))
1218 :social-description (when-let (x (cdr (assoc :html-body post))) (extract-excerpt x))
1219 :extra-head #'extra-head)
1220 (cond
1221 (condition
1222 (error-explanation-case (error-to-html condition)
1223 (lw2-not-allowed-error
1224 <p>This probably means the post has been deleted or moved back to the author's drafts.</p>)))
1226 (post-body-to-html (acons :debate-responses debate-responses post))))
1227 (when (and lw2-auth-token (equal (logged-in-userid) (cdr (assoc :user-id post))))
1228 (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>"
1229 (cdr (assoc :--id post))))
1230 (alist-bind (fm-crosspost foreign-post) post
1231 (alist-bind (is-crosspost hosted-here) fm-crosspost
1232 (when is-crosspost
1233 (if-let (crosspost-site-host (backend-magnum-crosspost-site *current-backend*))
1234 (let* ((*current-site* (find-site crosspost-site-host))
1235 (crosspost-site-title (main-site-title *current-site*)))
1236 (alist-bind (comment-count base-score) foreign-post
1237 <a class="crosspost" href=(generate-item-link :post foreign-post :absolute t)>Crossposted (if hosted-here "to" "from") (progn crosspost-site-title)
1238 \ \((safe (pretty-number (or base-score 0) "point")), (safe (pretty-number (or comment-count 0) "comment"))\)</a>))
1239 (error "Could not retrieve crossposted post. magnum-crosspost-site not configured.")))))
1240 (post-nav-links post post-sequences)
1241 (activate-client-trigger "postLoaded")
1242 (when show-comments
1243 (write-string "<script> </script>" out-stream)
1244 (finish-output out-stream)
1245 (with-error-html-block ()
1246 ;; Temporary hack to support nominations
1247 (let* ((real-comments (get-post-comments post-id))
1248 (answers (when (cdr (assoc :question post))
1249 (get-post-answers post-id)))
1250 (posted-at (and (typep *current-backend* 'backend-lw2)
1251 (cdr (assoc :posted-at post))))
1252 (posted-timestamp (and posted-at (local-time:parse-timestring posted-at)))
1253 (now (local-time:now))
1254 (nominations-open nil)
1255 (reviews-eligible (timerange "2020-01-01" posted-timestamp "2021-01-01"))
1256 (reviews-open (and reviews-eligible (timerange "2021-12-14" now "2022-01-11"))))
1257 (labels ((top-level-property (comment property)
1258 (or (cdr (assoc property comment))
1259 (cdr (assoc property (cdr (assoc :top-level-comment comment)))))))
1260 (multiple-value-bind (normal-comments nominations reviews)
1261 (loop for comment in real-comments
1262 if (top-level-property comment :nominated-for-review)
1263 collect comment into nominations
1264 else if (top-level-property comment :reviewing-for-review)
1265 collect comment into reviews
1266 else
1267 collect comment into normal-comments
1268 finally (return (values normal-comments nominations reviews)))
1269 (unless (or nominations reviews)
1270 (setf normal-comments real-comments)) ;for caching
1271 (loop for (name comments open) in (list-cond ((or nominations nominations-open)
1272 (list "nomination" nominations nominations-open))
1273 ((or reviews reviews-open)
1274 (list "review" reviews reviews-open))
1275 ((cdr (assoc :question post))
1276 (list "answer" answers t))
1278 (list "comment" normal-comments t)))
1279 do (output-comments out-stream name comments nil
1280 :replies-open open
1281 :overcomingbias-sort (cdr (assoc :comment-sort-order post)) :chrono chrono :preview preview))))))))))))))
1282 (:post ()
1283 (post-comment :post-id post-id :need-auth need-auth))))
1285 (defparameter *edit-post-template* (compile-template* "edit-post.html"))
1287 (define-page view-edit-post "/edit-post" (title url section tags post-id link-post)
1288 (request-method
1289 (:get ()
1290 (let* ((csrf-token (make-csrf-token))
1291 (post-body (if post-id (get-post-body post-id :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1292 (section (or section (loop for (sym . sec) in '((:draft . "drafts") (:meta . "meta") (:frontpage-date . "frontpage"))
1293 if (cdr (assoc sym post-body)) return sec
1294 finally (return "all")))))
1295 (emit-page (out-stream :title (if post-id "Edit Post" "New Post") :content-class "edit-post-page")
1296 (render-template* *edit-post-template* out-stream
1297 :csrf-token csrf-token
1298 :title (cdr (assoc :title post-body))
1299 :url (cdr (assoc :url post-body))
1300 :question (cdr (assoc :question post-body))
1301 :tags-supported (typep *current-backend* 'backend-accordius)
1302 :tags (when (and post-id (typep *current-backend* 'backend-accordius)) (do-wl-rest-query (format nil "posts/~a/update_tagset/" post-id) '()))
1303 :post-id post-id
1304 :section-list (loop for (name desc) in '(("all" "All") ("meta" "Meta") ("frontpage" "Frontpage") ("drafts" "Drafts"))
1305 when (or (string= name section) (member name '("drafts" "all") :test #'string=))
1306 collect (alist :name name :desc desc :selected (string= name section)))
1307 :lesswrong-misc (typep *current-backend* 'backend-lw2-misc-features)
1308 :submit-to-frontpage (if post-id (cdr (assoc :submit-to-frontpage post-body)) t)
1309 :markdown-source (or (and post-id (markdown-source :post post-id (cdr (assoc :html-body post-body)))) "")))))
1310 (:post (text question submit-to-frontpage)
1311 (let ((lw2-auth-token *current-auth-token*)
1312 (url (if (string= url "") nil url)))
1313 (assert lw2-auth-token)
1314 (let* ((post-data
1315 (list-cond
1316 (t :body (postprocess-markdown text))
1317 (t :title (or (nonempty-string title) "Untitled"))
1318 (link-post :url url)
1319 (t :meta (or (string= section "meta") :false))
1320 ((not post-id) :is-event nil)
1321 (t :draft (or (string= section "drafts") :false))
1322 ((typep *current-backend* 'backend-lw2-misc-features) :submit-to-frontpage (and submit-to-frontpage t))
1323 ((not post-id) :question (if question t :false))))
1324 (post-unset
1325 (list-cond
1326 ((not link-post) :url t)))
1327 (new-post-data
1328 (if post-id
1329 (do-lw2-post-edit lw2-auth-token post-id post-data post-unset)
1330 (do-lw2-post lw2-auth-token post-data)))
1331 (new-post-id (cdr (assoc :--id new-post-data))))
1332 (assert new-post-id)
1333 (when (typep *current-backend* 'backend-accordius)
1334 (do-wl-rest-mutate :post
1335 (format nil "posts/~a/update_tagset/" post-id)
1336 (alist "tags" tags)
1337 lw2-auth-token))
1338 (setf (markdown-source :post new-post-id (cdr (assoc :html-body new-post-data))) text)
1339 (ignore-errors (get-post-body post-id :force-revalidate t))
1340 (redirect (if (js-true (cdr (assoc :draft post-data)))
1341 (concatenate 'string (generate-item-link :post new-post-data) "?need-auth=y")
1342 (generate-item-link :post new-post-data))))))))
1344 (define-json-endpoint (view-karma-vote forum-site "/karma-vote")
1345 (let ((auth-token *current-auth-token*))
1346 (request-method
1347 (:post (target target-type (vote-json :real-name "vote"))
1348 (let ((vote (safe-decode-json vote-json)))
1349 (multiple-value-bind (current-vote result)
1350 (do-lw2-vote auth-token target-type target vote)
1351 (alist-bind (vote-count base-score af af-base-score extended-score) result
1352 (let ((vote-buttons (vote-buttons base-score
1353 :as-text t
1354 :af-score (and af af-base-score)
1355 :vote-count (+ vote-count (if (member (cdr (assoc :karma current-vote)) '(nil "neutral") :test #'equal)
1358 :extended-score extended-score))
1359 (out (make-hash-table)))
1360 (loop for (axis . axis-vote) in current-vote
1361 do (setf (gethash axis out) (list* axis-vote (gethash axis vote-buttons))))
1362 out))))))))
1364 (delete-easy-handler 'view-karma-vote)
1366 (define-json-endpoint (view-user-status login-site "/current-user-status")
1367 (let ((auth-token *current-auth-token*))
1368 (request-method
1369 (:get ()
1370 (if (lw2-graphql-query (graphql-query-string "currentUser" nil '(:--id)) :auth-token auth-token)
1371 (sethash (make-hash-table)
1372 "notifications" (check-notifications (logged-in-userid) auth-token)
1373 "alignmentForumAllowed" (member "alignmentForum" (cdr (assoc :groups (get-user :user-id (logged-in-userid)))) :test #'string=))
1374 (with-cache-transaction
1375 (cache-del "auth-token-to-userid" auth-token)
1376 (cache-del "auth-token-to-username" auth-token)))))))
1378 (hunchentoot:define-easy-handler (view-check-notifications :uri "/check-notifications") (format)
1379 (with-error-page
1380 (setf (hunchentoot:content-type*) "application/json")
1381 (if *current-auth-token*
1382 (let ((notifications-status (check-notifications (logged-in-userid) *current-auth-token* :full (string= format "push"))))
1383 (json:encode-json-to-string notifications-status)))))
1385 (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)
1386 (with-error-page
1387 (check-csrf-token csrf-token)
1388 (let ((user-id (logged-in-userid)))
1389 (unless user-id (error "Not logged in."))
1390 (with-cache-transaction
1391 (let ((ignore-hash (get-ignore-hash user-id)))
1392 (if (string= state "ignore")
1393 (setf (gethash target-id ignore-hash) t)
1394 (remhash target-id ignore-hash))
1395 (cache-put "user-ignore-list" user-id ignore-hash :value-type :json))))
1396 (when return
1397 (redirect return))))
1399 (client-defun comment-controls (&key standalone parent-comment-id parent-answer-id edit-comment-id)
1400 (flet ((inner ()
1401 <form method="post" id="conversation-form" class="aligned-form">
1402 <div class="textarea-container">
1403 <textarea name="text" oninput="enableBeforeUnload();"></textarea>
1404 <span class="markdown-reference-link">You can use <a href="http://commonmark.org/help/" target="_blank">Markdown</a> here.</span>
1405 <button type="button" class="guiedit-mobile-auxiliary-button guiedit-mobile-help-button">Help</button>
1406 <button type="button" class="guiedit-mobile-auxiliary-button guiedit-mobile-exit-button">Exit</button>
1407 </div>
1408 <div>
1409 (macrolet ((hidden-var (name)
1410 `(when ,name <input type="hidden" name=,(string-downcase name) value=,name>)))
1411 (hidden-var parent-comment-id)
1412 (hidden-var parent-answer-id)
1413 (hidden-var edit-comment-id))
1414 <input name="csrf-token" value=(make-csrf-token) type="hidden">
1415 <input value="Submit" type="submit">
1416 </div>
1417 </form>))
1418 (if standalone
1419 <div class="posting-controls standalone with-markdown-editor" onsubmit="disableBeforeUnload();">(with-html-stream-output (inner))</div>
1420 (inner))))
1422 (define-json-endpoint (view-karma-vote-shortform shortform-site "/karma-vote/shortform")
1423 (let ((auth-token *current-auth-token*))
1424 (request-method
1425 (:get ((offset :type fixnum :default 0))
1426 (sethash (make-hash-table)
1427 "Comment" (get-shortform-votes auth-token :offset offset))))))
1429 (define-component view-comments-index (index-type)
1430 (:http-args ((offset :type fixnum)
1431 (limit :type fixnum)
1432 (view :member '(nil :alignment-forum))))
1433 (request-method
1434 (:get ()
1435 (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.
1436 (shortform (eq index-type :shortform))
1437 (with-voting (not (null (and shortform (logged-in-userid))))))
1438 (multiple-value-bind (title query-view top-nav)
1439 (cond
1440 (shortform (values "Shortform" "shortform" (if (logged-in-userid) (lambda () (comment-controls :standalone t)))))
1441 (t (values (case view (:alignment-forum "Alignment Forum recent comments") (t "Recent comments")) "allRecentComments" nil)))
1442 (multiple-value-bind (recent-comments total last-modified)
1443 (if (or (not (eq index-type :recent-comments)) offset limit view (/= (user-pref :items-per-page) 20))
1444 (let ((*use-alignment-forum* (eq view :alignment-forum)))
1445 (lw2-graphql-query (lw2-query-string :comment :list
1446 (remove nil (alist :view query-view
1447 :limit (or limit (user-pref :items-per-page)) :offset offset)
1448 :key #'cdr)
1449 :context (if shortform :shortform :index)
1450 :with-total want-total)))
1451 (get-recent-comments :with-total want-total))
1452 (handle-last-modified last-modified)
1453 (renderer ()
1454 (view-items-index recent-comments
1455 :title title
1456 :extra-head (lambda ()
1457 (when with-voting
1458 (call-with-server-data 'process-vote-data (format nil "/karma-vote/shortform?offset=~A" (or offset 0)))))
1459 :content-class (if shortform "index-page shortform-index-page comment-thread-page" "index-page comment-index-page")
1460 :pagination (pagination-nav-bars :offset (or offset 0) :with-next (not want-total) :total (if want-total total))
1461 :top-nav (lambda () (page-toolbar-to-html :title title) (when top-nav (funcall top-nav)))
1462 :alternate-html (if (eq index-type :shortform)
1463 (lambda ()
1464 (let ((*enable-voting* with-voting))
1465 <div class="comments">
1466 (comment-tree-to-html *html-output*
1467 (make-comment-parent-hash
1468 (flatten-shortform-comments recent-comments)))
1469 </div>)))))))))
1470 (:post ()
1471 (post-comment :shortform t))))
1473 (define-component-routes forum-site (view-recent-comments (standard-route :uri "/recentcomments") () (view-comments-index :recent-comments)))
1474 (define-component-routes shortform-site (view-shortform (standard-route :uri "/shortform") () (view-comments-index :shortform)))
1476 (delete-easy-handler 'view-recent-comments)
1478 (defun tag-to-html (tag &key skip-headline)
1479 (schema-bind (:tag tag :auto :context :body)
1480 (alist-bind (edited-at html user-id) description
1481 (unless skip-headline
1482 <h1 class="post-title">(safe (clean-text-to-html name))</h1>
1483 <div class="post-meta">
1484 <span>(if core "Core ")(if wiki-only "Wiki" "Tag")</span>
1485 (when (and (nonempty-string edited-at) (nonempty-string user-id))
1486 <span>Last edit: (pretty-time-html edited-at)
1487 \ by <a class="author" href=("/users/~A" (get-user-slug user-id))>(get-username user-id)</a>
1488 </span>)
1489 </div>)
1490 (when html
1491 <div class="tag-description body-text">(with-html-stream-output (:stream stream) (let ((*memoized-output-stream* stream)) (clean-html* html)))</div>))))
1493 (defun tag-list-to-html (tags)
1494 <ul class="tag-list">
1495 (iter (for tag in tags)
1496 (schema-bind (:tag tag :auto :context :index)
1497 <li><a class="post-title-link" href=("/tag/~A" slug)>(safe (clean-text-to-html name))(if wiki-only
1498 " (wiki)"
1499 (if post-count (format nil " (~A)" post-count)))</a></li>))
1500 </ul>)
1502 (define-json-endpoint (view-user-autocomplete forum-site "/-user-autocomplete")
1503 (request-method
1504 (:get (q)
1505 (lw2-search-query q :indexes '(:users)))))
1507 (define-json-endpoint (view-karma-vote-tag forum-site "/karma-vote/tag")
1508 (let ((auth-token *current-auth-token*))
1509 (request-method
1510 (:get (tag-id post-id)
1511 (hash-cond (make-hash-table)
1512 (tag-id "Post" (get-tag-post-votes tag-id auth-token))
1513 (tag-id "Comment" (get-tag-comments-votes tag-id auth-token))
1514 (post-id "Tag" (get-post-tag-votes post-id auth-token)))))))
1516 (define-component view-tag (slug tail)
1517 (:http-args ((sort :default :relevant :member '(:relevant :new :old))))
1518 (when (nonempty-string tail)
1519 (redirect (format nil "/tag/~A" slug))
1520 (return))
1521 (let ((tag (first (lw2-graphql-query (lw2-query-string :tag :list (alist :view "tagBySlug" :slug slug) :context :body)))))
1522 (unless tag
1523 (error 'lw2-not-found-error))
1524 (request-method
1525 (:get ()
1526 (let* ((posts (get-tag-posts slug))
1527 (posts (if (eq sort :relevant) posts (sort-items posts sort))))
1528 (schema-bind (:tag tag :auto :context :body)
1529 (renderer ()
1530 (view-items-index posts
1531 :title (format nil "~A tag" name)
1532 :extra-head (lambda ()
1533 (when-let (canonical-source (and (always-canonical *current-site*)
1534 (main-site-link *current-site* :tag slug)))
1535 <link rel="canonical" href=canonical-source>)
1536 (when (logged-in-userid)
1537 (call-with-server-data 'process-vote-data (format nil "/karma-vote/tag?tag-id=~A" tag-id))))
1538 :top-nav (lambda ()
1539 (page-toolbar-to-html :title name :rss (not wiki-only))
1540 (tag-to-html tag)
1541 (when (and posts (not *preview*))
1542 (sublevel-nav-to-html '(:relevant :new :old)
1543 sort
1544 :default :relevant
1545 :param-name "sort"
1546 :extra-class "sort")))
1547 :content-class "index-page tag-index-page"
1548 :alternate-html (lambda ()
1549 (unless wiki-only
1550 (write-index-items-to-html *html-output* posts))
1551 (when (typep *current-backend* 'backend-lw2-tags-comments)
1552 (finish-output *html-output*)
1553 (let ((*enable-voting* (not (null (logged-in-userid))))
1554 (comments (lw2-graphql-query (lw2-query-string :comment :list (alist :view "tagDiscussionComments" :tag-id tag-id)))))
1555 (output-comments *html-output* "comment" comments nil :replies-open t)))))))))
1556 (:post ()
1557 (schema-bind (:tag tag (tag-id))
1558 (renderer ()
1559 (post-comment :tag-id tag-id)))))))
1561 (define-component-routes forum-site (view-tag (regex-route :regex "^/(?:tag|topics)/([^/?]+)(/[^/?]*)?") (slug tail) (view-tag slug tail)))
1563 (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/"))))
1565 (define-component view-tags-index ()
1566 (:http-args ())
1567 (multiple-value-bind (all-tags portal)
1568 (lw2-graphql-query-multi
1569 (list (lw2-query-string* :tag :list (alist :view "allTagsAlphabetical"))
1570 (lw2-query-string* :tag :list (alist :view "tagBySlug" :slug "portal") :context :body)))
1571 (let ((core-tags
1572 (iter (for tag in all-tags)
1573 (schema-bind (:tag tag (core))
1574 (when core (collect tag)))))
1575 (title (if (typep *current-site* 'lesswrong-viewer-site) "Concepts Portal" "Tags Portal")))
1576 (renderer ()
1577 (emit-page (out-stream :title title)
1578 <article>
1579 <h1 class="post-title">(safe title)</h1>
1580 (tag-to-html (first portal) :skip-headline t)
1581 </article>
1582 (iter (for (title . tags) in (alist "Core Tags" core-tags "All Tags" all-tags))
1583 (progn
1584 <h1>(safe title)</h1>
1585 (tag-list-to-html tags))))))))
1587 (define-component-routes forum-site (view-tags-index (standard-route :uri "/tags") () (view-tags-index)))
1588 (define-component-routes forum-site (view-tags-index-alt (standard-route :uri "/topics") () (view-tags-index)))
1590 (define-route 'forum-site 'standard-route :name 'view-tags-index-redirect :uri "/tags/all" :handler (lambda () (redirect "/tags")))
1591 (define-route 'forum-site 'standard-route :name 'view-tags-index-redirect :uri "/topics/all" :handler (lambda () (redirect "/topics")))
1593 (define-route 'alternate-frontend-site 'standard-route :name 'view-tags-voting-redirect :uri "/tagVoting" :handler (lambda () (main-site-redirect "/tagVoting")))
1594 (define-route 'alternate-frontend-site 'standard-route :name 'view-tags-dashboard-redirect :uri "/tags/dashboard" :handler (lambda () (main-site-redirect "/tags/dashboard")))
1596 (hunchentoot:define-easy-handler (view-push-register :uri "/push/register") ()
1597 (with-error-page
1598 (let* ((data (call-with-safe-json (lambda ()
1599 (json:decode-json-from-string
1600 (hunchentoot:raw-post-data :force-text t :external-format :utf-8)))))
1601 (subscription (cdr (assoc :subscription data)))
1602 (cancel (cdr (assoc :cancel data))))
1603 (cond
1604 (subscription
1605 (make-subscription *current-auth-token*
1606 (cdr (assoc :endpoint subscription))
1607 (cdr (assoc :expires *current-auth-status*)))
1608 (send-notification (cdr (assoc :endpoint subscription)) :ttl 120))
1609 (cancel
1610 (delete-subscription *current-auth-token*)))
1611 nil)))
1613 (hunchentoot:define-easy-handler (view-inbox-redirect :uri "/push/go-inbox") ()
1614 (with-error-page
1615 (redirect (format nil "/users/~A?show=inbox" *current-user-slug*))))
1617 (define-page view-user (:regex "^/users/(.*?)(?:$|\\?)|^/user" user-slug) (id
1618 (offset :type fixnum :default 0)
1619 (show :member '(:all :posts :comments :drafts :conversations :inbox) :default :all)
1620 (sort :member '(:top :new :old) :default :new))
1621 (let* ((auth-token (if (eq show :inbox) *current-auth-token*))
1622 (user-info
1623 (let* ((ui (get-user (cond (user-slug :user-slug) (id :user-id)) (or user-slug id) :auth-token auth-token))
1624 (canonical-slug (cdr (assoc :slug ui))))
1625 (when (and user-slug
1626 canonical-slug
1627 (not (string-equal user-slug canonical-slug)))
1628 (return-from view-user (redirect (format nil "/users/~A" canonical-slug))))
1629 (if (and (not (cdr (assoc :deleted ui))) (cdr (assoc :--id ui)))
1631 (error 'lw2-user-not-found-error))))
1632 (user-id (cdr (assoc :--id user-info)))
1633 (own-user-page (logged-in-userid user-id))
1634 (display-name (if user-slug (cdr (assoc :display-name user-info)) user-id))
1635 (show-text (if (not (eq show :all)) (string-capitalize show)))
1636 (title (format nil "~A~@['s ~A~]" display-name show-text))
1637 (sort-type (case sort (:top :score) (:new :date) (:old :date-reverse))))
1638 (multiple-value-bind (items total last-modified)
1639 (case show
1640 (:posts
1641 (get-user-page-items user-id :posts :offset offset :limit (+ 1 (user-pref :items-per-page)) :sort-type sort-type))
1642 (:comments
1643 (get-user-page-items user-id :comments :offset offset :limit (+ 1 (user-pref :items-per-page)) :sort-type sort-type))
1644 (:drafts
1645 (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")))
1646 (:conversations
1647 (let ((conversations
1648 (lw2-graphql-query (lw2-query-string :conversation :list
1649 (alist :view "userConversations" :limit (+ 1 (user-pref :items-per-page)) :offset offset :user-id user-id)
1650 :fields '(:--id :created-at :title (:participants :display-name :slug) :----typename))
1651 :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1652 (lw2-graphql-query-map
1653 (lambda (c)
1654 (lw2-query-string* :message :total (alist :view "messagesConversation" :conversation-id (cdr (assoc :--id c)))))
1655 conversations
1656 :postprocess (lambda (c result)
1657 (acons :messages-total result c))
1658 :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1659 (:inbox
1660 (error-explanation-case
1661 (prog1
1662 (let ((notifications (get-notifications :user-id user-id :offset offset :auth-token (hunchentoot:cookie-in "lw2-auth-token")))
1663 (last-check (ignore-errors (local-time:parse-timestring (cdr (assoc :last-notifications-check user-info))))))
1664 (labels ((check-new (key obj)
1665 (if (ignore-errors (local-time:timestamp< last-check (local-time:parse-timestring (cdr (assoc key obj)))))
1666 (acons :highlight-new t obj)
1667 obj))
1668 (check-replied (comment)
1669 (let* ((post-id (cdr (assoc :post-id comment)))
1670 (comment-id (cdr (assoc :--id comment)))
1671 (reply-comment-id (check-comment-replied comment-id user-id)))
1672 (if reply-comment-id
1673 (acons :replied (list :post post-id :comment-id reply-comment-id) comment)
1674 comment))))
1675 (lw2-graphql-query-map
1676 (lambda (n)
1677 (alexandria:switch ((cdr (assoc :document-type n)) :test #'string=)
1678 ("comment"
1679 (lw2-query-string* :comment :single
1680 (alist :document-id (cdr (assoc :document-id n)))
1681 :context :index))
1682 ("post"
1683 (lw2-query-string* :post :single (alist :document-id (cdr (assoc :document-id n)))))
1684 ("message"
1685 (lw2-query-string* :message :single (alist :document-id (cdr (assoc :document-id n)))
1686 :fields *messages-index-fields*))
1688 (values n t))))
1689 notifications
1690 :postprocess (lambda (n result)
1691 (if result
1692 (funcall (if (string= (cdr (assoc :document-type n)) "comment") #'check-replied #'identity)
1693 (check-new
1694 (alexandria:switch ((cdr (assoc :document-type n)) :test #'string=)
1695 ("comment" :posted-at)
1696 ("post" :posted-at)
1697 ("message" :created-at))
1698 result))
1700 :auth-token auth-token)))
1701 (do-user-edit
1702 (hunchentoot:cookie-in "lw2-auth-token")
1703 user-id
1704 (alist :last-notifications-check (timestamp-to-graphql (local-time:now)))))
1705 (lw2-not-allowed-error
1706 <p>This may mean your login token has expired or become invalid. You can try <a href="/login">logging in again</a>.</p>)))
1708 (get-user-page-items user-id :both :offset offset :limit (+ 1 (user-pref :items-per-page)) :sort-type sort-type)))
1709 (handle-last-modified last-modified)
1710 (let ((with-next (> (length items) (+ (if (eq show :all) offset 0) (user-pref :items-per-page))))
1711 (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
1712 (view-items-index interleave :title title
1713 :content-class (format nil "user-page~@[ ~A-user-page~]~:[~; own-user-page~]" (string-downcase show) own-user-page)
1714 :current-uri (format nil "/users/~A" user-slug)
1715 :section :personal
1716 :pagination (pagination-nav-bars :offset offset :total total :with-next (if (not total) with-next))
1717 :need-auth (eq show :drafts) :section (if (eq show :drafts) "drafts" nil)
1718 :top-nav (lambda ()
1719 (page-toolbar-to-html :title title
1720 :enable-push-notifications (eq show :inbox)
1721 :rss (not (member show '(:drafts :conversations :inbox)))
1722 :new-post (if (eq show :drafts) "drafts" t)
1723 :new-conversation (if own-user-page t user-slug)
1724 :ignore (if (and (logged-in-userid) (not own-user-page))
1725 (lambda ()
1726 (let ((ignored (gethash user-id *current-ignore-hash*)))
1727 <form method="post" action="/ignore-user">
1728 <button class=("button ~A" (if ignored "unignore-button" "ignore-button"))>(if ignored "Unignore user" "Ignore user")</button>
1729 <input type="hidden" name="csrf-token" value=(make-csrf-token)>
1730 <input type="hidden" name="target-id" value=user-id>
1731 <input type="hidden" name="state" value=(if ignored "unignore" "ignore")>
1732 <input type="hidden" name="return" value=(hunchentoot:request-uri*)>
1733 </form>)))
1734 :logout own-user-page)
1735 (alist-bind ((actual-id string :--id)
1736 (actual-slug string :slug)
1737 (karma (or null fixnum))
1738 (af-karma (or null fixnum)))
1739 user-info
1740 <h1 class="page-main-heading"
1741 (when (not own-user-page)
1742 (format nil "data-~:[~;anti-~]~:*kibitzer-redirect=~:[/users/~*~A~;/user?id=~A~]"
1743 user-slug actual-id actual-slug))>
1744 (progn display-name)
1745 (let ((full-name (get-user-full-name user-id)))
1746 (when (and user-slug (stringp full-name) (> (length full-name) 0))
1747 <span class="user-full-name">\((progn full-name)\)</span>))
1748 </h1>
1749 <div class="user-stats">
1750 Karma:
1751 <span class="karma-type">
1752 <span class="karma-total">(if user-slug (pretty-number (or karma 0)) "##")</span>(if af-karma " (LW),")
1753 </span>\
1754 (when af-karma
1755 <span class="karma-type">
1756 <span class="karma-total af-karma-total">(if user-slug (pretty-number (or af-karma 0)) "##")</span> \(AF\)
1757 </span>)
1758 </div>
1759 (when-let (html-bio (cdr (assoc :html-bio user-info)))
1760 <div class="user-bio body-text">
1761 (with-html-stream-output (:stream stream)
1762 (let ((*memoized-output-stream* stream))
1763 (clean-html* html-bio)))
1764 </div>))
1765 (sublevel-nav-to-html `(:all :posts :comments
1766 ,@(if own-user-page
1767 '(:drafts :conversations :inbox)))
1768 show
1769 :default :all)
1770 (when (member show '(:all :posts :comments))
1771 (sublevel-nav-to-html '(:new :top :old)
1772 sort
1773 :default :new
1774 :param-name "sort"
1775 :extra-class "sort"))))))))
1777 (defparameter *conversation-template* (compile-template* "conversation.html"))
1779 (define-page view-conversation "/conversation" (id to subject)
1780 (request-method
1781 (:get ()
1782 (cond
1783 ((and id to) (error "This is an invalid URL."))
1785 (multiple-value-bind (conversation messages)
1786 (get-conversation-messages id (hunchentoot:cookie-in "lw2-auth-token"))
1787 (let ((conversation (rectify-conversation conversation)))
1788 (view-items-index (nreverse messages) :content-class "conversation-page" :need-auth t :title (encode-entities (cdr (assoc :title conversation)))
1789 :top-nav (lambda () (render-template* *conversation-template* *html-output*
1790 :conversation conversation :csrf-token (make-csrf-token)))))))
1792 (emit-page (out-stream :title "New conversation" :content-class "conversation-page")
1793 (render-template* *conversation-template* out-stream
1794 :to to
1795 :subject subject
1796 :csrf-token (make-csrf-token))))))
1797 (:post ((text :required t))
1798 (let* ((id (or id
1799 (let ((participant-ids (list (logged-in-userid) (cdar (lw2-graphql-query (lw2-query-string :user :single (alist :slug to) :fields '(:--id)))))))
1800 (do-create-conversation (hunchentoot:cookie-in "lw2-auth-token") (alist :participant-ids participant-ids :title subject))))))
1801 (do-create-message (hunchentoot:cookie-in "lw2-auth-token") id text)
1802 (redirect (format nil "/conversation?id=~A" id))))))
1804 (define-page view-search "/search" ((q :required t)
1805 (sort :default :relevant :member '(:relevant :new :old)))
1806 (let ((*current-search-query* q)
1807 (link (presentable-link q :search))
1808 (title (format nil "~@[~A - ~]Search" q)))
1809 (declare (special *current-search-query*))
1810 (if link
1811 (redirect link)
1812 (multiple-value-bind (results tags) (lw2-search-query q)
1813 (let* ((sort (if (string= (hunchentoot:get-parameter "format") "rss")
1814 :new
1815 sort))
1816 (results (if (eq sort :relevant)
1817 results
1818 (sort-items results sort)))
1819 (results (if (hunchentoot:get-parameter "format")
1820 (firstn results 20)
1821 results)))
1822 (view-items-index results
1823 :top-nav (lambda ()
1824 (page-toolbar-to-html :title title :rss t)
1825 (sublevel-nav-to-html '(:relevant :new :old)
1826 sort
1827 :default :relevant
1828 :param-name "sort"
1829 :extra-class "sort")
1830 (when tags
1831 <h1>Tags</h1>
1832 (tag-list-to-html (firstn tags 20))))
1833 :content-class "index-page search-results-page" :current-uri "/search"
1834 :title title))))))
1836 (defgeneric view-login (backend))
1838 (defmethod view-login ((backend backend-password-login))
1839 (with-http-args (return cookie-check
1840 (login-username :request-type :post) (login-password :request-type :post)
1841 (signup-username :request-type :post) (signup-email :request-type :post) (signup-password :request-type :post) (signup-password2 :request-type :post))
1842 (labels
1843 ((emit-login-page (&key error-message)
1844 (let ((csrf-token (make-csrf-token)))
1845 (emit-page (out-stream :title "Log in" :current-uri "/login" :content-class "login-page" :robots "noindex, nofollow")
1846 (when error-message
1847 (format out-stream "<div class=\"error-box\">~A</div>" error-message))
1848 (with-outputs (out-stream) "<div class=\"login-container\">")
1849 (output-form out-stream "post" (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))) "login-form" "Log in" csrf-token
1850 '(("login-username" "Username" "text" "username")
1851 ("login-password" "Password" "password" "current-password"))
1852 "Log in"
1853 :end-html (when (typep *current-backend* 'backend-websocket-login) ;other backends not supported yet
1854 "<a href=\"/reset-password\">Forgot password</a>"))
1855 (output-form out-stream "post" (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))) "signup-form" "Create account" csrf-token
1856 '(("signup-username" "Username" "text" "username")
1857 ("signup-email" "Email" "text" "email")
1858 ("signup-password" "Password" "password" "new-password")
1859 ("signup-password2" "Confirm password" "password" "new-password"))
1860 "Create account")
1861 (if-let (main-site-title (main-site-title *current-site*))
1862 (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>"
1863 main-site-title))
1864 (format out-stream "</div>"))))
1865 (finish-login (username user-id auth-token error-message &optional expires)
1866 (cond
1867 (auth-token
1868 (set-cookie "lw2-auth-token" auth-token :max-age (if expires (+ (- expires (get-unix-time)) (* 24 60 60)) (1- (expt 2 31))))
1869 (if expires (set-cookie "lw2-status" (json:encode-json-to-string (alist :expires expires))))
1870 (cache-put "auth-token-to-userid" auth-token user-id)
1871 (cache-put "auth-token-to-username" auth-token username)
1872 (redirect (if (and return (ppcre:scan "^/[^/]" return)) return "/")))
1874 (emit-login-page :error-message error-message)))))
1875 (cond
1876 ((not (or cookie-check (hunchentoot:cookie-in "session-token")))
1877 (set-cookie "session-token" (base64:usb8-array-to-base64-string (ironclad:make-random-salt)))
1878 (redirect (format nil "/login?~@[return=~A&~]cookie-check=y" (if return (url-rewrite:url-encode return)))))
1879 (cookie-check
1880 (if (hunchentoot:cookie-in "session-token")
1881 (redirect (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))))
1882 (emit-page (out-stream :title "Log in" :current-uri "/login")
1883 (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))))))
1884 (login-username
1885 (cond
1886 ((or (string= login-username "") (string= login-password "")) (emit-login-page :error-message "Please enter a username and password"))
1887 ((lw2.dnsbl:dnsbl-check (hunchentoot:real-remote-addr)) (emit-login-page :error-message "Your IP address is blacklisted."))
1888 (t (multiple-value-call #'finish-login login-username (do-login login-username login-password)))))
1889 (signup-username
1890 (cond
1891 ((not (every (lambda (x) (not (string= x ""))) (list signup-username signup-email signup-password signup-password2)))
1892 (emit-login-page :error-message "Please fill in all fields"))
1893 ((not (string= signup-password signup-password2))
1894 (emit-login-page :error-message "Passwords do not match"))
1895 ((lw2.dnsbl:dnsbl-check (hunchentoot:real-remote-addr)) (emit-login-page :error-message "Your IP address is blacklisted."))
1896 (t (multiple-value-call #'finish-login signup-username (do-lw2-create-user signup-username signup-email signup-password)))))
1898 (emit-login-page))))))
1900 (defmethod view-logout ((backend backend-password-login))
1901 (request-method
1902 (:post ()
1903 (set-cookie "lw2-auth-token" "" :max-age 0)
1904 (do-logout *current-auth-token*)
1905 (redirect "/"))))
1907 (defparameter *reset-password-template* (compile-template* "reset-password.html"))
1909 (define-component basic-reset-password ()
1910 (:http-args ((email :request-type :post) (reset-link :request-type :post) (password :request-type :post) (password2 :request-type :post)))
1911 (renderer ()
1912 (labels ((emit-rpw-page (&key message message-type step)
1913 (let ((csrf-token (make-csrf-token)))
1914 (emit-page (out-stream :title "Reset password" :content-class "reset-password" :robots "noindex, nofollow")
1915 (render-template* *reset-password-template* out-stream
1916 :csrf-token csrf-token
1917 :reset-link reset-link
1918 :message message
1919 :message-type message-type
1920 :step step)))))
1921 (cond
1922 (email
1923 (multiple-value-bind (ret error)
1924 (do-lw2-forgot-password email)
1925 (declare (ignore ret))
1926 (if error
1927 (emit-rpw-page :step 1 :message error :message-type "error")
1928 (emit-rpw-page :step 1 :message "Password reset email sent." :message-type "success"))))
1929 (reset-link
1930 (ppcre:register-groups-bind (reset-token) ("(?:reset-password/|^)([^/#]+)$" reset-link)
1931 (cond
1932 ((not reset-token)
1933 (emit-rpw-page :step 2 :message "Invalid password reset link." :message-type "error"))
1934 ((not (string= password password2))
1935 (emit-rpw-page :step 2 :message "Passwords do not match." :message-type "error"))
1937 (multiple-value-bind (user-id auth-token error-message) (do-lw2-reset-password reset-token password)
1938 (declare (ignore user-id auth-token))
1939 (cond
1940 (error-message (emit-rpw-page :step 2 :message error-message :message-type "error"))
1942 (with-error-page (emit-page (out-stream :title "Reset password" :content-class "reset-password")
1943 (format out-stream "<h1>Password reset complete</h1><p>You can now <a href=\"/login\">log in</a> with your new password.</p>"))))))))))
1945 (emit-rpw-page))))))
1947 (define-route 'login-site 'standard-route :name 'view-login :uri "/login" :handler (lambda () (with-error-page (view-login *current-backend*))))
1948 (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*))))
1950 (define-route 'login-site 'standard-route :name 'view-logout :uri "/logout" :handler (lambda () (with-error-page (view-logout *current-backend*))))
1952 (define-component-routes login-site
1953 (basic-reset-password (standard-route :uri "/reset-password") () (basic-reset-password)))
1955 (defun oauth2.0-login-request-uri (backend path &optional query)
1956 (quri:render-uri
1957 (quri:merge-uris
1958 (quri:make-uri :path path :query query)
1959 (quri:uri (oauth2.0-login-uri backend)))))
1961 (defmethod view-login ((backend backend-oauth2.0-login))
1962 (with-http-args (return)
1963 (set-cookie "session-token" (base64:usb8-array-to-base64-string (ironclad:make-random-salt)))
1964 (redirect
1965 (oauth2.0-login-request-uri backend "authorize"
1966 (alist "response_type" "code"
1967 "client_id" (oauth2.0-client-id backend)
1968 "redirect_uri" (quri:render-uri (quri:merge-uris (quri:uri "/auth/callback") (quri:uri (site-uri *current-site*))))
1969 "scope" "openid profile email"
1970 "state" return)))))
1972 (defmethod view-login-oauth2.0-callback ((backend backend-oauth2.0-login))
1973 (with-http-args (code state)
1974 (let ((auth-response
1975 (call-with-http-response #'json:decode-json
1976 (oauth2.0-login-request-uri backend "oauth/token")
1977 :method :post
1978 :content (alist "grant_type" "authorization_code"
1979 "client_id" (oauth2.0-client-id backend)
1980 "client_secret" (oauth2.0-client-secret backend)
1981 "code" code
1982 "redirect_uri" (quri:render-uri (quri:merge-uris (quri:uri "/auth/callback") (quri:uri (site-uri *current-site*)))))
1983 :want-stream t :force-string t)))
1984 (alist-bind ((access-token (or null simple-string) :access--token)
1985 (error (or null simple-string))
1986 (error-description (or null simple-string) :error--description))
1987 auth-response
1988 (when error
1989 (error "Login error: ~A" (cdr (assoc :error--description auth-response))))
1990 (unless access-token
1991 (error "Login error: server did not provide an access token."))
1992 (let ((auth-token (do-login-with-oidc-access-token access-token)))
1993 (alist-bind ((user-id simple-string :--id)
1994 (username simple-string :display-name))
1995 (do-lw2-post-query
1996 auth-token (alist "query"
1997 (graphql-query-string :current-user nil '(:--id :display-name))))
1998 (cache-put "auth-token-to-userid" auth-token user-id)
1999 (cache-put "auth-token-to-username" auth-token username))
2000 (set-cookie "lw2-auth-token" auth-token :max-age (1- (expt 2 31)))
2001 (redirect (if (and state (ppcre:scan "^/[^/]" state)) state "/")))))))
2003 (defmethod view-logout ((backend backend-oauth2.0-login))
2004 (request-method
2005 (:post ()
2006 (set-cookie "lw2-auth-token" "" :max-age 0)
2007 (redirect
2008 (oauth2.0-login-request-uri backend "v2/logout" (alist "client_id" (oauth2.0-client-id backend)))))))
2010 (delete-easy-handler 'view-login)
2011 (delete-easy-handler 'view-logout)
2012 (delete-easy-handler 'view-reset-password)
2014 (define-page view-library "/library"
2015 ((view :member '(:featured :community) :default :featured))
2016 (let ((sequences
2017 (lw2-graphql-query
2018 (lw2-query-string :sequence :list
2019 (alist :view (case view
2020 (:featured "curatedSequences")
2021 (:community "communitySequences")))
2022 :fields '(:--id :created-at :user-id :title :----typename)))))
2023 (view-items-index
2024 sequences
2025 :title "Sequences Library"
2026 :content-class "sequences-page"
2027 :current-uri "/library"
2028 :top-nav (lambda ()
2029 (sublevel-nav-to-html '(:featured :community)
2030 view
2031 :default :featured
2032 :param-name "view"
2033 :extra-class "sequences-view")))))
2035 (define-page view-sequence (:regex "^/s(?:equences)?/([^/?#]+)(?:/?$|\\?)" sequence-id) ()
2036 (let ((sequence (get-sequence sequence-id)))
2037 (alist-bind ((title string))
2038 sequence
2039 (emit-page (out-stream
2040 :title title
2041 :content-class "sequence-page")
2042 (sequence-to-html sequence)))))
2044 (define-component view-collection (collection-id) ()
2045 (let ((collection (get-collection collection-id)))
2046 (renderer ()
2047 (emit-page (out-stream :title (cdr (assoc :title collection)) :content-class "sequence-page collection-page")
2048 (collection-to-html collection)))))
2050 (define-component-routes lesswrong-viewer-site (view-sequences (standard-route :uri "/sequences") () (view-collection "oneQyj4pw77ynzwAF")))
2051 (define-component-routes lesswrong-viewer-site (view-codex (standard-route :uri "/codex") () (view-collection "2izXHCrmJ684AnZ5X")))
2052 (define-component-routes lesswrong-viewer-site (view-hpmor (standard-route :uri "/hpmor") () (view-collection "ywQvGBSojSQZTMpLh")))
2053 (define-component-routes ea-forum-viewer-site (view-handbook (standard-route :uri "/handbook") () (view-collection "MobebwWs2o86cS9Rd")))
2055 (define-component-routes forum-site (view-tags-index (standard-route :uri "/tags") () (view-tags-index)))
2057 (define-page view-archive (:regex "^/archive(?:/(\\d{4})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))"
2058 (year :type (mod 10000))
2059 (month :type (integer 1 12))
2060 (day :type (integer 1 31)))
2061 ((offset :type fixnum :default 0))
2062 (local-time:with-decoded-timestamp (:day current-day :month current-month :year current-year :timezone local-time:+utc-zone+) (local-time:now)
2063 (local-time:with-decoded-timestamp (:day earliest-day :month earliest-month :year earliest-year :timezone local-time:+utc-zone+) (earliest-post-time)
2064 (labels ((url-elements (&rest url-elements)
2065 (declare (dynamic-extent url-elements))
2066 (format nil "/~{~A~^/~}" url-elements))
2067 (archive-nav ()
2068 (let ((out-stream *html-output*))
2069 (with-outputs (out-stream) "<div class=\"archive-nav\"><div class=\"archive-nav-years\">")
2070 (link-if-not out-stream (not (or year month day)) (url-elements "archive") "archive-nav-item-year" "All")
2071 (loop for y from earliest-year to current-year
2072 do (link-if-not out-stream (eq y year) (url-elements "archive" y) "archive-nav-item-year" y))
2073 (format out-stream "</div>")
2074 (when year
2075 (format out-stream "<div class=\"archive-nav-months\">")
2076 (link-if-not out-stream (not month) (url-elements "archive" year) "archive-nav-item-month" "All")
2077 (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)
2078 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)))
2079 (format out-stream "</div>"))
2080 (when month
2081 (format out-stream "<div class=\"archive-nav-days\">")
2082 (link-if-not out-stream (not day) (url-elements "archive" year month) "archive-nav-item-day" "All")
2083 (loop for d from (if (and (= (or year current-year) earliest-year) (= (or month current-month) earliest-month)) earliest-day 1)
2084 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)))
2085 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))
2086 (format out-stream "</div>"))
2087 (format out-stream "</div>"))))
2088 (multiple-value-bind (posts total)
2089 (lw2-graphql-query (lw2-query-string :post :list
2090 (alist :view (if day "new" "top") :limit 51 :offset offset
2091 :after (if (and year (not day)) (format nil "~A-~A-~A" (or year earliest-year) (or month 1) (or day 1)))
2092 :before (if year (format nil "~A-~A-~A" (or year current-year) (or month 12)
2093 (or day (local-time:days-in-month (or month 12) (or year current-year))))))))
2094 (emit-page (out-stream :title "Archive" :current-uri "/archive" :content-class "archive-page"
2095 :top-nav #'archive-nav
2096 :pagination (pagination-nav-bars :items-per-page 50 :offset offset :total total :with-next (if total nil (> (length posts) 50))))
2097 (write-index-items-to-html out-stream (firstn posts 50) :empty-message "No posts for the selected period.")))))))
2099 (define-page view-about "/about" ()
2100 (emit-page (out-stream :title "About" :current-uri "/about" :content-class "about-page")
2101 (alexandria:with-input-from-file (in-stream "www/about.html" :element-type '(unsigned-byte 8))
2102 (alexandria:copy-stream in-stream out-stream))))
2104 (define-page misc-pages (:regex "^/misc-pages/.+") ()
2105 (let ((pathname (hunchentoot:request-pathname)))
2106 (unless (probe-file pathname)
2107 (error 'lw2-not-found-error))
2108 (emit-page (out-stream :title "Misc page" :content-class "misc-page")
2109 (alexandria:with-input-from-file (in-stream pathname :element-type '(unsigned-byte 8))
2110 (alexandria:copy-stream in-stream out-stream)))))
2112 (define-page view-generated-script (:regex "^/generated/([^/]+)\\.js" (name :type string)) ()
2113 (when-let ((package (find-package (string-upcase name))))
2114 (setf (hunchentoot:header-out "Content-Type") "text/javascript")
2115 (let ((stream (make-flexi-stream (hunchentoot:send-headers) :external-format :utf-8)))
2116 (write-package-client-scripts package stream))))
2118 (hunchentoot:define-easy-handler
2119 (view-proxy-asset
2120 :uri (lambda (r)
2121 (with-error-page
2122 (multiple-value-bind (match? strings) (ppcre:scan-to-strings "^/proxy-assets/([0-9A-Za-z]+)(-inverted)?$" (hunchentoot:script-name r) :sharedp t)
2123 (when-let* ((base-filename (and match? (svref strings 0)))
2124 (image-data (cache-get "cached-images" base-filename :value-type :json)))
2125 (let ((inverted (svref strings 1)))
2126 (alist-bind ((mime-type simple-string)) image-data
2127 (setf (hunchentoot:header-out "X-Content-Type-Options") "nosniff"
2128 (hunchentoot:header-out "Cache-Control") #.(format nil "public, max-age=~A, immutable" 600))
2129 (hunchentoot:handle-static-file (concatenate 'string "www/proxy-assets/" base-filename (if inverted "-inverted" "")) mime-type)
2130 t)))))))
2131 nil)