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