aboutsummaryrefslogtreecommitdiff
path: root/zzcxz.cgi
blob: 9336bfc0d4cb476fb3236d9bb4f38084469ec6ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
#!/usr/bin/env lua5.3
-- this software is licensed under the terms of the GNU affero public license
-- v3 or later. view LICENSE.txt for more information.

-- if you host your own instance, please change the email address in the about
-- page and clearly distinguish your instance from https://zzcxz.citrons.xyz.

local env = os.getenv

local f = io.open("/dev/urandom", 'r')
local e = f and f:read(1)
if f then f:close() end
math.randomseed(os.time() + string.byte(e))

local function url_encode(str)
	return (str:gsub("([^A-Za-z0-9%_%.%-%~])", function(v)
		return string.upper(string.format("%%%02x", string.byte(v)))
	end))
end

local esc_sequences = {
	["<"] = "&lt;",
	[">"] = "&gt;",
	['"'] = "&quot;"
}
local function html_encode(x)
	local escaped = tostring(x)
	escaped = escaped:gsub("&", "&amp;")

	for char,esc in pairs(esc_sequences) do
		escaped = string.gsub(escaped, char, esc)
	end
	return escaped
end

local function parse_qs(str,sep)
	sep = sep or '&'
	local function decode(str, path)
		local str = str
		if not path then
			str = str:gsub('+', ' ')
		end
		str = str:gsub("%%(%x%x)", function(c)
				return string.char(tonumber(c, 16))
		end)
		return (str:gsub('\r\n', '\n'))
	end

	local values = {}
	for key,val in str:gmatch(string.format('([^%q=]+)(=*[^%q=]*)', sep, sep)) do
		local key = decode(key)
		
		local keys = {}
		key = key:gsub('%[([^%]]*)%]', function(v)
				-- extract keys between balanced brackets
				if string.find(v, "^-?%d+$") then
					v = tonumber(v)
				else
					v = decode(v)
				end
				table.insert(keys, v)
				return "="
		end)
		key = key:gsub('=+.*$', "")
		key = key:gsub('%s', "_") -- remove spaces in parameter name
		val = val:gsub('^=+', "")

		if not values[key] then
			values[key] = {}
		end
		if #keys > 0 and type(values[key]) ~= 'table' then
			values[key] = {}
		elseif #keys == 0 and type(values[key]) == 'table' then
			values[key] = decode(val)
		end

		local t = values[key]
		for i,k in ipairs(keys) do
			if type(t) ~= 'table' then
				t = {}
			end
			if k == "" then
				k = #t+1
			end
			if not t[k] then
				t[k] = {}
			end
			if i == #keys then
				t[k] = decode(val)
			end
			t = t[k]
		end
	end
	return values
end

local cookies = env "HTTP_COOKIE" and parse_qs(env "HTTP_COOKIE","; ") or {}
local history = {}
if cookies.history then
	for page in cookies.history:gmatch "(%w%w%w%w%w)%," do
		table.insert(history, page)
	end
end
local flags = {}
for k,v in pairs(cookies) do
	local flag = k:match "flag_(.+)"
	if flag then
		flags[flag] = v
	end
end

local function redirect(to)
	return "", {
		status = '303 see other',
		headers = { location = to },
	}
end

local function template(str)
	return function (t)
		return (str:gsub("$([A-Za-z][A-Za-z0-9]*)", function(v)
			return t[v] or ""
		end))
	end
end

local base = template [[
<!doctype html>
<html>
	<head>
		<link rel="stylesheet" href="/static/amethyst.css" />
		<meta charset="utf-8"/>
		<title>zzcxz: $title</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">
	</head>
	<body>
		<h1>zzcxz</h1>
		<main>$content</main>
		<footer>
			<div class="links">
				<p><a href="/">zzcxz</a></p>
				<p><a href="/about">help</a></p>
				<p><a href="https://citrons.xyz/git/zzcxz.git/about">
					source code
				</a></p>
				<p><a href="/g/zzcxy">archive</a></p>
				<p><a href="https://citrons.xyz">citrons.xyz</a></p>
			</div>
		</footer>
	</body>
</html>
]]

local not_found = function() 
	return
		base {
			title = "not found",
			content = "the content requested was not found.",
		}, { status = '404 not found' }
end

local function parse_directive(line, directives, tmp_flags)
	flags = flags or {}
	local directive, args = line:match "^#([A-Za-z]+)%s*(.-)\n?$"
	directive = directive and directive:lower()
	if not directive then
		return
	elseif directive == "redirect" then
		local redirect = args:match "^%s*(%w%w%w%w%w)%s*$"
		if not redirect then return end
		directives.redirect = redirect
	elseif directive == "deadend" then
		directives.deadend = true
	elseif directive == "set" then
		if args:match "^%s*$" then return end
		local flagname, text = args:match "^%s*([%w%-_]+)%s*(.-)%s*$"
		if not flagname then return end
		text = text or ""
		if utf8.len(flagname) > 150 or utf8.len(text) > 1000 then
			return
		end
		directives.flags_updated[flagname] = text
		tmp_flags[flagname] = text
	elseif directive == "unset" then
		local flagname = args:match "^%s*([%w%-_]+)%s*$"
		if not flagname then return end
		directives.flags_updated[flagname] = false
		tmp_flags[flagname] = nil
	elseif directive == "require" then
		local flagname = args:match "^%s*([%w%-_]+)%s*$"
		if not flagname then return end
		directives.require[flagname] = true
	else
		return
	end
	return true
end

local load_page
local function convert_markup(m)
	local result = {}
	local tmp_flags = {}
	for name, value in pairs(flags) do
		tmp_flags[name] = value
	end
	local directives = {flags_updated = {}, require = {}}
	local code_block = false
	for line in (m..'\n'):gmatch "(.-)\n" do
		if not code_block then
			if line:match "^%s*$" then
				goto continue
			end
			if line:sub(1,1) == '#' and
					parse_directive(line, directives, tmp_flags) then
				if directives.redirect then
					local to = load_page(directives.redirect)
					if to then
						local m, d = convert_markup(to.content)
						-- the final destination will not have a redirect
						-- value in this directive. as such, this will store
						-- final destination of a chain of redirects.
						d.redirect = d.redirect or to
						return m, d
					else
						directives.redirect = nil
					end
				else
					goto continue
				end
			end

			line = html_encode(line)
			if line:sub(1,1) == ' ' then
				table.insert(result, '<pre><code>')
				code_block = true
			else
				line = line:gsub("\\\\([%[%]\\])", "&#92;%1")
				line = line:gsub("\\([%[%]])", 
					{ ['['] = "&#91;", [']'] = "&#93;" })
				line = line:gsub("%[(.-)%]",
					function(s)
						return ('<span class="important">%s</span>'):format(s)
					end
				)
				table.insert(result, ('<p>%s</p>'):format(line))
			end
		end
		if code_block then
			if line:sub(1,1) == ' ' then
				table.insert(result, line .. '\n') 
			else
				table.insert(result, '</code></pre>')
				code_block = false
			end
		end
		::continue::
	end
	if code_block then
		table.insert(result, '</code></pre>')
		code_block = false
	end

	return table.concat(result), directives
end
local function target_requirements(p)
	local page = load_page(p, false, true)
	if not page then return true end
	local _,directives = convert_markup(page.content)
	for k,v in pairs(directives.require) do
		if not flags[k] then return false end
	end
	return true
end
local function parse_page(s)
	local page = {}
	page.title = s:match "^(.-)\n"
	page.actions = {}
	local content = {}
	for line in (s..'\n'):gmatch "(.-\n)" do
		if line:sub(1,1) == '\t' then
			table.insert(content, line:sub(2))
		elseif line:match("^!image")  then
			page.illustration = line:match "^!image%s+(%w+)"
		elseif line:match("^!archive") then
			page.archive = true
		else
			local target, action = line:match "^(%w%w%w%w%w):(.-)\n$"
			if action then
				table.insert(page.actions, {action = action, target = target})
			end
		end
	end
	page.content = table.concat(content)

	return page
end

function load_page(p, raw)
	if not p:match("^%w%w%w%w%w$") then return nil end
	local f, bee = io.open('content/'..p)
	if not f then return nil end
	local s = f:read "a"
	f:close()
	if not s then return nil end
	if raw then return s end
	local page = parse_page(s)
	page.id = p
	return page
end

local function new_action(page, action, result)
	local _, directives = convert_markup(result)

::generate_name::
	local new_name = {}
	for i=1,5 do
		table.insert(new_name, string.char(
			string.byte 'a' + math.random(0,25)))
	end
	new_name = table.concat(new_name)

	local exists = io.open('content/'..new_name, 'r')
	if exists then
		exists:close()
		goto generate_name
	end

	local old = assert(io.open('content/'..page, 'a'))
	local new = assert(io.open('content/'..new_name, 'w'))

	action = action:gsub('\n', ' ')
	assert(new:write(action..'\n'))
	for line in (result..'\n'):gmatch "(.-\n)" do
		assert(new:write('\t' .. line))
	end
	assert(old:write(('%s:%s\n'):format(new_name, action)))

	if env "REMOTE_ADDR" then
		new:write(('!ip %s\n'):format(env "REMOTE_ADDR"))
	end

	if directives.backlinks then
		for _,d in ipairs(directives.backlinks) do
			assert(new:write(('%s:%s\n'):format(d.page, d.action)))
		end
	end

	new:close()
	old:close()

	return new_name
end

local hist_template = template [[
	<ul class="hist-log">
		$log
	</ul>
]]
local function show_hist(show_ids)
	local log = {}
	if #history == 0 then return "" end

	for i=#history,1,-1 do
		local page = load_page(history[i])
		if not page then goto continue end

		-- highlight the current page
		local title = i ~= #history and html_encode(page.title)
			or '<strong>'..html_encode(page.title)..'</strong>'
		if show_ids then
			table.insert(log,
				('<li>%s <span class="page-id">%s</span></li>')
					:format(title, history[i]))
		else
			table.insert(log, ('<li>%s</li>'):format(title))
		end
		::continue::
	end
	return hist_template {
		log = table.concat(log),
	}
end

local map = {}

local page_template = template [[
	<h2>$title</h2>
	$illustration
	$content
	$drawthis
	<ul class="actions">
	$actions
	</ul>
	$log
]]
local draw_this = [[
	<p id="draw-this"><a href="$page/illustrate">illustrate this</a></p>
]]
map["^/g/(%w%w%w%w%w)$"] = function(p)
	local page = load_page(p)
	if not page then return not_found() end
	local content, directives = convert_markup(page.content)

	if env "REQUEST_METHOD" ~= "POST" then
		if history[#history] ~= p then
			table.insert(history, p)
		end
		if #history > 75 then
			table.remove(history, 1)
		end

		local title = page.title

		if directives.redirect then
			page = directives.redirect
		end

		local actions = {}
		for _,a in ipairs(page.actions) do
			if target_requirements(a.target) then
				table.insert(actions,
					('<li><a href="%s">%s</a></li>'):format(
						html_encode(a.target), html_encode(a.action)))
			end
		end
		if not directives.deadend and not page.archive then
			table.insert(actions,
				([[
					<li>
						<a class="important" href="%s/act?back=%s#what">%s</a>
					</li>
				]]):format(page.id, p, #page.actions == 0 and
					"do something..." or "do something else...")
			)
		end

		local illustration, draw_this
		if page.illustration then
			illustration = ([[
				<img class="illustration" src="/i/%s.%s" />
			]]):format(page.id, page.illustration)
		else
--			draw_this = ([[
--				<p id="draw-this"><a href="%s/illustrate">
--					illustrate this
--				</a></p>
--			]]):format(p)
		end

		local cookies = {}
		table.insert(cookies,
			('history=%s; path=/; secure; max-age=99999999999')
				:format(table.concat(history, ',')..','))

		for flagname, text in pairs(directives.flags_updated) do
			if text then
				table.insert(cookies,
					('flag_%s=%s; secure; max-age=999999999999')
						:format(flagname, url_encode(text)))
			else
				-- clear the cookie by expiring it in the past
				table.insert(cookies,
					('flag_%s=; expires=Thu, 01 Jan 1970 00:00:00 GMT;')
						:format(flagname))
			end
		end

		return base {
			title = html_encode(title),
			content = page_template {
				title = html_encode(title),
				content = content,
				actions = table.concat(actions),
				illustration = illustration,
				drawthis = draw_this,
				log = show_hist(),
			},
		}, {headers = {["set-cookie"] = cookies, bees = "3.14"}}
	else
		if directives.deadend then
			return base {
				title = "error",
				content = "forbidden",
			}, { status = '403 forbidden' }
		end

		local form = parse_qs(io.read "a")

		form.wyd = form.wyd or "something"
		form.happens = form.happens or "something"
		if utf8.len(form.wyd) > 150 then form.wyd = "something" end
		if utf8.len(form.happens) > 10000 then form.wyd = "something" end

		local new = new_action(p, form.wyd, form.happens)
		return redirect("/g/"..new)
	end
end

map["^/g/(%w%w%w%w%w)/$"] = function(p)
	return redirect('/g/'..p)
end

local edit_template = template [[
	$content
	<hr id="what"/>
	$preview
	<form method="POST">
		<p>
			<a href="/about#rules">READ THIS</a> before touching anything.
		</p>
		<h2>what do you do?</h2>
		<input
			type="text"
			id="wyd" name="wyd"
			value="$title"
			maxlength="150" required
		/>
		<h2>what happens next?</h2>
		<textarea
			id="happens" name="happens"
			maxlength="10000" required
		>$editing</textarea>
		<div class="buttons">
			<a href="$cancel">cancel</a>
			<input type="submit" value="preview" />
			$submit
		</div>
		$log
	</form>
]]
local preview_template = template [[
	<h2>$title</h2>
	$content
	<hr />
]]
local submit_template = template [[
	<input type="submit" formaction="/g/$page" value="submit" />
]]
map["^/g/(%w%w%w%w%w)/act$"] = function(p)
	local page = load_page(p)
	if not page then return not_found() end

	local _, directives = convert_markup(page.content)
	if directives.deadend then return not_found() end

	local query = parse_qs(env "QUERY_STRING" or "")
	local cancel = '/g/'..(query.back or p)

	if env "REQUEST_METHOD" ~= "POST" then
		return base {
			title = "do something new",
			content = edit_template {
				page = p,
				content = convert_markup(page.content),
				log = show_hist(true),
				cancel = html_encode(cancel),
			},
		}
	else
		local form = parse_qs(io.read "a")
		form.wyd = form.wyd or "something"
		form.happens = form.happens or "something"

		local prev, prev_direct = convert_markup(form.happens)

		local prev_title =
			prev_direct.title and html_encode(prev_direct.title) or
				html_encode(form.wyd)

		if prev_direct.redirect then
			local note =
				('<span class="note">previewing %s</span>')
					:format(prev_direct.redirect.id)
			prev = note..prev
		end

		return base {
			title = "do something new",
			content = edit_template {
				page = p,
				content = convert_markup(page.content),
				preview = preview_template {
					title = prev_title,
					content = prev,
				},
				title = html_encode(form.wyd),
				editing = html_encode(form.happens),
				submit = submit_template { page = p },
				cancel = html_encode(cancel),
				log = show_hist(true),
			},
		}
	end
end

local illustrate_template = template [[
	<h2>$title</h2>
	$content
	<hr/>
	<h2 id="what">what does this look like?</h2>
	<form method="POST" action="/g/$page/illustrate"
			enctype="multipart/form-data" id="img-form">
		<input
			type="file"
			name="file"
			accept="image/png,image/jpeg,image/gif"
		/>
		<input type="submit" value="submit image" />
	</form>
]]
-- map["^/g/(%w%w%w%w%w)/illustrate"] = function(p)
-- 	local page = load_page(p)
-- 	if not page then return not_found() end
-- 
-- 	if env "REQUEST_METHOD" ~= "POST" then
-- 		return base {
-- 			title = "illustration: " .. html_encode(page.title),
-- 			content = illustrate_template {
-- 				title = html_encode(page.title),
-- 				content = convert_markup(page.content),
-- 				page = p,
-- 			},
-- 		}
-- 	else
-- 	end
-- end

map["^/i/(%w%w%w%w%w).(%w+)$"] = function(p, format)
	local page = load_page(p)
	if not page or
			not page.illustration or not page.illustration == format then
		return not_found()
	end
	return
		assert(io.open(('content/%s.%s'):format(p, format), 'r')),
		{ content_type = 'image/'..format }
end

map["^/g/(%w%w%w%w%w)/raw$"] = function(p)
	local page = load_page(p, true)
	if not page then return not_found() end

	page = page:gsub("\n!ip [^\n]*", "")

	return page, {
		content_type = 'text/plain',
		headers = { ['access-control-allow-origin'] = "*" }
	}
end

map["^/g/?$"] = function()
	if #history > 0 then
		return redirect('/g/'..history[#history])
	else
		return redirect '/g/zzcxz'
	end
end

map["^/about/?$"] = function()
	return assert(io.open("about.html", 'r'))
end

map["^/robots.txt$"] = function()
	return assert(io.open("robots.txt", 'r')),
		{ content_type = 'text/plain' }
end

local index_template = template [[
<!doctype html>
<html>
	<head>
		<link rel="stylesheet" href="/static/amethyst.css" />
		<meta charset="utf-8" />
		<title>zzcxz</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta property="og:title" content="zzcxz" />
		<meta property="og:description" content="the zzcxz is to be entered. do not believe what you read" />
		<meta property="og:image" content="https://zzcxz.citrons.xyz/static/zzcxz.png" />
	</head>
	<body>
		<main class="index">
			<img class="logo" src="/static/zzcxz.png" alt="zzcxz" />
			<ul class="actions">
				$actions
				<li><a href="/about">help</a></li>
			</ul>
		</main>
	</body>
</html>
]]
map["^/$"] = function()
	local last_page =
		load_page(history[#history] or 'zzcxz') or load_page 'zzcxz'
	local actions = ('<li><a href="/g/%s" class="important">%s</a></li>')
		:format(last_page.id, html_encode(last_page.title))
	if last_page.id ~= 'zzcxz' then
		actions = actions .. '<li><a href="/g/zzcxz">reenter the zzcxz</a></li>'
	end
	return index_template {actions = actions}
end

local function main()
	for k,v in pairs(map) do
		local m = {(env "PATH_INFO"):match(k)}
		if m[1] then
			return v(table.unpack(m))
		end
	end
	return not_found()
end

local ok, content, resp = pcall(main)
if not ok or (type(content) ~= 'string' and type(content) ~= 'userdata') then
	io.stderr:write(content..'\n')

	content = base {
		title = "internal error",
		content = "an internal error occurred."
	}
	resp = { status = '500 internal server error' }
end

resp = resp or {}
resp.content_type = resp.content_type or 'text/html'
resp.status = resp.status or '200 OK'
resp.headers = resp.headers or {}
resp.headers['content-type'] = resp.content_type
resp.headers['apioforms'] = math.random(0,104942)/2

print("status: "..resp.status)
for k,v in pairs(resp.headers) do
	if type(v) == "table" then
		for _, v2 in ipairs(v) do
			print(("%s: %s"):format(k, v2))
		end
	else
		print(("%s: %s"):format(k, v))
	end
end

print ""
if type(content) == 'string' then
	io.write(content)
else
	while 1 do
		local data = content:read(1024)
		if not data then break end
		io.write(data)
	end
end