-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfunctions.js
378 lines (337 loc) · 12 KB
/
functions.js
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
var views = require('./views')
, vacuum = require('vacuum')
, marked = require('marked')
, forum = require('./')
, parseURL = require('url').parse
, formatURL = require('url').format
forum.escapeText = escapeText // hmmm... kind of ugly...
var PAGE_SIZE = forum.PAGE_SIZE = 20
function renderContent(template, functions, context, chunk, done) {
var templateCopy = {}
vacuum.copyProps(templateCopy, template)
delete templateCopy.type
if (!templateCopy.parts) throw new Error('template must have "parts", only has '+Object.keys(templateCopy).join(','))
vacuum.renderTemplate(template, functions, context, chunk, done)
}
function insertSmileys(text) {
var SMILEYS =
{ ':)': 'Smiling'
, ':D': 'Grinning'
, ':(': 'Unhappy'
, ':/': 'Uncertain'
}
Object.keys(SMILEYS).forEach(function(needle) {
var replacement = '<img src="/static/smileys/'+SMILEYS[needle]+'.png/'+forum.ramstatic.unique+'">'
var i = 0
while (true) {
var nextText = text.slice(i)
var nextTagOpen = nextText.indexOf('<')+i
var nextSmiley = nextText.indexOf(needle)+i
if (nextSmiley === i-1) break
if (nextTagOpen !== i-1 && nextTagOpen < nextSmiley) {
var nextTagEnd = nextText.indexOf('>')+i
if (nextTagEnd !== i-1) {
i = nextTagEnd + 1
continue
}
}
nextText = nextText.replace(needle, replacement)
text = text.slice(0, i) + nextText
i = nextSmiley+1
}
})
return text
}
function sanitizeHTML(text) {
text = text.replace(/</g, '<')
text = text.replace(/>/g, '>')
return text
}
function unsanitizeHTML(text) {
var tags =
{ a: ['href', 'title']
, p: []
, em: []
, ul: []
, li: []
, strong: []
, code: []
, pre: []
, img: ['src', 'alt']
, blockquote: []
}
var tagsWithBody = ['a', 'p', 'em', 'ul', 'li', 'strong', 'code', 'pre', 'blockquote']
tagfinder: for (var i=0; i<text.length; i++) {
if (text.slice(i, i+4) !== '<') continue
i+=4
var attrsStart = text.slice(i).indexOf(' ')+i
var attrsEnd = text.slice(i).indexOf('>')+i
if (attrsEnd < i) break // no more ">" - there can't be any more tags
if (attrsStart > attrsEnd || attrsStart === i-1) attrsStart = attrsEnd // attributeless
var nodeName = text.slice(i, attrsStart)
if (!tags.hasOwnProperty(nodeName)) continue
var allowedProperties = tags[nodeName]
var attrsStr = text.slice(attrsStart, attrsEnd)
var attrsOK = attrsStr.split(/ (?=[^"]*(?:(?:"[^"]*){2})*$)/).map(function(attrStr) {
return attrStr.trim()
}).filter(function(attrStr) {
return attrStr !== ''
}).every(function(attrStr) {
attrStr = attrStr.split('=')
var name = attrStr[0]
if (allowedProperties.indexOf(name) === -1) return false
var value = attrStr.slice(1).join('=')
if (value.length < 2) return false
if (value[0] !== '"') return false
if (value[value.length-1] !== '"') return false
value = value.slice(1, -1)
// yes, this will give me some false positives, but it should at least be secure.
if (/[\r\n\\"]/.test(value)) return false
if (name === 'href') {
// "javascript:" URLs, yay!
if (value.slice(0, 7) !== 'http://' && value.slice(0, 8) !== 'https://') return false
}
return true
})
if (!attrsOK) continue
if (tagsWithBody.indexOf(nodeName) !== -1) {
// ugh.
// basically, we have to find a closing tag. aaand avoid stuff like <a><b></a></b>.
// so, if we meet no opening tag for this until we see the closing tag, all is well.
// if we do meet one, GRAAH.
// example: <p><p></p></p>
var stack = [nodeName]
var seekTagI = attrsEnd
var lastClosePos
while (stack.length > 0) {
// find next <
seekTagI++
reResult = /</.exec(text.slice(seekTagI))
if (!reResult) continue tagfinder
seekTagI += reResult.index
if (text[seekTagI+4] === '/') {
var tagCloseReResult = /^([a-z]+)>/.exec(text.slice(seekTagI+5))
if (!tagCloseReResult) continue
if (stack[stack.length-1] !== tagCloseReResult[1]) continue
stack.pop()
lastClosePos = seekTagI
continue
}
var openTagReResult = /^([a-z]+)(?:>| )/.exec(seekTagI+4)
if (!openTagReResult) continue
if (tagsWithBody.indexOf(openTagReResult[1]) !== -1) {
stack.push(openTagReResult[1])
}
}
// phew, we've found a closing tag. so, let's verify that there are no < or > chars in between.
if (/<|>/.test(text.slice(attrsEnd, lastClosePos))) continue
// as we already know the tag is ok, unescape the closing tag.
text = text.slice(0, lastClosePos)
+ '</'
+ nodeName
+ '>'
+ text.slice(lastClosePos+('</'+nodeName+'>').length)
}
// this tag is ok. unescape it.
text = text.slice(0, i-4) // stuff in front of this
+ '<'
+ nodeName
+ (attrsStr ? ' ' : '')
+ attrsStr
+ '>'
+ text.slice(attrsEnd+4)
i-=3
}
text = text.replace(/&/g, '&')
return text
}
function escapeAttribute(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
}
function escapeText(value, format) {
if (format === 'plain') {
value = sanitizeHTML(value)
} else if (format === 'hex') {
value = value.replace(/[^0-9a-f]/gi, '')
} else if (format === 'markdown') {
value = marked(value)
value = insertSmileys(value)
value = value.replace(/&/g, '&')
value = sanitizeHTML(value)
value = unsanitizeHTML(value)
} else if (format === 'attribute') {
value = escapeAttribute(value)
} else {
throw new Error('unknown sanitization class: '+format)
}
return value
}
// -------------------------------------------------------------------------------------------------
exports.text = function TEXT(template, functions, context, chunk, done) {
var value = vacuum.getFromContext(context, 'name')
var format = context.format
value = escapeText(value, format)
chunk(value)
done()
}
// adds "thread.posts", "thread.owner", "thread.title", "thread.length", "thread.title"
// needs "thread" key
exports.withthread = function WITHTHREAD(template, functions, context, chunk, done) {
var childContext = {}
vacuum.copyProps(childContext, context)
var thread = {}
childContext.thread = thread
var needed = 2
var goOn = renderContent.bind(null, template, functions, childContext, chunk, done)
views.getThreadPosts(context.thread, PAGE_SIZE, PAGE_SIZE * ((context.page-1) || 0), function(err, data) {
if (err) return done(err)
thread.posts = data.rows
thread.length = data.total_rows
thread.pages = Math.ceil(data.total_rows / PAGE_SIZE)
thread.id = context.thread
childContext.maxpage = thread.pages
thread.posts.forEach(function(post) {
post.value.creation = new Date(post.value.creation).toGMTString()
if (post.value.modification) post.value.modification = new Date(post.value.modification).toGMTString()
})
if (!--needed) goOn()
})
views.getThread(context.thread, function(err, data) {
if (err) return done(err)
thread.owner = data.owner
thread.title = data.title
thread.path = data.path
if (!--needed) goOn()
})
}
exports.withforum = function WITHFORUM(template, functions, context, chunk, done) {
var childContext = {}
vacuum.copyProps(childContext, context)
var forum = {}
childContext.forum = forum
views.getForum(context.forum, PAGE_SIZE, PAGE_SIZE * ((context.page-1) || 0), function(err, data) {
if (err) return done(err)
forum.threads = data.rows
forum.length = data.total_rows
forum.title = data.meta.title
forum.pages = Math.ceil(data.total_rows / PAGE_SIZE)
forum.id = context.forum
childContext.maxpage = forum.pages
forum.threads.forEach(function(thread) {
thread.value.lastpost = new Date(thread.value.lastpost).toGMTString()
thread.id = thread.id.split(':')[1]
})
renderContent(template, functions, childContext, chunk, done)
})
}
exports.withsuperforum = function WITHSUPERFORUM(template, functions, context, chunk, done) {
var childContext = {}
vacuum.copyProps(childContext, context)
var forum = {}
childContext.superforum = forum
views.getSuperforum(context.superforum, function(err, data) {
if (err) return done(err)
forum.rows = data.rows.map(function(subforum) {
return (
{ title: subforum.value.title
, link: '/' + subforum.value.type + '/' + encodeURI(subforum.value.path) + ((subforum.value.type === 'forum') ? '/1' : '')
})
})
forum.length = data.total_rows
forum.title = data.meta.title
forum.pages = Math.ceil(data.total_rows / PAGE_SIZE)
forum.id = context.superforum
childContext.maxpage = forum.pages
renderContent(template, functions, childContext, chunk, done)
})
}
exports.if = function IF(template, functions, context, chunk, done) {
var name = vacuum.getFromContext(context, 'name', true)
if (!name) return done()
var templateCopy = {}
vacuum.copyProps(templateCopy, template)
delete templateCopy.type
vacuum.renderTemplate(templateCopy, functions, context, chunk, done)
}
exports.static = function STATIC(template, functions, context, chunk, done) {
var file = context.file
if (!file) throw new Error('falsy "file"')
chunk('/static/'+file+'/'+forum.ramstatic.unique)
done()
}
exports.pagenav = function PAGENAV(template, functions, context, chunk, done) {
var page = +context.page
var maxpage = +context.maxpage
var urlpos = context.pageURLPos
if (!page) throw new Error('invalid page')
if (!maxpage && maxpage !== 0) throw new Error('invalid maxpage: '+maxpage)
if (!urlpos) throw new Error('invalid urlpos')
var leftURL = addToURLPart(-1)
var rightURL = addToURLPart(1)
var data = ''
if (page > 1) {
data += '<a href="'+leftURL+'"><img src="/static/arrow-left.png/'+forum.ramstatic.unique+'"></a> '
}
data += 'page '+page+' of '+maxpage
if (page < maxpage) {
data += ' <a href="'+rightURL+'"><img src="/static/arrow-right.png/'+forum.ramstatic.unique+'"></a>'
}
chunk(data)
return done()
function addToURLPart(change) {
url = parseURL(context.request.url)
var path = url.pathname.split('/')
path[urlpos] = +path[urlpos] + change
url.pathname = path.join('/')
return formatURL(url)
}
}
exports.rePOST = function rePOST(template, functions, context, chunk, done) {
var NOREPOST = ['formtoken', 'loginUser', 'loginPassword', 'registerUser', 'registerPassword', 'registerRecoverData']
if (!context.postData) return done() // no POST, no data
var pairs = []
Object.keys(context.postData).forEach(function(key) {
var values = context.postData[key]
if (typeof values === 'string') values = [values]
values.forEach(function(value) {
if (NOREPOST.indexOf(key) !== -1) return
pairs.push({key: key, value: value})
})
})
chunk(pairs.map(function(pair) {
return '<input type="hidden" name="'
+ escapeAttribute(pair.key)
+ '" value="'
+ escapeAttribute(pair.value)
+ '">'
}).join('\n'))
done()
}
exports.uplinks = function UPLINKS(template, functions, context, chunk, done) {
var path = vacuum.getFromContext(context, 'pathvar').split('/')
var type = context.type
var output = ''
if (type === 'thread') {
prepend(path, false)
output = '/'+output
} else if (type === 'forum' || type === 'superforum') {
} else throw new Error('unknown type')
path.pop()
while (path.length > 0) {
prepend(path, true)
output = '/'+output
path.pop()
}
output = '<a href="/superforum">root</a>'
+ output
chunk(output)
done()
function prepend(path, isSuperforum) {
output = '<a href="/'+(isSuperforum?'superforum':'forum')+'/'+escapeAttribute(path.join('/'))+(isSuperforum?'">':'/1">')
+ escapeText(path[path.length-1], 'plain')
+ '</a>'
+ output
}
}