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