Fixed bug in Less theme
[lw2-viewer.git] / lw2.lisp
blobd2ac6ebcfbe8f9e22a9898e15b5f73a7bd9f0cec
1 (uiop:define-package #:lw2-viewer
2 (:use #:cl #:sb-thread #:flexi-streams #:djula
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)
4 (:unintern
5 #:define-regex-handler #:*fonts-stylesheet-uri* #:generate-fonts-link
6 #:user-nav-bar #:*primary-nav* #:*secondary-nav* #:*nav-bars*
7 #:begin-html #:end-html))
9 (in-package #:lw2-viewer)
11 (named-readtables:in-readtable html-reader)
13 (add-template-directory (asdf:system-relative-pathname "lw2-viewer" "templates/"))
15 (define-cache-database "auth-token-to-userid" "auth-token-to-username" "comment-markdown-source" "post-markdown-source")
17 (defvar *current-auth-token*)
18 (defvar *current-userid*)
19 (defvar *current-username*)
20 (defvar *current-user-slug*)
22 (defvar *read-only-mode* nil)
23 (defvar *read-only-default-message* "Due to a system outage, you cannot log in or post at this time.")
25 (defparameter *default-prefs* (alist :items-per-page 20 :default-sort "new"))
26 (defvar *current-prefs* nil)
28 (defun logged-in-userid (&optional is-userid)
29 (let ((current-userid *current-userid*))
30 (if is-userid
31 (string= current-userid is-userid)
32 current-userid)))
34 (defun logged-in-username ()
35 *current-username*)
37 (defun logged-in-user-slug ()
38 *current-user-slug*)
40 (defun pretty-time (timestring &key format)
41 (let ((time (local-time:parse-timestring timestring)))
42 (values (local-time:format-timestring nil time :timezone local-time:+utc-zone+ :format (or format '(:day #\ :short-month #\ :year #\ :hour #\: (:min 2) #\ :timezone)))
43 (* (local-time:timestamp-to-unix time) 1000))))
45 (defun pretty-number (number &optional object)
46 (let ((str (coerce (format nil "~:D~@[<span> ~A~P</span>~]" number object number) '(vector character))))
47 (if (eq (aref str 0) #\-)
48 (setf (aref str 0) #\MINUS_SIGN))
49 str))
51 (defun generate-post-auth-link (post &optional comment-id absolute need-auth)
52 (if need-auth
53 (concatenate 'string (generate-post-link post comment-id absolute) "?need-auth=y")
54 (generate-post-link post comment-id absolute)))
56 (defun clean-lw-link (url)
57 (when url
58 (ppcre:regex-replace "([^/]*//[^/]*)lesserwrong\.com" url "\\1lesswrong.com")))
60 (defun votes-to-tooltip (votes)
61 (if votes
62 (format nil "~A vote~:*~P"
63 (typecase votes (integer votes) (list (length votes))))
64 ""))
66 (defun post-section-to-html (out-stream post &key skip-section)
67 (alist-bind ((user-id string)
68 (frontpage-date (or null string))
69 (curated-date (or null string))
70 (meta boolean)
71 (af boolean)
72 (draft boolean))
73 post
74 (format out-stream "~1{<a class=\"post-section ~A\" title=\"~A\"~1@{ href=\"~A\"~}></a>~}"
75 (cond (af (if (eq skip-section :alignment-forum) nil (list "alignment-forum" "View Alignment Forum posts" "/index?view=alignment-forum")))
76 ; show alignment forum even if skip-section is t
77 ((eq skip-section t) nil)
78 (draft nil)
79 (curated-date (if (eq skip-section :featured) nil (list "featured" "View Featured posts" "/index?view=featured")))
80 (frontpage-date (if (eq skip-section :frontpage) nil (list "frontpage" "View Frontpage posts" "/")))
81 (meta (if (eq skip-section :meta) nil (list "meta" "View Meta posts" "/index?view=meta")))
82 (t (if (eq skip-section :personal) nil (list "personal" (format nil "View posts by ~A" (get-username user-id)) (format nil "/users/~A?show=posts" (get-user-slug user-id)))))))))
84 (defun post-headline-to-html (out-stream post &key skip-section need-auth)
85 (alist-bind ((post-id string :--id)
86 (title string)
87 (user-id string)
88 (url (or null string))
89 (posted-at string)
90 (base-score fixnum)
91 (comment-count (or null fixnum))
92 (page-url (or null string))
93 (word-count (or null fixnum))
94 (frontpage-date (or null string))
95 (curated-date (or null string))
96 (meta boolean)
97 (af boolean)
98 (question boolean)
99 (vote-count (or null fixnum))
100 (draft boolean))
101 post
102 (multiple-value-bind (pretty-time js-time) (pretty-time posted-at)
103 (format out-stream "<h1 class=\"listing~:[~; link-post-listing~]~:[~; question-post-listing~]~:[~; own-post-listing~]\">~@[<a href=\"~A\">&#xf0c1;</a>~]<a href=\"~A\">~:[~;<span class=\"post-type-prefix\">[Question] </span>~]~A</a>~@[<a class=\"edit-post-link button\" href=\"/edit-post?post-id=~A\"></a>~]</h1>"
105 question
106 (logged-in-userid user-id)
107 (if url (encode-entities (convert-any-link (string-trim " " url))))
108 (generate-post-auth-link post nil nil need-auth)
109 question
110 (clean-text-to-html title)
111 (if (logged-in-userid user-id) post-id))
112 (format out-stream "<div class=\"post-meta\"><a class=\"author~:[~; own-user-author~]\" href=\"/users/~A\" data-userid=\"~A\">~A</a> <div class=\"date\" data-js-date=\"~A\">~A</div><div class=\"karma\"><span class=\"karma-value\" title=\"~A\">~A</span></div><a class=\"comment-count\" href=\"~A#comments\">~A</a>~:[~*~;~:*<span class=\"read-time\" title=\"~:D word~:P\">~:D<span> min read</span></span>~]~:[~*~;~:*<a class=\"lw2-link\" href=\"~A\">~A<span> link</span></a>~]"
113 (logged-in-userid user-id)
114 (encode-entities (get-user-slug user-id))
115 (encode-entities user-id)
116 (encode-entities (get-username user-id))
117 js-time
118 pretty-time
119 (votes-to-tooltip vote-count)
120 (pretty-number base-score "point")
121 (generate-post-link post)
122 (pretty-number (or comment-count 0) "comment")
123 word-count
124 (and word-count (max 1 (round word-count 300)))
125 (clean-lw-link page-url)
126 (main-site-abbreviation *current-site*)))
127 (post-section-to-html out-stream post :skip-section skip-section)
128 (if url (format out-stream "<div class=\"link-post-domain\">(~A)</div>" (encode-entities (puri:uri-host (puri:parse-uri (string-trim " " url))))))
129 (format out-stream "</div>")))
131 (defun post-body-to-html (out-stream post)
132 (alist-bind ((post-id string :--id)
133 (title string)
134 (user-id string)
135 (url (or null string))
136 (posted-at string)
137 (base-score fixnum)
138 (comment-count (or null fixnum))
139 (page-url (or null string))
140 (frontpage-date (or null string))
141 (curated-date (or null string))
142 (meta boolean)
143 (draft boolean)
144 (af boolean)
145 (question boolean)
146 (vote-count (or null fixnum))
147 (html-body (or null string)))
148 post
149 (multiple-value-bind (pretty-time js-time) (pretty-time posted-at)
150 (format out-stream "<div class=\"post~:[~; link-post~]~:[~; question-post~]\"><h1 class=\"post-title\">~:*~:[~;<span class=\"post-type-prefix\">[Question] </span>~]~A</h1><div class=\"post-meta\"><a class=\"author~:[~; own-user-author~]\" href=\"/users/~A\" data-userid=\"~A\">~A</a> <div class=\"date\" data-js-date=\"~A\">~A</div><div class=\"karma\" data-post-id=\"~A\"><span class=\"karma-value\" title=\"~A\">~A</span></div><a class=\"comment-count\" href=\"#comments\">~A</a>~:[~*~;~:*<a class=\"lw2-link\" href=\"~A\">~A<span> link</span></a>~]"
152 question
153 (clean-text-to-html title :hyphenation nil)
154 (logged-in-userid user-id)
155 (encode-entities (get-user-slug user-id))
156 (encode-entities user-id)
157 (encode-entities (get-username user-id))
158 js-time
159 pretty-time
160 post-id
161 (votes-to-tooltip vote-count)
162 (pretty-number base-score "point")
163 (pretty-number (or comment-count 0) "comment")
164 (clean-lw-link page-url)
165 (main-site-abbreviation *current-site*)))
166 (post-section-to-html out-stream post)
167 (format out-stream "</div><div class=\"post-body\">")
168 (if url (format out-stream "<p><a href=\"~A\" class=\"link-post-link\">Link post</a></p>" (encode-entities (convert-any-link (string-trim " " url)))))
169 (write-sequence (clean-html* (or html-body "") :with-toc t :post-id post-id) out-stream)
170 (format out-stream "</div></div>")))
172 (defparameter *comment-individual-link* nil)
174 (defun comment-to-html (out-stream comment &key with-post-title)
175 (if (or (cdr (assoc :deleted comment)) (cdr (assoc :deleted-public comment)))
176 (format out-stream "<div class=\"comment deleted-comment\"><div class=\"comment-meta\"><span class=\"deleted-meta\">[ ]</span></div><div class=\"comment-body\">[deleted]</div></div>")
177 (alist-bind ((comment-id string :--id)
178 (user-id string)
179 (posted-at string)
180 (highlight-new boolean)
181 (post-id string)
182 (base-score fixnum)
183 (page-url (or null string))
184 (parent-comment list)
185 (parent-comment-id (or null string))
186 (child-count (or null fixnum))
187 (children list)
188 (vote-count (or null fixnum))
189 (retracted boolean)
190 (answer boolean)
191 (parent-answer-id (or null string))
192 (html-body string))
193 comment
194 (multiple-value-bind (pretty-time js-time) (pretty-time posted-at)
195 <div class=("comment~{ ~A~}"
196 (list-cond
197 ((and (logged-in-userid user-id)
198 (< (* 1000 (local-time:timestamp-to-unix (local-time:now))) (+ js-time 15000)))
199 "just-posted-comment")
200 (highlight-new "comment-item-highlight")
201 (retracted "retracted")))>
202 <div class="comment-meta">
203 <a class=("author~:[~; own-user-author~]" (logged-in-userid user-id))
204 href=("/users/~A" (encode-entities (get-user-slug user-id)))
205 data-userid=user-id>
206 (get-username user-id)
207 </a>
208 <a class="date" href=(generate-post-link post-id comment-id) data-js-date=js-time> (safe pretty-time) </a>
209 <div class="karma">
210 <span class="karma-value" title=(votes-to-tooltip vote-count)> (safe (pretty-number base-score "point")) </span>
211 </div>
212 <a class="permalink" href=("~A/~A/~A"
213 (generate-post-link post-id)
214 (cond ((or answer parent-answer-id) "answer") (t "comment"))
215 comment-id)
216 title="Permalink"></a>
217 (with-html-stream-output
218 (when page-url
219 <a class="lw2-link" href=(clean-lw-link page-url) title=(main-site-abbreviation *current-site*)></a>)
220 (if with-post-title
221 <div class="comment-post-title">
222 (with-html-stream-output
223 (when parent-comment
224 (alist-bind ((user-id string)
225 (post-id string)
226 (parent-id string :--id))
227 parent-comment
228 <span class="comment-in-reply-to">in reply to:
229 <a href=("/users/~A" (get-user-slug user-id))
230 class=("inline-author~:[~; own-user-author~]" (logged-in-userid user-id))
231 data-userid=(progn user-id)>
232 (get-username user-id)</a>'s
233 <a href=(generate-post-link post-id parent-id)>comment</a>
234 (progn " ")
235 </span>)))
236 <span class="comment-post-title2">on: <a href=(generate-post-link post-id)>(safe (clean-text-to-html (get-post-title post-id)))</a></span>
237 </div>
238 (when parent-comment-id
239 (if *comment-individual-link*
240 <a class="comment-parent-link" href=(progn parent-comment-id) title="Parent"></a>
241 <a class="comment-parent-link" href=("#comment-~A" parent-comment-id)>Parent</a>)))
242 (when children
243 <div class="comment-child-links">
244 Replies:
245 (with-html-stream-output
246 (dolist (child children)
247 (alist-bind ((comment-id string)
248 (user-id string))
249 child
250 <a href=("#comment-~A" comment-id)>(">~A" (get-username user-id))</a>)))
251 </div>)
252 <div class="comment-minimize-button"
253 data-child-count=(progn child-count)>
254 </div>)
255 </div>
256 <div class="comment-body" (safe ("~@[ data-markdown-source=\"~A\"~]"
257 (if (logged-in-userid user-id)
258 (encode-entities
259 (or (cache-get "comment-markdown-source" comment-id)
260 html-body)))))>
261 (with-html-stream-output (write-sequence (clean-html* html-body) out-stream))
262 </div>
263 </div>))))
265 (defun postprocess-conversation-title (title)
266 (if (or (null title) (string= title ""))
267 "[Untitled conversation]"
268 title))
270 (defun conversation-message-to-html (out-stream message)
271 (alist-bind ((user-id string)
272 (created-at string)
273 (highlight-new boolean)
274 (conversation list)
275 (content list)
276 (html-body (or string null)))
277 message
278 (multiple-value-bind (pretty-time js-time) (pretty-time created-at)
279 (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</span><div class=\"comment-post-title\">Private message in: <a href=\"/conversation?id=~A\">~A</a></div></div><div class=\"comment-body\">"
280 (if highlight-new " comment-item-highlight" "")
281 (encode-entities (get-user-slug user-id))
282 (encode-entities (get-username user-id))
283 js-time
284 pretty-time
285 (encode-entities (cdr (assoc :--id conversation)))
286 (encode-entities (postprocess-conversation-title (cdr (assoc :title conversation))))))
287 (if html-body
288 (write-sequence (clean-html* html-body) out-stream)
289 (format out-stream "~{<p>~A</p>~}" (loop for block in (cdr (assoc :blocks content)) collect (encode-entities (cdr (assoc :text block))))))
290 (format out-stream "</div></div>")))
292 (defun conversation-index-to-html (out-stream conversation)
293 (alist-bind ((conversation-id string :--id)
294 (title (or null string))
295 (created-at (or null string))
296 (participants list)
297 (messages-total fixnum))
298 conversation
299 (multiple-value-bind (pretty-time js-time) (if created-at (pretty-time created-at) (values "[Error]" 0))
300 (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</div></div>"
301 (encode-entities conversation-id)
302 (encode-entities (postprocess-conversation-title title))
303 (loop for p in participants
304 collect (list (encode-entities (cdr (assoc :slug p))) (encode-entities (cdr (assoc :display-name p)))))
305 (pretty-number messages-total "message")
306 js-time
307 pretty-time))))
309 (defun error-to-html (out-stream condition)
310 (format out-stream "<div class=\"gw-error\"><h1>Error</h1><p>~A</p></div>"
311 (encode-entities (princ-to-string condition))))
313 (defmacro with-error-html-block ((out-stream) &body body)
314 "If an error occurs within BODY, write an HTML representation of the
315 signaled condition to OUT-STREAM."
316 `(handler-case
317 (progn ,@body)
318 (serious-condition (c) (error-to-html ,out-stream c))))
320 (defun make-comment-parent-hash (comments)
321 (let ((existing-comment-hash (make-hash-table :test 'equal))
322 (hash (make-hash-table :test 'equal)))
323 (dolist (c comments)
324 (alexandria:if-let (id (cdr (assoc :--id c)))
325 (setf (gethash id existing-comment-hash) t)))
326 (dolist (c comments)
327 (let* ((parent-id (cdr (assoc :parent-comment-id c)))
328 (old (gethash parent-id hash)))
329 (setf (gethash parent-id hash) (cons c old))
330 (when (and parent-id (not (gethash parent-id existing-comment-hash)))
331 (let ((placeholder (alist :--id parent-id :parent-comment-id nil :deleted t)))
332 (setf (gethash parent-id existing-comment-hash) t
333 (gethash nil hash) (cons placeholder (gethash nil hash)))))))
334 (maphash (lambda (k old)
335 (setf (gethash k hash) (nreverse old)))
336 hash)
337 (labels
338 ((count-children (parent)
339 (let ((children (gethash (cdr (assoc :--id parent)) hash)))
340 (+ (length children) (apply #'+ (map 'list #'count-children children)))))
341 (add-child-counts (comment-list)
342 (loop for c in comment-list
343 as id = (cdr (assoc :--id c))
344 do (setf (gethash id hash) (add-child-counts (gethash id hash)))
345 collecting (cons (cons :child-count (count-children c)) c))))
346 (setf (gethash nil hash) (add-child-counts (gethash nil hash))))
347 hash))
349 (defun comment-thread-to-html (out-stream emit-comment-item-fn)
350 (format out-stream "<ul class=\"comment-thread\">")
351 (funcall emit-comment-item-fn)
352 (format out-stream "</ul>"))
354 (defun comment-item-to-html (out-stream comment &key extra-html-fn)
355 (with-error-html-block (out-stream)
356 (let ((c-id (cdr (assoc :--id comment))))
357 (format out-stream "<li id=\"comment-~A\" class=\"comment-item\">" c-id)
358 (unwind-protect
359 (comment-to-html out-stream comment)
360 (if extra-html-fn (funcall extra-html-fn c-id))
361 (format out-stream "</li>")))))
363 (defun comment-tree-to-html (out-stream comment-hash &optional (target nil) (level 0))
364 (let ((comments (gethash target comment-hash)))
365 (when comments
366 (comment-thread-to-html out-stream
367 (lambda ()
368 (loop for c in comments do
369 (comment-item-to-html out-stream c
370 :extra-html-fn (lambda (c-id)
371 (if (and (= level 10) (gethash c-id comment-hash))
372 (format out-stream "<input type=\"checkbox\" id=\"expand-~A\"><label for=\"expand-~:*~A\" data-child-count=\"~A comment~:P\">Expand this thread</label>"
373 c-id
374 (cdr (assoc :child-count c))))
375 (comment-tree-to-html out-stream comment-hash c-id (1+ level))))))))))
377 (defun comment-chrono-to-html (out-stream comments)
378 (let ((comment-hash (make-comment-parent-hash comments))
379 (comments-sorted (sort comments #'local-time:timestamp< :key (lambda (c) (local-time:parse-timestring (cdr (assoc :posted-at c)))))))
380 (comment-thread-to-html out-stream
381 (lambda ()
382 (loop for c in comments-sorted do
383 (let* ((c-id (cdr (assoc :--id c)))
384 (new-c (acons :children (gethash c-id comment-hash) c)))
385 (comment-item-to-html out-stream new-c)))))))
387 (defun comment-post-interleave (list &key limit offset (sort-by :date))
388 (multiple-value-bind (sort-fn sort-key)
389 (ecase sort-by
390 (:date (values #'local-time:timestamp> (lambda (x) (local-time:parse-timestring (cdr (assoc :posted-at x))))))
391 (:score (values #'> (lambda (x) (cdr (assoc :base-score x))))))
392 (let ((sorted (sort list sort-fn :key sort-key)))
393 (loop for end = (if (or limit offset) (+ (or limit 0) (or offset 0)))
394 for x in sorted
395 for count from 0
396 until (and end (>= count end))
397 when (or (not offset) (>= count offset))
398 collect x))))
400 (defun write-index-items-to-html (out-stream items &key need-auth (empty-message "No entries.") skip-section)
401 (if items
402 (dolist (x items)
403 (with-error-html-block (out-stream)
404 (cond
405 ((typep x 'condition)
406 (error-to-html out-stream x))
407 ((assoc :message x)
408 (format out-stream "<p>~A</p>" (cdr (assoc :message x))))
409 ((string= (cdr (assoc :----typename x)) "Message")
410 (format out-stream "<ul class=\"comment-thread\"><li class=\"comment-item\">")
411 (unwind-protect
412 (conversation-message-to-html out-stream x)
413 (format out-stream "</li></ul>")))
414 ((string= (cdr (assoc :----typename x)) "Conversation")
415 (conversation-index-to-html out-stream x))
416 ((assoc :comment-count x)
417 (post-headline-to-html out-stream x :need-auth need-auth :skip-section skip-section))
419 (format out-stream "<ul class=\"comment-thread\"><li class=\"comment-item\" id=\"comment-~A\">" (cdr (assoc :--id x)))
420 (unwind-protect
421 (comment-to-html out-stream x :with-post-title t)
422 (format out-stream "</li></ul>"))))))
423 (format out-stream "<div class=\"listing-message\">~A</div>" empty-message)))
425 (defun write-index-items-to-rss (out-stream items &key title need-auth)
426 (let ((full-title (format nil "~@[~A - ~]~A" title (site-title *current-site*))))
427 (xml-emitter:with-rss2 (out-stream :encoding "UTF-8")
428 (xml-emitter:rss-channel-header full-title (site-uri *current-site*) :description full-title)
429 (labels ((emit-item (item &key title link (guid (cdr (assoc :--id item))) (author (get-username (cdr (assoc :user-id item))))
430 (date (pretty-time (cdr (assoc :posted-at item)) :format local-time:+rfc-1123-format+)) body)
431 (xml-emitter:rss-item
432 title
433 :link link
434 :author author
435 :pubDate date
436 :guid guid
437 :description body)))
438 (dolist (item items)
439 (if (assoc :comment-count item)
440 (let ((author (get-username (cdr (assoc :user-id item)))))
441 (emit-item item
442 :title (clean-text (format nil "~A by ~A" (cdr (assoc :title item)) author))
443 :author author
444 :link (generate-post-auth-link item nil t need-auth)
445 :body (clean-html (or (cdr (assoc :html-body (get-post-body (cdr (assoc :--id item)) :revalidate nil))) "") :post-id (cdr (assoc :--id item)))))
446 (emit-item item
447 :title (format nil "Comment by ~A on ~A" (get-username (cdr (assoc :user-id item))) (get-post-title (cdr (assoc :post-id item))))
448 :link (generate-post-link (cdr (assoc :post-id item)) (cdr (assoc :--id item)) t)
449 :body (clean-html (cdr (assoc :html-body item))))))))))
451 (defparameter *fonts-stylesheet-uris*
452 '("https://fonts.greaterwrong.com/?fonts=InconsolataGW,CharterGW,ConcourseGW,Whitney,MundoSans,SourceSansPro,Raleway,ProximaNova,TiredOfCourier,AnonymousPro,InputSans,InputSansNarrow,InputSansCondensed,GaramondPremierPro,TriplicateCode,TradeGothic,NewsGothicBT,Caecilia,SourceSerifPro,SourceCodePro"
453 "https://fonts.greaterwrong.com/?fonts=BitmapFonts,FontAwesomeGW&base64encode=1"))
454 ;(defparameter *fonts-stylesheet-uris* '("https://fonts.greaterwrong.com/?fonts=*"))
456 (defvar *fonts-redirect-data* nil)
457 (sb-ext:defglobal *fonts-redirect-lock* (make-mutex))
458 (sb-ext:defglobal *fonts-redirect-thread* nil)
460 (defun generate-fonts-links ()
461 (let ((current-time (get-unix-time)))
462 (labels ((get-redirects (uri-list)
463 (loop for request-uri in uri-list collect
464 (multiple-value-bind (body status headers uri)
465 (drakma:http-request request-uri :method :head :close t :redirect nil :additional-headers (alist :referer (site-uri (first *sites*)) :accept "text/css,*/*;q=0.1"))
466 (declare (ignore body uri))
467 (let ((location (cdr (assoc :location headers))))
468 (if (and (typep status 'integer) (< 300 status 400) location)
469 location
470 nil)))))
471 (update-redirects ()
472 (handler-case
473 (let* ((new-redirects (get-redirects *fonts-stylesheet-uris*))
474 (new-redirects (loop for new-redirect in new-redirects
475 for original-uri in *fonts-stylesheet-uris*
476 collect (if new-redirect (quri:render-uri (quri:merge-uris (quri:uri new-redirect) (quri:uri original-uri))) original-uri))))
477 (with-mutex (*fonts-redirect-lock*) (setf *fonts-redirect-data* (list *fonts-stylesheet-uris* new-redirects current-time)
478 *fonts-redirect-thread* nil))
479 new-redirects)
480 (serious-condition () *fonts-stylesheet-uris*)))
481 (ensure-update-thread ()
482 (with-mutex (*fonts-redirect-lock*)
483 (or *fonts-redirect-thread*
484 (setf *fonts-redirect-thread* (make-thread #'update-redirects :name "fonts redirect update"))))))
485 (destructuring-bind (&optional base-uris redirect-uris timestamp) (with-mutex (*fonts-redirect-lock*) *fonts-redirect-data*)
486 (if (and (eq base-uris *fonts-stylesheet-uris*) timestamp)
487 (progn
488 (if (>= current-time (+ timestamp 60))
489 (ensure-update-thread))
490 (or redirect-uris *fonts-stylesheet-uris*))
491 (update-redirects))))))
493 (defparameter *html-head*
494 (format nil
495 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
496 <meta name=\"HandheldFriendly\" content=\"True\" />"))
498 (defparameter *extra-external-scripts* "")
499 (defparameter *extra-inline-scripts* "")
501 (defun generate-versioned-link (file)
502 (format nil "~A?v=~A" file (sb-posix:stat-mtime (sb-posix:stat (format nil "www~A" file)))))
504 (defun search-bar-to-html (out-stream)
505 (declare (special *current-search-query*))
506 (let ((query (and (boundp '*current-search-query*) (hunchentoot:escape-for-html *current-search-query*))))
507 (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*))))
509 (defun inbox-to-html (out-stream user-slug &optional new-messages)
510 (let* ((target-uri (format nil "/users/~A?show=inbox" user-slug))
511 (as-link (string= (hunchentoot:request-uri*) target-uri)))
512 (multiple-value-bind (nm-class nm-text)
513 (if new-messages (values "new-messages" "New messages") (values "no-messages" "Inbox"))
514 (format out-stream "<~:[a href=\"~A\"~;span~*~] id=\"inbox-indicator\" class=\"~A\" accesskey=\"o\" title=\"~A~:[ [o]~;~]\">~A</a>"
515 as-link target-uri nm-class nm-text as-link nm-text))))
517 (defmethod site-nav-bars ((site site))
518 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
519 ("about" "/about" "About" :accesskey "t")
520 user-nav-item))
521 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
522 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
524 (defmethod site-nav-bars ((site lesswrong-viewer-site))
525 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
526 ("about" "/about" "About" :accesskey "t")
527 ("search" "/search" "Search" :html search-bar-to-html)
528 user-nav-item))
529 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
530 ("featured" "/index?view=featured" "Featured" :description "Latest featured posts" :accesskey "f")
531 ("all" "/index?view=all" "All" :description "Latest posts from all sections" :accesskey "a")
532 ("meta" "/index?view=meta" "Meta" :description "Latest meta posts" :accesskey "m")
533 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
535 (defmethod site-nav-bars ((site ea-forum-viewer-site))
536 '((:secondary-bar (("archive" "/archive" "Archive" :accesskey "r")
537 ("about" "/about" "About" :accesskey "t")
538 ("search" "/search" "Search" :html search-bar-to-html)
539 user-nav-item))
540 (:primary-bar (("home" "/" "Home" :description "Latest frontpage posts" :accesskey "h")
541 ("all" "/index?view=all" "All" :description "Latest posts from all sections" :accesskey "a")
542 ("meta" "/index?view=community" "Community" :description "Latest community posts" :accesskey "m")
543 ("recent-comments" "/recentcomments" "<span>Recent </span>Comments" :description "Latest comments" :accesskey "c")))))
545 (defun prepare-nav-bar (nav-bar current-uri)
546 (list (first nav-bar)
547 (map 'list (lambda (item) (if (listp item) item (funcall item current-uri)))
548 (second nav-bar))))
550 (defun nav-item-active (item current-uri)
551 (when item
552 (destructuring-bind (id uri name &key description html accesskey nofollow trailing-html override-uri) item
553 (declare (ignore id name description html accesskey nofollow trailing-html))
554 (string= (or override-uri uri) current-uri))))
556 (defun nav-bar-active (nav-bar current-uri)
557 (some (lambda (x) (nav-item-active x current-uri)) (second nav-bar)))
559 (defun nav-bar-inner (out-stream items &optional current-uri)
560 (maplist (lambda (items)
561 (let ((item (first items)))
562 (destructuring-bind (id uri name &key description html accesskey nofollow trailing-html override-uri) item
563 (declare (ignore override-uri))
564 (let* ((item-active (nav-item-active item current-uri))
565 (nav-class (format nil "nav-item ~:[nav-inactive~;nav-current~]~:[~; nav-item-last-before-current~]"
566 item-active (and (not item-active) (nav-item-active (cadr items) current-uri)))))
567 (format out-stream "<span id=\"nav-item-~A\" class=\"~A\" ~@[title=\"~A\"~]>"
568 id nav-class description)
569 (if html
570 (funcall html out-stream)
571 (link-if-not out-stream item-active uri "nav-inner" name :accesskey accesskey :nofollow nofollow))
572 (if trailing-html
573 (funcall trailing-html out-stream))
574 (format out-stream "</span>")))))
575 items))
577 (defun nav-bar-outer (out-stream class nav-bar &optional current-uri)
578 (format out-stream "<div id=\"~A\" class=\"nav-bar~@[ ~A~]\">" (string-downcase (first nav-bar)) class)
579 (nav-bar-inner out-stream (second nav-bar) current-uri)
580 (format out-stream "</div>"))
582 (defun nav-bar-to-html (out-stream &optional current-uri)
583 (let* ((nav-bars (map 'list (lambda (x) (prepare-nav-bar x current-uri)) (site-nav-bars *current-site*)))
584 (active-bar (or (find-if (lambda (x) (nav-bar-active x current-uri)) nav-bars) (car (last nav-bars))))
585 (inactive-bars (remove active-bar nav-bars)))
586 (dolist (bar inactive-bars)
587 (nav-bar-outer out-stream "inactive-bar" bar current-uri))
588 (nav-bar-outer out-stream "active-bar" active-bar current-uri)))
590 (defun user-nav-item (&optional current-uri)
591 (if *read-only-mode*
592 `("login" "/login" "Read Only Mode" :html ,(lambda () (format nil "<span class=\"nav-inner\" title=\"~A\">[Read Only Mode]</span>"
593 (typecase *read-only-mode*
594 (string *read-only-mode*)
595 (t *read-only-default-message*)))))
596 (alexandria:if-let (username (logged-in-username))
597 (let ((user-slug (encode-entities (logged-in-user-slug))))
598 `("login" ,(format nil "/users/~A" user-slug) ,(plump:encode-entities username) :description "User page" :accesskey "u"
599 :trailing-html ,(lambda (out-stream) (inbox-to-html out-stream user-slug))))
600 `("login" ,(format nil "/login?return=~A" (url-rewrite:url-encode current-uri)) "Log In" :accesskey "u" :nofollow t :override-uri "/login"))))
602 (defun sublevel-nav-to-html (out-stream options current &key default (base-uri (hunchentoot:request-uri*)) (param-name "show") (remove-params '("offset")) extra-class)
603 (declare (type (or null string) extra-class))
604 (format out-stream "<div class=\"sublevel-nav~@[ ~A~]\">" extra-class)
605 (loop for item in options
606 do (multiple-value-bind (param-value text) (if (atom item)
607 (values (string-downcase item) (string-capitalize item))
608 (values-list item))
609 (let* ((selected (string-equal current param-value))
610 (class (if selected "sublevel-item selected" "sublevel-item")))
611 (link-if-not out-stream selected (apply #'replace-query-params base-uri param-name (unless (string-equal param-value default) param-value)
612 (loop for x in remove-params nconc (list x nil)))
613 class text))))
614 (format out-stream "</div>"))
616 (defun make-csrf-token (&optional (session-token (hunchentoot:cookie-in "session-token")) (nonce (ironclad:make-random-salt)))
617 (if (typep session-token 'string) (setf session-token (base64:base64-string-to-usb8-array session-token)))
618 (let ((csrf-token (concatenate '(vector (unsigned-byte 8)) nonce (ironclad:digest-sequence :sha256 (concatenate '(vector (unsigned-byte 8)) nonce session-token)))))
619 (values (base64:usb8-array-to-base64-string csrf-token) csrf-token)))
621 (defun check-csrf-token (csrf-token &optional (session-token (hunchentoot:cookie-in "session-token")))
622 (let* ((session-token (base64:base64-string-to-usb8-array session-token))
623 (csrf-token (base64:base64-string-to-usb8-array csrf-token))
624 (correct-token (nth-value 1 (make-csrf-token session-token (subseq csrf-token 0 16)))))
625 (assert (ironclad:constant-time-equal csrf-token correct-token) nil "CSRF check failed.")
626 t))
628 (defun generate-css-link ()
629 (labels ((gen-inner (theme os)
630 (generate-versioned-link (format nil "/style~@[-~A~].~A.css" (if (and theme (> (length theme) 0)) theme) os))))
631 (let* ((ua (hunchentoot:header-in* :user-agent))
632 (theme (hunchentoot:cookie-in "theme"))
633 (os (cond ((search "Windows" ua) "windows")
634 ((search "Mac OS" ua) "mac")
635 (t "linux"))))
636 (handler-case (gen-inner theme os)
637 (serious-condition () (gen-inner nil os))))))
639 (defun html-body (out-stream fn &key title description current-uri content-class robots)
640 (let* ((session-token (hunchentoot:cookie-in "session-token"))
641 (csrf-token (and session-token (make-csrf-token session-token))))
642 (format out-stream "<!DOCTYPE html><html lang=\"en-US\"><head>")
643 (format out-stream "<script>window.GW = { }; loggedInUserId=\"~A\"; loggedInUserDisplayName=\"~A\"; loggedInUserSlug=\"~A\"; ~@[GW.csrfToken=\"~A\"; ~]~A</script>~A"
644 (or (logged-in-userid) "")
645 (or (logged-in-username) "")
646 (or (logged-in-user-slug) "")
647 csrf-token
648 (load-time-value (with-open-file (s "www/head.js") (uiop:slurp-stream-string s)) t)
649 *extra-inline-scripts*)
650 (format out-stream "~A<link rel=\"stylesheet\" href=\"~A\">~{<link rel=\"stylesheet\" href=\"~A\">~}<link rel=\"shortcut icon\" href=\"~A\">"
651 *html-head*
652 (generate-css-link)
653 (generate-fonts-links)
654 (generate-versioned-link "/favicon.ico"))
655 (format out-stream "<script src=\"~A\" async></script>~A"
656 (generate-versioned-link "/script.js")
657 *extra-external-scripts*)
658 (format out-stream "<title>~@[~A - ~]~A</title>~@[<meta name=\"description\" content=\"~A\">~]~@[<meta name=\"robots\" content=\"~A\">~]"
659 (if title (encode-entities title))
660 (site-title *current-site*)
661 description
662 robots)
663 (format out-stream "</head>"))
664 (unwind-protect
665 (progn
666 (format out-stream "<body><div id=\"content\"~@[ class=\"~A\"~]>"
667 content-class)
668 (nav-bar-to-html out-stream (or current-uri (replace-query-params (hunchentoot:request-uri*) "offset" nil "sort" nil)))
669 (force-output out-stream)
670 (funcall fn))
671 (format out-stream "</div></body></html>")))
673 (defun replace-query-params (uri &rest params)
674 (let* ((quri (quri:uri uri))
675 (old-params (quri:uri-query-params quri))
676 (new-params (loop with out = old-params
677 for (param value) on params by #'cddr
678 do (if value
679 (alexandria:if-let (old-cons (assoc param out :test #'equal))
680 (setf (cdr old-cons) value)
681 (setf out (nconc out (list (cons param value)))))
682 (setf out (remove-if (lambda (x) (equal (car x) param)) out)))
683 finally (return out))))
684 (if new-params
685 (setf (quri:uri-query-params quri) new-params)
686 (setf (quri:uri-query quri) nil))
687 (quri:render-uri quri)))
689 (defun pagination-nav-bars (&key offset total with-next (items-per-page (user-pref :items-per-page)))
690 (lambda (out-stream fn)
691 (labels ((pages-to-end (n) (< (+ offset (* items-per-page n)) total)))
692 (let* ((with-next (if total (pages-to-end 1) with-next))
693 (next (if (and offset with-next) (+ offset items-per-page)))
694 (prev (if (and offset (>= offset items-per-page)) (- offset items-per-page)))
695 (request-uri (hunchentoot:request-uri*))
696 (first-uri (if (and prev (> prev 0)) (replace-query-params request-uri "offset" nil)))
697 (prev-uri (if prev (replace-query-params request-uri "offset" (if (= prev 0) nil prev))))
698 (next-uri (if next (replace-query-params request-uri "offset" next)))
699 (last-uri (if (and total offset (pages-to-end 2))
700 (replace-query-params request-uri "offset" (- total (mod (- total 1) items-per-page) 1)))))
701 (if (or next prev last-uri)
702 (labels ((write-item (uri class title accesskey)
703 (format out-stream "<a href=\"~A\" class=\"button nav-item-~A~:[ disabled~;~]\" title=\"~A [~A]\" accesskey=\"~A\"></a>"
704 (or uri "#") class uri title accesskey accesskey)))
705 (format out-stream "<div id='top-nav-bar'>")
706 (write-item first-uri "first" "First page" "\\")
707 (write-item prev-uri "prev" "Previous page" "[")
708 (format out-stream "<span class='page-number'><span class='page-number-label'>Page</span> ~A</span>" (+ 1 (/ (or offset 0) items-per-page)))
709 (write-item next-uri "next" "Next page" "]")
710 (write-item last-uri "last" "Last page" "/")
711 (format out-stream "</div>")))
712 (funcall fn)
713 (nav-bar-outer out-stream nil (list :bottom-bar
714 (list-cond
715 (first-uri `("first" ,first-uri "Back to first"))
716 (prev-uri `("prev" ,prev-uri "Previous" :nofollow t))
717 (t `("top" "#top" "Back to top"))
718 (next-uri `("next" ,next-uri "Next" :nofollow t))
719 (last-uri `("last" ,last-uri "Last" :nofollow t)))))
720 (format out-stream "<script>document.querySelectorAll('#bottom-bar').forEach(bb => { bb.classList.add('decorative'); });</script>")))))
722 (defun map-output (out-stream fn list)
723 (loop for item in list do (write-string (funcall fn item) out-stream)))
725 (defmacro with-outputs ((out-stream) &body body)
726 (alexandria:with-gensyms (stream-sym)
727 (let ((out-body (map 'list (lambda (x) `(princ ,x ,stream-sym)) body)))
728 `(let ((,stream-sym ,out-stream))
729 ,.out-body))))
731 (defun call-with-emit-page (out-stream fn &key title description current-uri content-class (return-code 200) robots (pagination (pagination-nav-bars)) top-nav)
732 (declare (ignore return-code))
733 (ignore-errors
734 (log-conditions
735 (html-body out-stream
736 (lambda ()
737 (when top-nav (funcall top-nav out-stream))
738 (funcall pagination out-stream fn))
739 :title title :description description :current-uri current-uri :content-class content-class :robots robots)
740 (force-output out-stream))))
742 (defun set-cookie (key value &key (max-age (- (expt 2 31) 1)) (path "/"))
743 (hunchentoot:set-cookie key :value value :path path :max-age max-age :secure (site-secure *current-site*)))
745 (defun set-default-headers (return-code)
746 (let ((push-option (if (hunchentoot:cookie-in "push") '("nopush"))))
747 (setf (hunchentoot:content-type*) "text/html; charset=utf-8"
748 (hunchentoot:return-code*) return-code
749 (hunchentoot:header-out :link) (format nil "~:{<~A>;rel=preload;type=~A;as=~A~@{;~A~}~:^,~}"
750 `((,(generate-css-link) "text/css" "style" ,.push-option)
751 ,.(loop for link in (generate-fonts-links)
752 collect (list* link "text/css" "style" push-option))
753 (,(generate-versioned-link "/script.js") "text/javascript" "script" ,.push-option))))
754 (unless push-option (set-cookie "push" "t" :max-age (* 4 60 60)))))
756 (defun user-pref (key)
757 (or (cdr (assoc key *current-prefs*))
758 (cdr (assoc key *default-prefs*))))
760 (defun set-user-pref (key value)
761 (assert (boundp 'hunchentoot:*reply*))
762 (setf *current-prefs* (remove-duplicates (acons key value *current-prefs*) :key #'car :from-end t))
763 (set-cookie "prefs" (quri:url-encode (json:encode-json-to-string *current-prefs*))))
765 (defmacro with-response-stream ((out-stream) &body body) `(call-with-response-stream (lambda (,out-stream) ,.body)))
767 (defun call-with-response-stream (fn)
768 (let ((*html-output* (make-flexi-stream (hunchentoot:send-headers) :external-format :utf-8)))
769 (funcall fn *html-output*)))
771 (defmacro emit-page ((out-stream &rest args &key (return-code 200) &allow-other-keys) &body body)
772 (alexandria:once-only (return-code)
773 `(progn
774 (set-default-headers ,return-code)
775 (with-response-stream (,out-stream)
776 (call-with-emit-page ,out-stream
777 (lambda () ,@body)
778 ,@args)))))
780 (defun call-with-error-page (fn)
781 (let* ((lw2-status
782 (alexandria:if-let (status-string (hunchentoot:cookie-in "lw2-status"))
783 (if (string= status-string "") nil
784 (let ((json:*identifier-name-to-key* #'json:safe-json-intern))
785 (json:decode-json-from-string status-string)))))
786 (*current-prefs*
787 (alexandria:if-let (prefs-string (hunchentoot:cookie-in "prefs"))
788 (let ((json:*identifier-name-to-key* 'json:safe-json-intern))
789 (ignore-errors (json:decode-json-from-string (quri:url-decode prefs-string)))))))
790 (with-site-context ((let ((host (or (hunchentoot:header-in* :x-forwarded-host) (hunchentoot:header-in* :host))))
791 (or (find-site host)
792 (error "Unknown site: ~A" host))))
793 (multiple-value-bind (*current-auth-token* *current-userid* *current-username*)
794 (if *read-only-mode*
795 (values)
796 (alexandria:if-let
797 (auth-token
798 (alexandria:if-let
799 (at (hunchentoot:cookie-in "lw2-auth-token"))
800 (if (or (string= at "") (not lw2-status) (> (get-unix-time) (- (cdr (assoc :expires lw2-status)) (* 60 60 24))))
801 nil at)))
802 (with-cache-readonly-transaction
803 (values
804 auth-token
805 (cache-get "auth-token-to-userid" auth-token)
806 (cache-get "auth-token-to-username" auth-token)))))
807 (let ((*current-user-slug* (and *current-userid* (get-user-slug *current-userid*))))
808 (handler-case
809 (log-conditions
810 (funcall fn))
811 (serious-condition (condition)
812 (emit-page (out-stream :title "Error" :return-code (condition-http-return-code condition) :content-class "error-page")
813 (error-to-html out-stream condition)))))))))
815 (defmacro with-error-page (&body body)
816 `(call-with-error-page (lambda () ,@body)))
818 (defun output-form (out-stream method action id heading csrf-token fields button-label &key textarea end-html)
819 (format out-stream "<form method=\"~A\" action=\"~A\" id=\"~A\"><h1>~A</h1>" method action id heading)
820 (loop for (id label type . params) in fields
821 do (format out-stream "<label for=\"~A\">~A:</label>" id label)
822 do (cond
823 ((string= type "select")
824 (destructuring-bind (option-list &optional default) params
825 (format out-stream "<select name=\"~A\">" id)
826 (loop for (value label) in option-list
827 do (format out-stream "<option value=\"~A\"~:[~; selected~]>~A</option>" value (string= default value) label))
828 (format out-stream "</select>")))
830 (destructuring-bind (&optional (autocomplete "off") default) params
831 (format out-stream "<input type=\"~A\" name=\"~A\" autocomplete=\"~A\"~@[ value=\"~A\"~]>" type id autocomplete (and default (encode-entities default))))))
832 do (format out-stream ""))
833 (if textarea
834 (destructuring-bind (ta-name ta-contents) textarea
835 (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))))
836 (format out-stream "<input type=\"hidden\" name=\"csrf-token\" value=\"~A\"><input type=\"submit\" value=\"~A\">~@[~A~]</form>"
837 csrf-token button-label end-html))
839 (defun page-toolbar-to-html (out-stream &key title new-post new-conversation logout (rss t))
840 (let ((liu (logged-in-userid)))
841 (format out-stream "<div class=\"page-toolbar\">")
842 (when logout
843 (format out-stream "<form method=\"post\" action=\"/logout\"><button class=\"logout-button button\" name=\"logout\" value=\"~A\">Log out</button></form>"
844 (make-csrf-token)))
845 (when (and new-conversation liu)
846 (multiple-value-bind (text to)
847 (typecase new-conversation (string (values "Send private message" new-conversation)) (t "New conversation"))
848 (format out-stream "<a class=\"new-private-message button\" href=\"/conversation~@[?to=~A~]\">~A</a>"
849 to text)))
850 (when (and new-post liu)
851 (format out-stream "<a class=\"new-post button\" href=\"/edit-post~@[?section=~A~]\" accesskey=\"n\" title=\"Create new post [n]\">New post</a>"
852 (typecase new-post (string new-post) (t nil))))
853 (when (and title rss)
854 (format out-stream "<a class=\"rss\" rel=\"alternate\" type=\"application/rss+xml\" title=\"~A RSS feed\" href=\"~A\">RSS</a>"
855 title (replace-query-params (hunchentoot:request-uri*) "offset" nil "format" "rss")))
856 (format out-stream "</div>")))
858 (defun view-items-index (items &key section title current-uri hide-title need-auth (pagination (pagination-nav-bars)) (top-nav (lambda (s) (page-toolbar-to-html s :title title))) (content-class "index-page"))
859 (alexandria:switch ((hunchentoot:get-parameter "format") :test #'string=)
860 ("rss"
861 (setf (hunchentoot:content-type*) "application/rss+xml; charset=utf-8")
862 (with-response-stream (out-stream)
863 (write-index-items-to-rss out-stream items :title title)))
865 (emit-page (out-stream :title (if hide-title nil title) :description (site-description *current-site*) :content-class content-class
866 :current-uri current-uri :robots (if (hunchentoot:get-parameter :offset) "noindex, nofollow")
867 :pagination pagination :top-nav top-nav)
868 (write-index-items-to-html out-stream items
869 :need-auth need-auth
870 :skip-section section)))))
872 (defun link-if-not (stream linkp url class text &key accesskey nofollow)
873 (declare (dynamic-extent linkp url text))
874 (if (not linkp)
875 (format stream "<a href=\"~A\" class=\"~A\"~@[ accesskey=\"~A\"~]~:[~; rel=\"nofollow\"~]>~A</a>" url class accesskey nofollow text)
876 (format stream "<span class=\"~A\">~A</span>" class text)))
878 (defun postprocess-markdown (markdown)
879 (ppcre:regex-replace-all (concatenate 'string (ppcre:regex-replace-all "\\." (site-uri *current-site*) "\\.") "posts/([^/ ]{17})/([^/# ]*)(?:#comment-([^/ ]{17})|/comment/([^/ ]{17}))?")
880 markdown
881 (lambda (target-string start end match-start match-end reg-starts reg-ends)
882 (declare (ignore start end match-start match-end))
883 (labels ((reg (n) (if (and (> (length reg-starts) n) (aref reg-starts n))
884 (substring target-string (aref reg-starts n) (aref reg-ends n)))))
885 (format nil "https://www.lesswrong.com/posts/~A/~A~@[#~A~]" (reg 0) (reg 1) (or (reg 2) (reg 3)))))))
887 (defun post-or-get-parameter (name)
888 (or (hunchentoot:post-parameter name) (hunchentoot:get-parameter name)))
890 (defun redirect (uri &key (type :see-other))
891 (setf (hunchentoot:return-code*) (ecase type (:see-other 303) (:permanent 301))
892 (hunchentoot:header-out "Location") uri))
894 (defmacro ignorable-multiple-value-bind ((&rest bindings) value-form &body body)
895 (let (new-bindings ignores)
896 (dolist (binding (reverse bindings))
897 (if (eq binding '*)
898 (let ((gensym (gensym)))
899 (push gensym new-bindings)
900 (push gensym ignores))
901 (push binding new-bindings)))
902 `(multiple-value-bind ,new-bindings ,value-form
903 (declare (ignore ,.ignores))
904 ,@body)))
906 (defmacro define-page (name path-specifier additional-vars &body body)
907 (labels ((make-lambda (args)
908 (loop for a in args
909 collect (if (atom a) a (first a))))
910 (filter-plist (plist &rest args)
911 (declare (dynamic-extent args))
912 (map-plist (lambda (key val) (when (member key args) (list key val))) plist))
913 (make-hunchentoot-lambda (args)
914 (loop for x in args
915 collect (if (atom x) x
916 (cons (first x) (filter-plist (rest x) :request-type :real-name)))))
917 (make-binding-form (additional-vars body &aux var-bindings additional-declarations additional-preamble)
918 (loop for x in additional-vars
919 when (not (eq x '*))
921 (destructuring-bind (name &key member type default required request-type real-name) (if (atom x) (list x) x)
922 (declare (ignore request-type real-name))
923 (let* ((inner-form
924 (cond
925 (member
926 `(let ((sym (find-symbol (string-upcase ,name) ,(find-package '#:keyword))))
927 (if (member sym (quote ,member)) sym)))
928 ((and type (subtypep type 'integer))
929 `(if ,name (parse-integer ,name)))))
930 (inner-form
931 (if default
932 `(or ,inner-form ,default)
933 inner-form)))
934 (when required
935 (push `(unless (and ,name (not (equal ,name ""))) (error "Missing required parameter: ~A" (quote ,name)))
936 additional-preamble))
937 (if member
938 (if type (error "Cannot specify both member and type.")
939 (push `(type (or null symbol) ,name) additional-declarations))
940 (if type
941 (push `(type (or null ,type) ,name) additional-declarations)
942 (push `(type (or null simple-string) ,name) additional-declarations)))
943 (when inner-form
944 (push `(,name ,inner-form) var-bindings)))))
945 `(let ,var-bindings (declare ,@additional-declarations) ,@additional-preamble ,@body)))
946 (multiple-value-bind (path-specifier-form path-bindings-wrapper specifier-vars)
947 (if (stringp path-specifier)
948 (values path-specifier #'identity)
949 (destructuring-bind (specifier-type specifier-body &rest specifier-args) path-specifier
950 (ecase specifier-type
951 (:function
952 (values `(lambda (r) (funcall ,specifier-body (hunchentoot:request-uri r)))
953 (if specifier-args
954 (lambda (body) `(ignorable-multiple-value-bind ,(make-lambda specifier-args) (funcall ,specifier-body (hunchentoot:request-uri*)) ,body))
955 #'identity)
956 specifier-args))
957 (:regex
958 (let ((fn `(lambda (r) (ppcre:scan-to-strings ,specifier-body (hunchentoot:request-uri r)))))
959 (values fn
960 (lambda (body)
961 (alexandria:with-gensyms (result-vector)
962 `(let ((,result-vector (nth-value 1 (funcall ,fn hunchentoot:*request*))))
963 (declare (type simple-vector ,result-vector))
964 (let
965 ,(loop for v in (make-lambda specifier-args) as x from 0 collecting `(,v (if (> (length ,result-vector) ,x) (aref ,result-vector ,x))))
966 ,body))))
967 specifier-args))))))
968 (let* ((rewritten-body
969 (if (eq (ignore-errors (caar body)) 'request-method)
970 (progn
971 (unless (= (length body) 1)
972 (error "REQUEST-METHOD must be the only form when it appears in DEFINE-PAGE."))
973 `((ecase (hunchentoot:request-method*)
974 ,.(loop for method-body in (cdar body)
975 collect (destructuring-bind (method args &body inner-body) method-body
976 (unless (eq method :get)
977 (alexandria:with-gensyms (csrf-token)
978 (push `(,csrf-token :real-name "csrf-token" :required t) args)
979 (push `(check-csrf-token ,csrf-token) inner-body)))
980 (loop for a in args
981 do (push (append (if (atom a) (list a) (cons (first a) (filter-plist (rest a) :real-name))) (list :request-type method)) additional-vars))
982 `(,method ,(make-binding-form args inner-body)))))))
983 body)))
984 `(hunchentoot:define-easy-handler (,name :uri ,path-specifier-form) ,(make-hunchentoot-lambda additional-vars)
985 (with-error-page
986 (block nil
987 ,(funcall path-bindings-wrapper
988 (make-binding-form (append specifier-vars additional-vars)
989 rewritten-body)))))))))
991 (define-component sort-widget (&key (sort-options '(:new :hot)) (pref :default-sort) (param-name "sort") (html-class "sort"))
992 (:http-args '((sort :alias param-name :member sort-options)))
993 (let ((sort-string (if sort (string-downcase sort))))
994 (if sort-string
995 (set-user-pref :default-sort sort-string))
996 (renderer (out-stream)
997 (sublevel-nav-to-html out-stream
998 sort-options
999 (user-pref pref)
1000 :param-name param-name
1001 :extra-class html-class))
1002 (or sort-string (user-pref pref))))
1004 (define-page view-root "/" ((offset :type fixnum)
1005 (limit :type fixnum))
1006 (component-value-bind ((sort-string sort-widget))
1007 (multiple-value-bind (posts total)
1008 (get-posts-index :offset offset :limit (or limit (user-pref :items-per-page)) :sort sort-string)
1009 (view-items-index posts
1010 :section :frontpage :title "Frontpage posts" :hide-title t
1011 :pagination (pagination-nav-bars :offset (or offset 0) :total total :with-next (not total))
1012 :top-nav (lambda (out-stream)
1013 (page-toolbar-to-html out-stream
1014 :title "Frontpage posts"
1015 :new-post t)
1016 (funcall sort-widget out-stream))))))
1018 (define-page view-index "/index" ((view :member (:all :new :frontpage :featured :meta :community :alignment-forum :questions) :default :all)
1019 before after
1020 (offset :type fixnum)
1021 (limit :type fixnum))
1022 (when (eq view :new) (redirect (replace-query-params (hunchentoot:request-uri*) "view" "all" "all" nil) :type :permanent) (return))
1023 (component-value-bind ((sort-string sort-widget))
1024 (multiple-value-bind (posts total)
1025 (get-posts-index :view (string-downcase view) :before before :after after :offset offset :limit (or limit (user-pref :items-per-page)) :sort sort-string)
1026 (let ((page-title (format nil "~@(~A posts~)" view)))
1027 (view-items-index posts
1028 :section view :title page-title
1029 :pagination (pagination-nav-bars :offset (or offset 0) :total total :with-next (not total))
1030 :content-class (format nil "index-page ~(~A~)-index-page" view)
1031 :top-nav (lambda (out-stream)
1032 (page-toolbar-to-html out-stream
1033 :title page-title
1034 :new-post (if (eq view :meta) "meta" t))
1035 (if (member view '(:all))
1036 (funcall sort-widget out-stream))))))))
1038 (define-page view-post "/post" ((id :required t))
1039 (redirect (generate-post-link id) :type :permanent))
1041 (define-page view-post-lw1-link (:function #'match-lw1-link) ()
1042 (redirect (convert-lw1-link (hunchentoot:request-uri*)) :type :permanent))
1044 (define-page view-post-lw2-slug-link (:function #'match-lw2-slug-link) ()
1045 (redirect (convert-lw2-slug-link (hunchentoot:request-uri*)) :type :see-other))
1047 (define-page view-post-lw2-sequence-link (:function #'match-lw2-sequence-link) ()
1048 (redirect (convert-lw2-sequence-link (hunchentoot:request-uri*)) :type :see-other))
1050 (define-page view-feed "/feed" ()
1051 (redirect "/?format=rss" :type :permanent))
1053 (define-page view-post-lw2-link (:function #'match-lw2-link post-id comment-id * comment-link-type) (need-auth chrono)
1054 (request-method
1055 (:get ()
1056 (let ((lw2-auth-token *current-auth-token*))
1057 (labels ((output-comments (out-stream id comments target)
1058 (format out-stream "<div id=\"~A\" class=\"comments\">" id)
1059 (with-error-html-block (out-stream)
1060 (if target
1061 (comment-thread-to-html out-stream
1062 (lambda ()
1063 (comment-item-to-html
1064 out-stream
1065 target
1066 :extra-html-fn (lambda (c-id)
1067 (let ((*comment-individual-link* nil))
1068 (comment-tree-to-html out-stream (make-comment-parent-hash comments) c-id))))))
1069 (if comments
1070 (if chrono
1071 (comment-chrono-to-html out-stream comments)
1072 (comment-tree-to-html out-stream (make-comment-parent-hash comments)))
1073 <div class="comments-empty-message">(if (string= id "answers") "No answers." "No comments.")</div>)))
1074 (format out-stream "</div>"))
1075 (output-comments-votes (out-stream)
1076 (handler-case
1077 (when lw2-auth-token
1078 (format out-stream "<script>commentVotes=~A</script>"
1079 (json:encode-json-to-string (get-post-comments-votes post-id lw2-auth-token))))
1080 (t () nil)))
1081 (output-post-vote (out-stream)
1082 (handler-case
1083 (format out-stream "<script>postVote=~A</script>"
1084 (json:encode-json-to-string (get-post-vote post-id lw2-auth-token)))
1085 (t () nil))))
1086 (multiple-value-bind (post title condition)
1087 (handler-case (nth-value 0 (get-post-body post-id :auth-token (and need-auth lw2-auth-token)))
1088 (serious-condition (c) (values nil "Error" c))
1089 (:no-error (post) (values post (cdr (assoc :title post)) nil)))
1090 (if comment-id
1091 (let* ((*comment-individual-link* t)
1092 (comment-thread-type (if (string= comment-link-type "answer") :answer :comment))
1093 (comments (case comment-thread-type
1094 (:comment (get-post-comments post-id))
1095 (:answer (get-post-answers post-id))))
1096 (target-comment (find comment-id comments :key (lambda (c) (cdr (assoc :--id c))) :test #'string=))
1097 (display-name (get-username (cdr (assoc :user-id target-comment))))
1098 (verb-phrase (cond
1099 ((and (eq comment-thread-type :answer)
1100 (not (cdr (assoc :parent-comment-id target-comment))))
1101 "answers")
1102 (t "comments on"))))
1103 (emit-page (out-stream :title (format nil "~A ~A ~A" display-name verb-phrase title)
1104 :content-class "individual-thread-page comment-thread-page")
1105 (format out-stream "<h1 class=\"post-title\">~A ~A <a href=\"~A\">~A</a></h1>"
1106 (encode-entities display-name)
1107 verb-phrase
1108 (generate-post-link post-id)
1109 (clean-text-to-html title :hyphenation nil))
1110 (output-comments out-stream "comments" comments target-comment)
1111 (when lw2-auth-token
1112 (force-output out-stream)
1113 (output-comments-votes out-stream))))
1114 (emit-page (out-stream :title title :content-class (format nil "post-page comment-thread-page~:[~; question-post-page~]" (cdr (assoc :question post))))
1115 (cond
1116 (condition
1117 (error-to-html out-stream condition))
1119 (post-body-to-html out-stream post)))
1120 (when (and lw2-auth-token (equal (logged-in-userid) (cdr (assoc :user-id post))))
1121 (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>"
1122 (cdr (assoc :--id post))))
1123 (force-output out-stream)
1124 (handler-case
1125 (let* ((question (cdr (assoc :question post)))
1126 (answers (when question
1127 (get-post-answers post-id)))
1128 (comments (get-post-comments post-id)))
1129 (when question
1130 (output-comments out-stream "answers" answers nil))
1131 (output-comments out-stream "comments" comments nil))
1132 (serious-condition (c) (error-to-html out-stream c)))
1133 (when lw2-auth-token
1134 (force-output out-stream)
1135 (output-post-vote out-stream)
1136 (output-comments-votes out-stream))))))))
1137 (:post (csrf-token text answer parent-answer-id parent-comment-id edit-comment-id retract-comment-id unretract-comment-id delete-comment-id)
1138 (let ((lw2-auth-token *current-auth-token*))
1139 (check-csrf-token csrf-token)
1140 (assert lw2-auth-token)
1141 (let ((question (cdr (assoc :question (get-post-body post-id :auth-token lw2-auth-token))))
1142 (new-comment-id
1143 (cond
1144 (text
1145 (let ((comment-data
1146 (list-cond
1147 (t :body (postprocess-markdown text))
1148 (t :last-edited-as "markdown")
1149 ((not edit-comment-id) :post-id post-id)
1150 (parent-comment-id :parent-comment-id parent-comment-id)
1151 (answer :answer t)
1152 (parent-answer-id :parent-answer-id parent-answer-id))))
1153 (if edit-comment-id
1154 (prog1 edit-comment-id
1155 (do-lw2-comment-edit lw2-auth-token edit-comment-id comment-data))
1156 (do-lw2-comment lw2-auth-token comment-data))))
1157 (retract-comment-id
1158 (do-lw2-comment-edit lw2-auth-token retract-comment-id '((:retracted . t))))
1159 (unretract-comment-id
1160 (do-lw2-comment-edit lw2-auth-token unretract-comment-id '((:retracted . nil))))
1161 (delete-comment-id
1162 (do-lw2-comment-edit lw2-auth-token delete-comment-id '((:deleted . t) (:deleted-public . t)
1163 (:deleted-reason . "Comment deleted by its author.")))
1164 nil))))
1165 (ignore-errors
1166 (get-post-comments post-id :force-revalidate t)
1167 (when question
1168 (get-post-answers post-id :force-revalidate t)))
1169 (when text
1170 (cache-put "comment-markdown-source" new-comment-id text)
1171 (redirect (generate-post-link (match-lw2-link (hunchentoot:request-uri*)) new-comment-id))))))))
1173 (defparameter *edit-post-template* (compile-template* "edit-post.html"))
1175 (define-page view-edit-post "/edit-post" (title url section post-id link-post)
1176 (request-method
1177 (:get ()
1178 (let* ((csrf-token (make-csrf-token))
1179 (post-body (if post-id (get-post-body post-id :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1180 (section (or section (loop for (sym . sec) in '((:draft . "drafts") (:meta . "meta") (:frontpage-date . "frontpage"))
1181 if (cdr (assoc sym post-body)) return sec
1182 finally (return "all")))))
1183 (emit-page (out-stream :title (if post-id "Edit Post" "New Post") :content-class "edit-post-page")
1184 (render-template* *edit-post-template* out-stream
1185 :csrf-token csrf-token
1186 :title (cdr (assoc :title post-body))
1187 :url (cdr (assoc :url post-body))
1188 :question (cdr (assoc :question post-body))
1189 :post-id post-id
1190 :section-list (loop for (name desc) in '(("all" "All") ("meta" "Meta") ("drafts" "Drafts"))
1191 collect (alist :name name :desc desc :selected (string= name section)))
1192 :markdown-source (or (and post-id (cache-get "post-markdown-source" post-id)) (cdr (assoc :html-body post-body)) "")))))
1193 (:post (text question)
1194 (let ((lw2-auth-token *current-auth-token*)
1195 (url (if (string= url "") nil url)))
1196 (assert lw2-auth-token)
1197 (let* ((post-data
1198 (list-cond
1199 (t :body (postprocess-markdown text))
1200 (t :title title)
1201 (t :last-edited-as "markdown")
1202 (t :url (if link-post url))
1203 (t :meta (string= section "meta"))
1204 (t :draft (string= section "drafts"))
1205 ((not post-id) :question (and question t))))
1206 (post-set (loop for item in post-data when (cdr item) collect item))
1207 (post-unset (loop for item in post-data when (not (cdr item)) collect (cons (car item) t))))
1208 (let* ((new-post-data
1209 (if post-id
1210 (do-lw2-post-edit lw2-auth-token post-id post-set post-unset)
1211 (do-lw2-post lw2-auth-token post-set)))
1212 (new-post-id (cdr (assoc :--id new-post-data))))
1213 (assert new-post-id)
1214 (cache-put "post-markdown-source" new-post-id text)
1215 (ignore-errors (get-post-body post-id :force-revalidate t))
1216 (redirect (if (cdr (assoc "draft" post-data :test #'equal))
1217 (concatenate 'string (generate-post-link new-post-data) "?need-auth=y")
1218 (generate-post-link new-post-data)))))))))
1220 (hunchentoot:define-easy-handler (view-karma-vote :uri "/karma-vote") ((csrf-token :request-type :post) (target :request-type :post) (target-type :request-type :post) (vote-type :request-type :post))
1221 (with-error-page
1222 (check-csrf-token csrf-token)
1223 (let ((lw2-auth-token (hunchentoot:cookie-in "lw2-auth-token")))
1224 (multiple-value-bind (points vote-type) (do-lw2-vote lw2-auth-token target target-type vote-type)
1225 (json:encode-json-to-string (list (pretty-number points "point") vote-type))))))
1227 (hunchentoot:define-easy-handler (view-check-notifications :uri "/check-notifications") ()
1228 (with-error-page
1229 (if *current-auth-token*
1230 (let ((notifications-status (check-notifications (logged-in-userid) *current-auth-token*)))
1231 (json:encode-json-to-string notifications-status)))))
1233 (define-page view-recent-comments "/recentcomments" ((offset :type fixnum)
1234 (limit :type fixnum))
1235 (let ((want-total (not (typep *current-backend* 'backend-lw2)))) ; jumping to last page causes LW2 to explode
1236 (multiple-value-bind (recent-comments total)
1237 (if (or offset limit (/= (user-pref :items-per-page) 20))
1238 (lw2-graphql-query (lw2-query-string :comment :list
1239 (remove nil (alist :view "postCommentsNew" :limit (or limit (user-pref :items-per-page)) :offset offset)
1240 :key #'cdr)
1241 (comments-index-fields)
1242 :with-total want-total))
1243 (get-recent-comments :with-total want-total))
1244 (view-items-index recent-comments :title "Recent comments" :pagination (pagination-nav-bars :offset (or offset 0) :with-next (not want-total) :total (if want-total total))))))
1246 (define-page view-user (:regex "^/users/(.*?)(?:$|\\?)|^/user" user-slug) (id
1247 (offset :type fixnum :default 0)
1248 (show :member (:all :posts :comments :drafts :conversations :inbox) :default :all)
1249 (sort :member (:top :new) :default :new))
1250 (let* ((auth-token (if (eq show :inbox) *current-auth-token*))
1251 (user-query-terms (cond
1252 (user-slug (alist :slug user-slug))
1253 (id (alist :document-id id))))
1254 (user-info
1255 (let ((ui (lw2-graphql-query (lw2-query-string :user :single user-query-terms `(:--id :slug :display-name :karma ,@(if (eq show :inbox) '(:last-notifications-check))))
1256 :auth-token auth-token)))
1257 (if (cdr (assoc :--id ui))
1259 (error (make-condition 'lw2-user-not-found-error)))))
1260 (user-id (cdr (assoc :--id user-info)))
1261 (own-user-page (logged-in-userid user-id))
1262 (comments-index-fields (remove :page-url (comments-index-fields))) ; page-url sometimes causes "Cannot read property '_id' of undefined" error
1263 (display-name (if user-slug (cdr (assoc :display-name user-info)) user-id))
1264 (show-text (if (not (eq show :all)) (string-capitalize show)))
1265 (title (format nil "~A~@['s ~A~]" display-name show-text))
1266 (sort-type (case sort (:top :score) (:new :date)))
1267 (comments-base-terms (ecase sort-type (:score (load-time-value (alist :view "postCommentsTop"))) (:date (load-time-value (alist :view "allRecentComments"))))))
1268 (multiple-value-bind (items total)
1269 (case show
1270 (:posts
1271 (get-user-posts user-id :offset offset :limit (+ 1 (user-pref :items-per-page)) :sort-type sort-type))
1272 (:comments
1273 (lw2-graphql-query (lw2-query-string :comment :list
1274 (nconc (alist :offset offset :limit (+ 1 (user-pref :items-per-page)) :user-id user-id)
1275 comments-base-terms)
1276 comments-index-fields)))
1277 (:drafts
1278 (get-user-posts user-id :drafts t :auth-token (hunchentoot:cookie-in "lw2-auth-token")))
1279 (:conversations
1280 (let ((conversations
1281 (lw2-graphql-query (lw2-query-string :conversation :list
1282 (alist :view "userConversations" :limit (+ 1 (user-pref :items-per-page)) :offset offset :user-id user-id)
1283 '(:--id :created-at :title (:participants :display-name :slug) :----typename))
1284 :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1285 (lw2-graphql-query-map
1286 (lambda (c)
1287 (lw2-query-string* :message :total (alist :view "messagesConversation" :conversation-id (cdr (assoc :--id c))) nil))
1288 conversations
1289 :postprocess (lambda (c result)
1290 (acons :messages-total result c))
1291 :auth-token (hunchentoot:cookie-in "lw2-auth-token"))))
1292 (:inbox
1293 (prog1
1294 (let ((notifications (get-notifications :user-id user-id :offset offset :auth-token (hunchentoot:cookie-in "lw2-auth-token")))
1295 (last-check (ignore-errors (local-time:parse-timestring (cdr (assoc :last-notifications-check user-info))))))
1296 (labels ((check-new (key obj)
1297 (if (ignore-errors (local-time:timestamp< last-check (local-time:parse-timestring (cdr (assoc key obj)))))
1298 (acons :highlight-new t obj)
1299 obj)))
1300 (lw2-graphql-query-map
1301 (lambda (n)
1302 (alexandria:switch ((cdr (assoc :document-type n)) :test #'string=)
1303 ("comment"
1304 (lw2-query-string* :comment :single
1305 (alist :document-id (cdr (assoc :document-id n)))
1306 (comments-index-fields)))
1307 ("post"
1308 (lw2-query-string* :post :single (alist :document-id (cdr (assoc :document-id n)))
1309 (posts-index-fields)))
1310 ("message"
1311 (lw2-query-string* :message :single (alist :document-id (cdr (assoc :document-id n)))
1312 *messages-index-fields*))
1314 (values n t))))
1315 notifications
1316 :postprocess (lambda (n result)
1317 (if result
1318 (check-new
1319 (alexandria:switch ((cdr (assoc :document-type n)) :test #'string=)
1320 ("comment" :posted-at)
1321 ("post" :posted-at)
1322 ("message" :created-at))
1323 result)
1325 :auth-token auth-token)))
1326 (do-user-edit
1327 (hunchentoot:cookie-in "lw2-auth-token")
1328 user-id
1329 (alist :last-notifications-check
1330 (local-time:format-timestring nil (local-time:now)
1331 :format lw2.graphql:+graphql-timestamp-format+
1332 :timezone local-time:+utc-zone+)))))
1334 (let ((user-posts (get-user-posts user-id :limit (+ 1 (user-pref :items-per-page) offset)))
1335 (user-comments (lw2-graphql-query (lw2-query-string :comment :list (nconc (alist :limit (+ 1 (user-pref :items-per-page) offset) :user-id user-id) comments-base-terms)
1336 comments-index-fields))))
1337 (concatenate 'list user-posts user-comments))))
1338 (let ((with-next (> (length items) (+ (if (eq show :all) offset 0) (user-pref :items-per-page))))
1339 (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
1340 (view-items-index interleave :title title
1341 :content-class (format nil "user-page~@[ ~A-user-page~]~:[~; own-user-page~]" show-text own-user-page)
1342 :current-uri (format nil "/users/~A" user-slug)
1343 :section :personal
1344 :pagination (pagination-nav-bars :offset offset :total total :with-next (if (not total) with-next))
1345 :need-auth (eq show :drafts) :section (if (eq show :drafts) "drafts" nil)
1346 :top-nav (lambda (out-stream)
1347 (page-toolbar-to-html out-stream
1348 :title title
1349 :rss (not (member show '(:drafts :conversations :inbox)))
1350 :new-post (if (eq show :drafts) "drafts" t)
1351 :new-conversation (if own-user-page t user-slug)
1352 :logout own-user-page)
1353 (format out-stream "<h1 class=\"page-main-heading\"~@[ ~A~]>~A</h1><div class=\"user-stats\">Karma: <span class=\"karma-total\">~A</span></div>"
1354 (if (not own-user-page)
1355 (if user-slug
1356 (format nil "data-anti-kibitzer-redirect=\"/user?id=~A\"" (cdr (assoc :--id user-info)))
1357 (format nil "data-kibitzer-redirect=\"/users/~A\"" (cdr (assoc :slug user-info)))))
1358 (encode-entities display-name)
1359 (if user-slug (pretty-number (or (cdr (assoc :karma user-info)) 0)) "##"))
1360 (sublevel-nav-to-html out-stream
1361 `(:all :posts :comments
1362 ,@(if own-user-page
1363 '(:drafts :conversations :inbox)))
1364 show
1365 :default :all)
1366 (when (member show '(:all :posts :comments))
1367 (sublevel-nav-to-html out-stream
1368 '(:new :top)
1369 sort
1370 :default :new
1371 :param-name "sort"
1372 :extra-class "sort"))))))))
1374 (defparameter *conversation-template* (compile-template* "conversation.html"))
1376 (define-page view-conversation "/conversation" (id)
1377 (request-method
1378 (:get ()
1379 (let ((to (post-or-get-parameter "to")))
1380 (cond
1381 ((and id to) (error "This is an invalid URL."))
1383 (multiple-value-bind (conversation messages)
1384 (get-conversation-messages id (hunchentoot:cookie-in "lw2-auth-token"))
1385 (view-items-index (nreverse messages) :content-class "conversation-page" :need-auth t :title (encode-entities (postprocess-conversation-title (cdr (assoc :title conversation))))
1386 :top-nav (lambda (out-stream) (render-template* *conversation-template* out-stream
1387 :conversation conversation :csrf-token (make-csrf-token))))))
1389 (emit-page (out-stream :title "New conversation" :content-class "conversation-page")
1390 (render-template* *conversation-template* out-stream
1391 :to to
1392 :csrf-token (make-csrf-token)))))))
1393 (:post ((text :required t))
1394 (let* ((subject (post-or-get-parameter "subject"))
1395 (to (post-or-get-parameter "to"))
1396 (id (or id
1397 (let ((participant-ids (list (logged-in-userid) (cdar (lw2-graphql-query (lw2-query-string :user :single (alist :slug to) '(:--id)))))))
1398 (do-create-conversation (hunchentoot:cookie-in "lw2-auth-token") (alist :participant-ids participant-ids :title subject))))))
1399 (do-create-message (hunchentoot:cookie-in "lw2-auth-token") id text)
1400 (redirect (format nil "/conversation?id=~A" id))))))
1402 (defun search-result-markdown-to-html (item)
1403 (cons (cons :html-body
1404 (handler-case (markdown:parse (cdr (assoc :body item)))
1405 (serious-condition () "[Error while processing search result]")))
1406 item))
1408 (define-page view-search "/search" ((q :required t))
1409 (let ((*current-search-query* q)
1410 (link (convert-any-link* q)))
1411 (declare (special *current-search-query*))
1412 (if link
1413 (redirect link)
1414 (multiple-value-bind (posts comments) (lw2-search-query q)
1415 (view-items-index (nconc (map 'list (lambda (p) (if (cdr (assoc :comment-count p)) p (cons (cons :comment-count 0) p))) posts)
1416 (map 'list #'search-result-markdown-to-html comments))
1417 :content-class "search-results-page" :current-uri "/search"
1418 :title (format nil "~@[~A - ~]Search" q))))))
1420 (define-page view-login "/login" (return cookie-check
1421 (csrf-token :request-type :post) (login-username :request-type :post) (login-password :request-type :post)
1422 (signup-username :request-type :post) (signup-email :request-type :post) (signup-password :request-type :post) (signup-password2 :request-type :post))
1423 (labels
1424 ((emit-login-page (&key error-message)
1425 (let ((csrf-token (make-csrf-token)))
1426 (emit-page (out-stream :title "Log in" :current-uri "/login" :content-class "login-page" :robots "noindex, nofollow")
1427 (when error-message
1428 (format out-stream "<div class=\"error-box\">~A</div>" error-message))
1429 (with-outputs (out-stream) "<div class=\"login-container\">")
1430 (output-form out-stream "post" (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))) "login-form" "Log in" csrf-token
1431 '(("login-username" "Username" "text" "username")
1432 ("login-password" "Password" "password" "current-password"))
1433 "Log in"
1434 :end-html "<a href=\"/reset-password\">Forgot password</a>")
1435 (output-form out-stream "post" (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))) "signup-form" "Create account" csrf-token
1436 '(("signup-username" "Username" "text" "username")
1437 ("signup-email" "Email" "text" "email")
1438 ("signup-password" "Password" "password" "new-password")
1439 ("signup-password2" "Confirm password" "password" "new-password"))
1440 "Create account")
1441 (alexandria:if-let (main-site-title (main-site-title *current-site*))
1442 (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>"
1443 main-site-title))
1444 (format out-stream "</div>"))))
1445 (finish-login (username user-id auth-token error-message &optional expires)
1446 (cond
1447 (auth-token
1448 (set-cookie "lw2-auth-token" auth-token :max-age (and expires (+ (- expires (get-unix-time)) (* 24 60 60))))
1449 (if expires (set-cookie "lw2-status" (json:encode-json-to-string (alist :expires expires))))
1450 (cache-put "auth-token-to-userid" auth-token user-id)
1451 (cache-put "auth-token-to-username" auth-token username)
1452 (redirect (if (and return (ppcre:scan "^/[^/]" return)) return "/")))
1454 (emit-login-page :error-message error-message)))))
1455 (cond
1456 ((not (or cookie-check (hunchentoot:cookie-in "session-token")))
1457 (set-cookie "session-token" (base64:usb8-array-to-base64-string (ironclad:make-random-salt)))
1458 (redirect (format nil "/login?~@[return=~A&~]cookie-check=y" (if return (url-rewrite:url-encode return)))))
1459 (cookie-check
1460 (if (hunchentoot:cookie-in "session-token")
1461 (redirect (format nil "/login~@[?return=~A~]" (if return (url-rewrite:url-encode return))))
1462 (emit-page (out-stream :title "Log in" :current-uri "/login")
1463 (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))))))
1464 (login-username
1465 (check-csrf-token csrf-token)
1466 (cond
1467 ((or (string= login-username "") (string= login-password "")) (emit-login-page :error-message "Please enter a username and password"))
1468 (t (multiple-value-call #'finish-login login-username (do-login "username" login-username login-password)))))
1469 (signup-username
1470 (check-csrf-token csrf-token)
1471 (cond
1472 ((not (every (lambda (x) (not (string= x ""))) (list signup-username signup-email signup-password signup-password2)))
1473 (emit-login-page :error-message "Please fill in all fields"))
1474 ((not (string= signup-password signup-password2))
1475 (emit-login-page :error-message "Passwords do not match"))
1476 (t (multiple-value-call #'finish-login signup-username (do-lw2-create-user signup-username signup-email signup-password)))))
1478 (emit-login-page)))))
1480 (define-page view-logout "/logout" ((logout :request-type :post))
1481 (check-csrf-token logout)
1482 (set-cookie "lw2-auth-token" "" :max-age 0)
1483 (redirect "/"))
1485 (defparameter *reset-password-template* (compile-template* "reset-password.html"))
1487 (define-page view-reset-password "/reset-password" ((csrf-token :request-type :post) (email :request-type :post) (reset-link :request-type :post) (password :request-type :post) (password2 :request-type :post))
1488 (labels ((emit-rpw-page (&key message message-type step)
1489 (let ((csrf-token (make-csrf-token)))
1490 (emit-page (out-stream :title "Reset password" :content-class "reset-password" :robots "noindex, nofollow")
1491 (render-template* *reset-password-template* out-stream
1492 :csrf-token csrf-token
1493 :reset-link reset-link
1494 :message message
1495 :message-type message-type
1496 :step step)))))
1497 (cond
1498 (email
1499 (check-csrf-token csrf-token)
1500 (multiple-value-bind (ret error)
1501 (do-lw2-forgot-password email)
1502 (declare (ignore ret))
1503 (if error
1504 (emit-rpw-page :step 1 :message error :message-type "error")
1505 (emit-rpw-page :step 1 :message "Password reset email sent." :message-type "success"))))
1506 (reset-link
1507 (ppcre:register-groups-bind (reset-token) ("(?:reset-password/|^)([^/#]+)$" reset-link)
1508 (cond
1509 ((not reset-token)
1510 (emit-rpw-page :step 2 :message "Invalid password reset link." :message-type "error"))
1511 ((not (string= password password2))
1512 (emit-rpw-page :step 2 :message "Passwords do not match." :message-type "error"))
1514 (check-csrf-token csrf-token)
1515 (multiple-value-bind (user-id auth-token error-message) (do-lw2-reset-password reset-token password)
1516 (declare (ignore user-id auth-token))
1517 (cond
1518 (error-message (emit-rpw-page :step 2 :message error-message :message-type "error"))
1520 (with-error-page (emit-page (out-stream :title "Reset password" :content-class "reset-password")
1521 (format out-stream "<h1>Password reset complete</h1><p>You can now <a href=\"/login\">log in</a> with your new password.</p>"))))))))))
1523 (emit-rpw-page)))))
1525 (defun firstn (list n)
1526 (loop for x in list
1527 for i from 1 to n
1528 collect x))
1530 (defparameter *earliest-post* (local-time:parse-timestring "2005-01-01"))
1532 (define-page view-archive (:regex "^/archive(?:/(\\d{4})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))(?:/(\\d{1,2})|/?(?:$|\\?.*$))"
1533 (year :type (mod 10000))
1534 (month :type (integer 1 12))
1535 (day :type (integer 1 31)))
1536 ((offset :type fixnum :default 0))
1537 (local-time:with-decoded-timestamp (:day current-day :month current-month :year current-year) (local-time:now)
1538 (local-time:with-decoded-timestamp (:day earliest-day :month earliest-month :year earliest-year) *earliest-post*
1539 (labels ((url-elements (&rest url-elements)
1540 (declare (dynamic-extent url-elements))
1541 (format nil "/~{~A~^/~}" url-elements))
1542 (archive-nav (out-stream)
1543 (with-outputs (out-stream) "<div class=\"archive-nav\"><div class=\"archive-nav-years\">")
1544 (link-if-not out-stream (not (or year month day)) (url-elements "archive") "archive-nav-item-year" "All")
1545 (loop for y from earliest-year to current-year
1546 do (link-if-not out-stream (eq y year) (url-elements "archive" y) "archive-nav-item-year" y))
1547 (format out-stream "</div>")
1548 (when year
1549 (format out-stream "<div class=\"archive-nav-months\">")
1550 (link-if-not out-stream (not month) (url-elements "archive" year) "archive-nav-item-month" "All")
1551 (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)
1552 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)))
1553 (format out-stream "</div>"))
1554 (when month
1555 (format out-stream "<div class=\"archive-nav-days\">")
1556 (link-if-not out-stream (not day) (url-elements "archive" year month) "archive-nav-item-day" "All")
1557 (loop for d from (if (and (= (or year current-year) earliest-year) (= (or month current-month) earliest-month)) earliest-day 1)
1558 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)))
1559 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))
1560 (format out-stream "</div>"))
1561 (format out-stream "</div>")))
1562 (multiple-value-bind (posts total)
1563 (lw2-graphql-query (lw2-query-string :post :list
1564 (alist :view (if day "new" "top") :limit 51 :offset offset
1565 :after (if (and year (not day)) (format nil "~A-~A-~A" (or year earliest-year) (or month 1) (or day 1)))
1566 :before (if year (format nil "~A-~A-~A" (or year current-year) (or month 12)
1567 (or day (local-time:days-in-month (or month 12) (or year current-year))))))
1568 (posts-index-fields)))
1569 (emit-page (out-stream :title "Archive" :current-uri "/archive" :content-class "archive-page"
1570 :top-nav #'archive-nav
1571 :pagination (pagination-nav-bars :items-per-page 50 :offset offset :total total :with-next (if total nil (> (length posts) 50))))
1572 (write-index-items-to-html out-stream (firstn posts 50) :empty-message "No posts for the selected period.")))))))
1574 (define-page view-about "/about" ()
1575 (emit-page (out-stream :title "About" :current-uri "/about" :content-class "about-page")
1576 (alexandria:with-input-from-file (in-stream "www/about.html" :element-type '(unsigned-byte 8))
1577 (alexandria:copy-stream in-stream out-stream))))
1579 (hunchentoot:define-easy-handler (view-versioned-resource :uri (lambda (r)
1580 (multiple-value-bind (file content-type)
1581 #.(labels ((defres (uri content-type)
1582 `(,uri (values (concatenate 'string "www" ,uri) ,content-type))))
1583 (concatenate 'list
1584 '(alexandria:switch ((hunchentoot:script-name r) :test #'string=))
1585 (loop for system in '("mac" "windows" "linux") nconc
1586 (loop for theme in '(nil "dark" "grey" "ultramodern" "zero" "brutalist" "rts")
1587 collect (defres (format nil "/style~@[-~A~].~A.css" theme system) "text/css")))
1588 (loop for (uri content-type) in
1589 '(("/script.js" "text/javascript")
1590 ("/favicon.ico" "image/x-icon"))
1591 collect (defres uri content-type))))
1592 (when file
1593 (when (assoc "v" (hunchentoot:get-parameters r) :test #'string=)
1594 (setf (hunchentoot:header-out "Cache-Control") (format nil "public, max-age=~A, immutable" (- (expt 2 31) 1))))
1595 (hunchentoot:handle-static-file file content-type)
1596 t))))
1597 nil)