-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.rb
executable file
·454 lines (384 loc) · 16 KB
/
server.rb
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
#!/usr/bin/env ruby
require 'rubygems'
require_relative 'database.rb'
require_relative 'entry.rb'
require_relative 'comment.rb'
require 'sinatra/base'
require 'xmlrpc/marshal'
require 'json'
include ERB::Util
require 'sinatra/browserid'
require 'thread/pool'
require 'rack/contrib/try_static'
require "open-uri"
module Ursprung
class Ursprung < Sinatra::Application
register Sinatra::BrowserID
set :static_cache_control, [:public, max_age: 31536000]
set :assets, Sprockets::Environment.new
class << self; attr_accessor :baseUrl end
class << self; attr_accessor :pool end
@pool = Thread.pool(2)
helpers do
include Rack::Utils
alias_method :uh, :escape
alias_method :h, :escape_html
alias_method :u, :unescape
def isAdmin?
if authorized?
if normalize_email(Database.new.getAdminMail) == authorized_email
return true
end
end
return false
end
def protected!
unless isAdmin?
throw(:halt, [401, "Not authorized\n"])
end
end
def blogOwner
return Database.new.getAdmin
end
def blogOwnerMail
return Database.new.getAdminMail
end
def blogTitle
return Database.new.getOption("blogTitle")
end
def autotitle(text)
db = Database.new
Oga.parse_html(text).css("a").map do |link|
if (href = link.attr("href").value) && link.attr("title") == nil && href.match(/^https?:/)
if ((title, _ = db.getCache(href)) == nil)
begin
page = URI.parse(URI.escape(href)).read
parsed_page = Oga.parse_html(page)
title = parsed_page.css('title').first.text
rescue Exception => error
warn error.to_s
title = ""
end
db.cache(href, title)
end
old_link = link.to_xml
link = link.to_xml.sub("<a", "<a title=\"#{title}\"")
begin
text[old_link] = link
rescue IndexError => ie
warn "could not insert #{title}: " + ie.to_s
end
end
end
return text
end
def excerpt (text, length = 200)
Strings.truncate(text, length)
end
def stripHtml(text)
fragment = Oga.parse_html(text)
stripped = ''
block = false
fragment.each_node do |element|
if element.class == Oga::XML::Text && block == false
stripped += element.text
end
if element.class != Oga::XML::Text
if element.name == 'script'
block = true
end
if element.name != 'script'
block = false
end
end
end
return stripped
end
def firstImage(text)
Oga.parse_html(text).css('img').first&.to_xml || ''
end
def find_template(views, name, engine, &block)
super(views, name, engine, &block) if File.exist?(File.join(views, name.to_s + ".erb"))
super(settings.design_default, name, engine, &block)
end
end
def self.loadConfiguration()
design = Database.new.getOption("design")
settings.views = File.join(settings.design_root, design)
use Rack::TryStatic, :root => File.join(settings.views, 'public'), :urls => %w[/] # first look in the designs public folder
settings.public_folder = 'public' # and otherwise in the global one, where also all the uploads are
settings.assets.clear_paths # js/css files else stay the same after a design switch
settings.assets.append_path File.join(settings.views, "js")
settings.assets.append_path File.join(settings.views, "css")
settings.assets.append_path File.join(settings.design_default, "js") if design != "default"
settings.assets.append_path File.join(settings.design_default, "css") if design != "default"
end
configure do
set(:design_root) { File.join(File.dirname(__FILE__), "designs") }
set(:design_default) { File.join(design_root, "default") }
loadConfiguration
end
####
#
# Careful: Don't let this become a blob. Delegate
#
####
before do
Ursprung::baseUrl = url('/', :full)
end
get '/' do
serveIndex()
end
get %r{/archive/([0-9]+)/([\w]+)} do |page, tag|
serveIndex(page: page.to_i, tag: tag)
end
get %r{/archive/([0-9]+)} do |page|
serveIndex(page: page.to_i)
end
get %r{/archive/([\w]+)} do |tag|
serveIndex(page: -1, tag: tag)
end
def serveIndex(page: -1, tag: nil)
db = Database.new
if db.firstUse?
db.setOption("secret", SecureRandom.urlsafe_base64(256))
db.setOption("blogTitle", "just a blog")
db.invalidateCache(nil)
erb :installer
else
limit = 5
totalPages, _ = db.getTotalPages(limit, tag)
page = totalPages if page == -1
entries = db.getEntries(page: page, limit: 5, tag: tag)
designs = Dir.new(settings.design_root).entries.reject{|design| design == "." || design == ".." }
design = db.getOption("design")
body erb :index, :locals => {:entries => entries, :page => page, :totalPages => totalPages, :designs => designs, :design => design, :tag => tag, :allTags => db.getAllTags}
end
end
get %r{/feed/([\w]+)} do |tag|
totalPages, _ = Database.new.getTotalPages(limit, tag)
entries = Database.new.getEntries(page: -1, limit: 10, tag: tag)
headers "Content-Type" => "application/rss+xml"
body erb :feed, :locals => {:entries => entries}
end
get '/feed' do
entries = Database.new.getEntries(page: -1, limit: 10, tag: nil)
headers "Content-Type" => "application/rss+xml"
body erb :feed, :locals => {:entries => entries}
end
post '/addEntry' do
protected!
entry = Entry.new(params, request)
redirect url entry.link + '#new'
end
post %r{/([0-9]+)/addTrackback} do |id|
paramsNew = {:name => params[:blog_name], :body => params[:excerpt], :entryId => id, :type => 'trackback', :url => params[:url], :mail => ""}
trackback = Comment.new(paramsNew, request)
if trackback.validTrackback
'<?xml version="1.0" encoding="utf-8"?>
<response>
<error>0</error>
</response>'
else
'<?xml version="1.0" encoding="utf-8"?>
<response>
<error>1</error>
<message>Could not find originating link</message>
</response>'
end
end
# solely used to handle pingbacks
post '/xmlrpc' do
xml = request.body.read
if(xml.empty?)
error = 400
return
end
method, arguments = XMLRPC::Marshal.load_call(xml)
if method == 'pingback.ping'
source = arguments[0]
target = arguments[1]
id = target.gsub(/http:\/\/.*\/([0-9]*)\/.*/, '\1')
paramsNew = {:name => "", :body => "", :entryId => id, :type => 'trackback', :url => source, :mail => ""}
comment = Comment.new(paramsNew, request)
content_type("text/xml", :charset => "utf-8")
if comment.validTrackback
XMLRPC::Marshal.dump_response("Pingback successfully added")
else
XMLRPC::Marshal.dump_response("Error: Didn't find pingback-link on originating page")
error = 400
end
else
error = 404
end
end
post '/file' do
protected!
filedata = Base64.decode64(params[:data].slice(params[:data].index('base64') + 7, params[:data].length))
target = File.join(settings.public_folder, 'upload', params[:filename].gsub("..", ""))
until ! File.exists?(target)
return target.gsub(settings.public_folder, "") if Digest::MD5.hexdigest(filedata) == Digest::MD5.hexdigest(File.open(target).read())
# assume the filename is a classical xy.abc, but dont forget the leading ./ of settings.public_folder
target = target.reverse.sub('.','._').reverse if target.scan(".").size > 1
target = target + "_" if target.scan(".").size <= 1
end
File.new(target, "w+").write(filedata)
request.script_name + target.gsub(settings.public_folder, "").gsub(" ", "+")
end
get %r{/([0-9]+)/editEntry} do |id|
protected!
entry = Entry.new(id.to_i)
erb :edit, :locals => {:entry => entry}
end
get %r{/([0-9]+)/editComment} do |id|
protected!
comment = Comment.new(id.to_i)
entry = Entry.new(comment.replyToEntry)
erb :editComment, :locals => {:comment => comment, :entry => entry}
end
post %r{/([0-9]+)/deleteComment} do |id|
protected!
Comment.new(id.to_i).delete
"Done"
end
post %r{/([0-9]+)/spam} do |id|
protected!
comment = Comment.new(id.to_i)
comment.spam()
comment.delete
"Done"
end
post %r{/([0-9]+)/ham} do |id|
protected!
comment = Comment.new(id.to_i)
comment.ham()
baseUrl = url '/', :full
comment.save() # ham also marks as approved, which needs to be saved
Ursprung::pool.process {
comment.mailSubscribers()
}
return "Done" if ! request.xhr?
erb :comment, :locals => {:comment => comment}
end
get %r{/([0-9]+)/verdict} do |id|
if Comment.new(id.to_i).isSpam?
"spam"
else
"ham"
end
end
post %r{/([0-9]+)/deleteEntry} do |id|
protected!
Entry.new(id.to_i).deleteSoft
"Done"
end
post %r{/([0-9]+)/restoreEntry} do |id|
protected!
Entry.new(id, nil, {:deleted => true}).save()
"Done"
end
post %r{/([0-9]+)/addComment} do |id|
entry = Entry.new(id.to_i)
params[:entryId] = id
comment = Comment.new(params, :new)
redirect url (comment.entry.link + "#" + comment.status)
end
get '/commentFeed' do
comments = Database.new.getComments(30)
headers "Content-Type" => "application/rss+xml"
body erb :commentFeed, :locals => {:comments => comments}
end
post '/addAdmin' do
db = Database.new
if db.firstUse? && ! authorized_email.empty?
name = params[:name]
db.addUser(name, authorized_email)
db.invalidateCache(nil)
redirect to('/')
else
'Error adding admin: param missing or admin already set'
end
end
post '/setOption' do
protected!
Database.new.setOption(params[:name], params[:value])
Database.new.invalidateCache(nil) # options are normally mighty enough to invalidate everything
Ursprung::loadConfiguration
origin = session[:origin]
# when setOption wasn't called first, like with the design, origin is old, so unset it
session.delete(:origin)
redirect origin if origin != nil
redirect back
end
get %r{/setOption/([\w]+)} do |name|
protected!
session[:origin] = back
erb :editOption, :locals => {:name => name, :value => Database.new.getOption(name)}
end
get %r{/search/([\w]+)} do |keyword|
db = Database.new
designs = Dir.new(settings.design_root).entries.reject{|design| design == "." || design == ".." }
design = db.getOption("design")
body erb :search, :locals => {:entries => db.searchEntries(keyword), :keyword => keyword, :designs => designs, :design => design}
end
get '/search' do
redirect url '/search/'+params[:keyword]
end
post '/preview' do
protected!
entry = Entry.new(params.merge({:preview => true}), request)
entry.date = DateTime.now().to_s
Database.new.deleteStoredEntries() # this has nothing to do with the preview, it just need to be somewhere
erb :entry, :locals => {:entry => entry}
end
post %r{/([0-9]+)/setEntryModeration} do |id|
protected!
Database.new.setEntryModeration(id, params[:value])
redirect back if ! request.xhr?
end
# A Page (entry with comments)
get %r{/([0-9]+)/(.+)} do |id, title|
db = Database.new
entry = Entry.new(id.to_i)
comments = db.getCommentsForEntry(id)
designs = Dir.new(settings.design_root).entries.reject{|design| design == "." || design == ".." }
design = db.getOption("design")
body erb :page, :locals => {:entry => entry, :comments => comments, :designs => designs, :design => design}
end
get '/subscriptions/:mail' do
db = Database.new
cipher = OpenSSL::Cipher::Cipher.new('bf-cbc').send(:decrypt)
cipher.key = Digest::SHA256.digest(db.getOption("secret"))
mail = cipher.update(params[:mail]) << cipher.final
body erb :subscriptions, :locals => {:mail => mail, :entries => db.getEntriesSubscribed(mail), :encryptedMail => params[:mail]}
end
post '/unsubscribe' do
db = Database.new
cipher = OpenSSL::Cipher::Cipher.new('bf-cbc').send(:decrypt)
cipher.key = Digest::SHA256.digest(db.getOption("secret"))
mail = cipher.update(u(params[:encryptedMail])) << cipher.final
db.unsubscribe(mail, params[:id])
db.invalidateCache("/subscriptions/%")
redirect back
end
get %r{/designinfo/([\w]+)} do |availableDesign|
target = File.join(settings.design_root, availableDesign.gsub("..", ""), 'about.txt')
body File.new(target).read
end
get "/js/:file.js" do
content_type "application/javascript"
body settings.assets[params[:file]+".js"].to_s
end
get "/css/:file.css" do
content_type "text/css"
body settings.assets[params[:file]+".css"].to_s
end
get '/login' do
body erb :login
end
post '/logout' do
logout!
redirect url '/'
end
end
end