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