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