This repository has been archived by the owner on Sep 25, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.rb
551 lines (462 loc) · 15.5 KB
/
app.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
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
require 'rubygems'
require 'bundler/setup'
require 'cgi'
require 'net/ldap'
require 'gollum-lib'
require 'sinatra'
require 'mustache/sinatra'
require 'useragent'
require 'stringex'
require_relative 'views/layout'
require_relative 'views/editable'
require_relative 'views/has_page'
require File.expand_path '../helpers', __FILE__
require File.expand_path('../uri_encode_component', __FILE__)
# Fix to_url
class String
alias :upstream_to_url :to_url
# _Header => header which causes errors
def to_url
return nil if self.nil?
return self if ['_Header', '_Footer', '_Sidebar'].include? self
upstream_to_url
end
end
# Run the frontend, based on Sinatra
#
# There are a number of wiki options that can be set for the frontend
#
# Example
# require 'app'
# Precious::App.set(:wiki_options, {
# :universal_toc => false,
# }
#
# See the wiki.rb file for more details on wiki options
module Precious
class App < Sinatra::Base
register Mustache::Sinatra
include Precious::Helpers
helpers do
def protected!
return unless settings.respond_to?('private')
redirect to("/login") unless authorized?
end
def authorized?
@session.include? :username
end
def may_login
settings.respond_to?('ldap')
end
def auth(username, pass)
return nil unless may_login
user = settings.ldap[:base] % username
ldap = Net::LDAP.new :host => settings.ldap[:host],
:port => settings.ldap[:port], :auth => {
:method => :simple,
:username => user,
:password => pass
}
return nil unless ldap.bind
account = ldap.search( :base => user).first
cn = account[:cn].first
email = ""
return {:username => cn, :email => email}
end
def spamfilter!(params)
score = 0
message = params[:message]
score += 1.0 if (params.member? :email) and (not params[:email].empty?)
score += 0.8 if message.include? "<a "
score += 0.8 if message.include? "[url="
score += 0.8 if message.include? "[link="
score += 0.2 if message.include? "http"
redirect to("/") if score >= 1.0
end
end
dir = File.dirname(File.expand_path(__FILE__))
# Detect unsupported browsers.
Browser = Struct.new(:browser, :version)
@@min_ua = [
Browser.new('Internet Explorer', '10.0'),
Browser.new('Chrome', '7.0'),
Browser.new('Firefox', '4.0'),
]
def supported_useragent?(user_agent)
ua = UserAgent.parse(user_agent)
@@min_ua.detect {|min| ua >= min }
end
# We want to serve public assets for now
set :public_folder, "#{dir}/public/gollum"
set :static, true
set :default_markup, :markdown
set :mustache, {
# Tell mustache where the Views constant lives
:namespace => Precious,
# Mustache templates live here
:templates => "#{dir}/templates",
# Tell mustache where the views are
:views => "#{dir}/views"
}
# Sinatra error handling
configure :development, :staging do
enable :show_exceptions, :dump_errors
disable :raise_errors, :clean_trace
end
configure :test do
enable :logging, :raise_errors, :dump_errors
end
enable :sessions
before do
@session = session
@may_login = may_login
@base_url = url('/', false).chomp('/')
settings.wiki_options.merge!({ :base_path => @base_url }) unless settings.wiki_options.has_key? :base_path
end
get '/' do
redirect File.join(settings.wiki_options[:base_path].to_s, 'Home')
end
get '/login' do
halt 404 unless may_login
# show login page
mustache :login
end
post '/login' do
halt 404 unless may_login
# attempt to login user using params[:login] and params[:password]
# and sets session[:username] and session[:email] on success
#
#
# login failed. redirect to /login and add a message
session.clear
result = auth(params[:login], params[:password])
halt 401 if result.nil?
session[:username] = result[:username]
session[:email] = result[:email]
redirect to("/")
end
get '/logout' do
# log user out, clear session
session.clear
mustache :logout
end
# Removes all slashes from the start of string.
def clean_url url
return url if url.nil?
url.gsub('%2F','/').gsub(/^\/+/,'')
end
# path is set to name if path is nil.
# if path is 'a/b' and a and b are dirs, then
# path must have a trailing slash 'a/b/' or
# extract_path will trim path to 'a'
# name, path, version
def wiki_page(name, path = nil, version = nil, exact = true)
path = name if path.nil?
name = extract_name(name)
path = extract_path(path)
path = '/' if exact && path.nil?
wiki = wiki_new
OpenStruct.new(:wiki => wiki, :page => wiki.paged(name, path, exact, version),
:name => name, :path => path)
end
def wiki_new
Gollum::Wiki.new(settings.gollum_path, settings.wiki_options)
end
get '/data/*' do
if page = wiki_page(params[:splat].first).page
page.raw_data
end
end
get '/edit/*' do
protected!
wikip = wiki_page(params[:splat].first)
@name = wikip.name
@path = wikip.path
wiki = wikip.wiki
if page = wikip.page
if wiki.live_preview && page.format.to_s.include?('markdown') && supported_useragent?(request.user_agent)
live_preview_url = '/livepreview/?page=' + encodeURIComponent(@name)
if @path
live_preview_url << '&path=' + encodeURIComponent(@path)
end
redirect to(live_preview_url)
else
@page = page
@page.version = wiki.repo.log(wiki.ref, @page.path).first
@content = page.text_data
mustache :edit
end
else
redirect to("/create/#{encodeURIComponent(@name)}")
end
end
post '/rename/*' do
protected!
wikip = wiki_page(params[:splat].first)
halt 500 if wikip.nil?
wiki = wikip.wiki
page = wiki.paged(wikip.name, wikip.path, exact = true)
rename = params[:rename]
halt 500 if page.nil?
halt 500 if rename.nil? or rename.empty?
# Fixup the rename if it is a relative path
# In 1.8.7 rename[0] != rename[0..0]
if rename[0..0] != '/'
source_dir = ::File.dirname(page.path)
source_dir = '' if source_dir == '.'
(target_dir, target_name) = ::File.split(rename)
target_dir = target_dir == '' ? source_dir : "#{source_dir}/#{target_dir}"
rename = "#{target_dir}/#{target_name}"
end
committer = Gollum::Committer.new(wiki, commit_message)
commit = { :committer => committer }
success = wiki.rename_page(page, rename, commit)
if !success
# This occurs on NOOPs, for example renaming A => A
redirect to("/#{page.escaped_url_path}")
return
end
committer.commit
wikip = wiki_page(rename)
page = wiki.paged(wikip.name, wikip.path, exact = true)
return if page.nil?
redirect to("/#{page.escaped_url_path}")
end
post '/edit/*' do
protected!
spamfilter!(params)
path = '/' + clean_url(sanitize_empty_params(params[:path])).to_s
page_name = CGI.unescape(params[:page])
wiki = wiki_new
page = wiki.paged(page_name, path, exact = true)
return if page.nil?
committer = Gollum::Committer.new(wiki, commit_message)
commit = { :committer => committer }
update_wiki_page(wiki, page, params[:content], commit, page.name, params[:format])
update_wiki_page(wiki, page.header, params[:header], commit) if params[:header]
update_wiki_page(wiki, page.footer, params[:footer], commit) if params[:footer]
update_wiki_page(wiki, page.sidebar, params[:sidebar], commit) if params[:sidebar]
committer.commit
redirect to("/#{page.escaped_url_path}") unless page.nil?
end
get '/delete/*' do
wikip = wiki_page(params[:splat].first)
name = wikip.name
wiki = wikip.wiki
page = wikip.page
wiki.delete_page(page, { :message => "Destroyed #{name} (#{page.format})" })
redirect to('/')
end
get '/create/*' do
wikip = wiki_page(params[:splat].first.gsub('+', '-'))
@name = wikip.name.to_url
@path = wikip.path
page = wikip.page
if page
redirect to("/#{page.escaped_url_path}")
else
mustache :create
end
end
post '/create' do
name = params[:page].to_url
path = sanitize_empty_params(params[:path])
path = '' if path.nil?
format = params[:format].intern
# write_page is not directory aware so use wiki_options to emulate dir support.
wiki_options = settings.wiki_options.merge({ :page_file_dir => path })
wiki = Gollum::Wiki.new(settings.gollum_path, wiki_options)
begin
wiki.write_page(name, format, params[:content], commit_message)
redirect to("/#{clean_url(CGI.escape(::File.join(path,name)))}")
rescue Gollum::DuplicatePageError => e
@message = "Duplicate page: #{e.message}"
mustache :error
end
end
post '/revert/:page/*' do
wikip = wiki_page(params[:page])
@path = wikip.path
@name = wikip.name
wiki = wikip.wiki
@page = wiki.paged(@name,@path)
shas = params[:splat].first.split("/")
sha1 = shas.shift
sha2 = shas.shift
commit = commit_message
commit[:message] = "Revert commit #{sha1.chars.take(7).join}"
if wiki.revert_page(@page, sha1, sha2, commit)
redirect to("/#{@page.escaped_url_path}")
else
sha2, sha1 = sha1, "#{sha1}^" if !sha2
@versions = [sha1, sha2]
diffs = wiki.repo.diff(@versions.first, @versions.last, @page.path)
@diff = diffs.first
@message = "The patch does not apply."
mustache :compare
end
end
post '/preview' do
wiki = wiki_new
@name = params[:page] || "Preview"
@page = wiki.preview_page(@name, params[:content], params[:format])
@content = @page.formatted_data
@toc_content = wiki.universal_toc ? @page.toc_data : nil
@mathjax = wiki.mathjax
@h1_title = wiki.h1_title
@editable = false
mustache :page
end
get '/livepreview/' do
wiki = wiki_new
@mathjax = wiki.mathjax
mustache :livepreview, { :layout => false }
end
get '/history/*' do
@page = wiki_page(params[:splat].first).page
@page_num = [params[:page].to_i, 1].max
unless @page.nil?
@versions = @page.versions :page => @page_num
mustache :history
else
redirect to("/")
end
end
get '/latest_changes' do
@wiki = wiki_new
max_count = settings.wiki_options.fetch(:latest_changes_count, 10)
@versions = @wiki.latest_changes({:max_count => max_count})
mustache :latest_changes
end
post '/compare/*' do
@file = encodeURIComponent(params[:splat].first)
@versions = params[:versions] || []
if @versions.size < 2
redirect to("/history/#{@file}")
else
redirect to("/compare/%s/%s...%s" % [
@file,
@versions.last,
@versions.first]
)
end
end
get %r{
/compare/ # match any URL beginning with /compare/
(.+) # extract the full path (including any directories)
/ # match the final slash
([^.]+) # match the first SHA1
\.{2,3} # match .. or ...
(.+) # match the second SHA1
}x do |path, start_version, end_version|
wikip = wiki_page(path)
@path = wikip.path
@name = wikip.name
@versions = [start_version, end_version]
wiki = wikip.wiki
@page = wikip.page
diffs = wiki.repo.diff(@versions.first, @versions.last, @page.path)
@diff = diffs.first
mustache :compare
end
get %r{^/(javascript|css|images)} do
halt 404
end
get %r{/(.+?)/([0-9a-f]{40})} do
file_path = params[:captures][0]
version = params[:captures][1]
wikip = wiki_page(file_path, file_path, version)
name = wikip.name
path = wikip.path
if page = wikip.page
@page = page
@name = name
@content = page.formatted_data
@editable = true
mustache :page
else
halt 404
end
end
get '/search' do
@query = params[:q]
wiki = wiki_new
@results = wiki.search @query
@name = @query
mustache :search
end
get %r{
/pages # match any URL beginning with /pages
(?: # begin an optional non-capturing group
/(.+) # capture any path after the "/pages" excluding the leading slash
)? # end the optional non-capturing group
}x do |path|
@path = extract_path(path) if path
wiki_options = settings.wiki_options.merge({ :page_file_dir => @path })
wiki = Gollum::Wiki.new(settings.gollum_path, wiki_options)
@results = wiki.pages
@ref = wiki.ref
mustache :pages
end
get '/fileview' do
wiki = Gollum::Wiki.new(settings.gollum_path, settings.wiki_options)
@results = Gollum::FileView.new(wiki.pages).render_files
@ref = wiki.ref
mustache :file_view
end
get '/*' do
show_page_or_file(params[:splat].first)
end
not_found do
@error = "404 - Page Not Found"
@message = "The requested page could not be found."
mustache :error
end
error 401 do
@error = "401 - Not Authorized"
@message = "Please login before accessing this page."
mustache :error
end
def show_page_or_file(fullpath)
name = extract_name(fullpath)
path = extract_path(fullpath)
wiki = wiki_new
path = '/' if path.nil?
if page = wiki.paged(name, path, exact = true)
@page = page
@name = name
@content = page.formatted_data
# Extensions and layout data
@editable = true
@page_exists = !page.versions.empty?
@toc_content = wiki.universal_toc ? @page.toc_data : nil
@mathjax = wiki.mathjax
@h1_title = wiki.h1_title
@bar_side = wiki.bar_side
mustache :page
elsif file = wiki.file(fullpath)
content_type file.mime_type
file.raw_data
else
page_path = [path, name].compact.join('/')
redirect to("/create/#{clean_url(encodeURIComponent(page_path))}")
end
end
def update_wiki_page(wiki, page, content, commit, name = nil, format = nil)
return if !page ||
((!content || page.raw_data == content) && page.format == format)
name ||= page.name
format = (format || page.format).to_sym
content ||= page.raw_data
wiki.update_page(page, name, format, content.to_s, commit)
end
def commit_message
msg = { :message => params[:message] }
if session.include? :username
msg[:name] = session[:username]
msg[:email] = session[:email]
end
msg
end
end
end