f3ce1dcb3268d452e29c997c5a698040a15b58cf
[geekigeeki.git] / geekigeeki.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 1999, 2000 Martin Pool <mbp@humbug.org.au>
5 # Copyright 2002 Gerardo Poggiali
6 # Copyright 2007, 2008, 2009 Bernie Innocenti <bernie@codewiz.org>
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21 __version__ = '$Id$'[4:12]
22
23 from time import clock
24 start_time = clock()
25
26 import cgi, sys, os, re, errno, stat
27
28 # Regular expression defining a WikiWord
29 # (but this definition is also assumed in other places)
30 word_re = re.compile(r"^\b((([A-Z][a-z0-9]+){2,}/)*([A-Z][a-z0-9]+){2,})\b$")
31 # FIXME: we accept stuff like foo/../bar and we shouldn't
32 file_re = re.compile(r"^\b([A-Za-z0-9_\-][A-Za-z0-9_\.\-/]*)\b$")
33 img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg|bmp|ico|ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt)$", re.IGNORECASE)
34 video_re = re.compile(r"^.*\.(ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt)$", re.IGNORECASE)
35 url_re = re.compile(r"^[a-z]{3,8}://[^\s'\"]+\S$")
36 link_re = re.compile("(?:\[\[|{{)([^\s\|]+)(?:\s*\|\s*([^\]]+)|)(?:\]\]|}})")
37
38 title_done = False
39
40 # CGI stuff ---------------------------------------------------------
41 def script_name():
42     return os.environ.get('SCRIPT_NAME', '')
43
44 def query_string():
45     path_info = os.environ.get('PATH_INFO', '')
46     if len(path_info) and path_info[0] == '/':
47         return path_info[1:] or 'FrontPage'
48     else:
49         return os.environ.get('QUERY_STRING', '') or 'FrontPage'
50
51 def privileged_path():
52     return privileged_url or script_name()
53
54 def remote_user():
55     user = os.environ.get('REMOTE_USER', '')
56     if user is None or user == '' or user == 'anonymous':
57         user = 'AnonymousCoward'
58     return user
59
60 def remote_host():
61     return os.environ.get('REMOTE_ADDR', '')
62
63 def get_hostname(addr):
64     try:
65         from socket import gethostbyaddr
66         return gethostbyaddr(addr)[0] + ' (' + addr + ')'
67     except Exception:
68         return addr
69
70 def is_external_url(pathname):
71     return (url_re.match(pathname) or pathname.startswith('/'))
72
73 def relative_url(pathname, privileged=False):
74     if not is_external_url(pathname):
75         if privileged:
76             url = privileged_path()
77         else:
78             url = script_name()
79         pathname = url + '/' + pathname
80     return pathname
81
82 def permalink(s):
83     return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip())
84
85 # Formatting stuff --------------------------------------------------
86 def emit_header(mime_type="text/html"):
87     print "Content-type: " + mime_type + "; charset=utf-8\n"
88
89 def sendfile(dest_file, src_file):
90     """Efficiently copy file data between file descriptors"""
91     while 1:
92         data = src_file.read(65536)
93         if not data: break
94         dest_file.write(data)
95
96 def send_guru(msg_text, msg_type):
97     if not msg_text: return
98     print '<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">'
99     if msg_type == 'error':
100         print '    Software Failure.  Press left mouse button to continue.\n'
101     print msg_text
102     if msg_type == 'error':
103         print '\n      Guru Meditation #DEADBEEF.ABADC0DE'
104     print '</pre>'
105     try:
106         sendfile(sys.stdout, open('gurumeditation.js', 'rb'))
107     except IOError, err:
108         pass
109
110 def send_title(name, text="Limbo", msg_text=None, msg_type='error', writable=False):
111     global title_done
112     if title_done: return
113
114     # Head
115     emit_header()
116     print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
117     print '  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
118     print '<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">'
119
120     print "<head><title>%s: %s</title>" % (site_name, text)
121     print ' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />'
122     if not name:
123         print ' <meta name="robots" content="noindex,nofollow" />'
124
125     for meta in meta_urls:
126         http_equiv, content = meta
127         print ' <meta http-equiv="%s" content="%s" />' % (http_equiv, relative_url(content))
128
129     for link in link_urls:
130         rel, href = link
131         print ' <link rel="%s" href="%s" />' % (rel, relative_url(href))
132
133     if name and writable and privileged_url is not None:
134         print ' <link rel="alternate" type="application/x-wiki" title="Edit this page" href="%s" />' \
135             % (privileged_path() + '?edit=' + name)
136
137     if history_url is not None:
138         print ' <link rel="alternate" type="application/rss+xml" title="RSS" href="%s" />' \
139             % relative_url(history_url + '?a=rss')
140
141     print '</head>'
142
143     # Body
144     if name and writable and privileged_url is not None:
145         print '<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">'
146     else:
147         print '<body>'
148
149     title_done = True
150     send_guru(msg_text, msg_type)
151
152     # Navbar
153     print '<div class="nav">'
154     print link_tag('FrontPage', relative_url(site_icon or 'Home'), 'navlink')
155     if name:
156         print '  <b>' + link_tag('?fullsearch=' + name, text, 'navlink') + '</b> '
157     else:
158         print '  <b>' + text + '</b> '
159     print ' | ' + link_tag('FindPage', 'Find Page', 'navlink')
160     if 'history_url' in globals():
161         print ' | <a href="' + relative_url(history_url) + '" class="navlink">Recent Changes</a>'
162         if name:
163             print ' | <a href="' + relative_url(history_url + '?a=history;f=' + name) + '" class="navlink">Page History</a>'
164
165     if name:
166         print ' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink')
167         if privileged_url is not None:
168             if writable:
169                 print ' | ' + link_tag('?edit=' + name, 'Edit', 'navlink', privileged=True)
170             else:
171                 print ' | ' + link_tag(name, 'Login', 'navlink', privileged=True)
172
173     else:
174         print ' | <i>Immutable Page</i>'
175
176     user = remote_user()
177     if user != 'AnonymousCoward':
178         print ' | <span class="login"><i><b>' + link_tag('User/' + user, user) + '</b></i></span>'
179
180     print '<hr /></div>'
181
182 def send_httperror(status="403 Not Found", query=""):
183     print "Status: %s" % status
184     send_title(None, msg_text=("%s: on query '%s'" % (status, query)))
185     send_footer()
186
187 def link_tag(params, text=None, link_class=None, privileged=False):
188     if text is None:
189         text = params # default
190     elif img_re.match(text):
191         text = '<img border="0" src="' + text + '" />'
192
193     if not link_class:
194         if is_external_url(params):
195             link_class = 'external'
196         elif file_re.match(params) and Page(params).exists():
197             link_class = 'wikilink'
198         else:
199             params = nonexist_pfx + params
200             link_class = 'nonexistent'
201
202     classattr = 'class="%s" ' % link_class
203     # Prevent crawlers from following links potentially added by spammers or to generated pages
204     if link_class == 'external' or link_class == 'navlink':
205         classattr += 'rel="nofollow"'
206
207     return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
208
209 def link_inline(name, descr=None, args=''):
210     if not descr: descr = name
211     if video_re.match(name):
212         return '<video src="%s">Your browser does not support the HTML5 video tag</video>' % name
213     else:
214         return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (name, name + args, descr)
215
216 # Search ---------------------------------------------------
217
218 def handle_fullsearch(needle):
219     send_title(None, 'Full text search for "%s"' % (needle))
220
221     needle_re = re.compile(needle, re.IGNORECASE)
222     hits = []
223     all_pages = page_list()
224     for page_name in all_pages:
225         body = Page(page_name).get_raw_body()
226         count = len(needle_re.findall(body))
227         if count:
228             hits.append((count, page_name))
229
230     # The default comparison for tuples compares elements in order,
231     # so this sorts by number of hits
232     hits.sort()
233     hits.reverse()
234
235     print "<ul>"
236     for (count, page_name) in hits:
237         print '<li><p>' + link_tag(page_name)
238         print ' . . . . ' + `count`
239         print ['match', 'matches'][count != 1]
240         print '</p></li>'
241     print "</ul>"
242
243     print_search_stats(len(hits), len(all_pages))
244
245 def handle_titlesearch(needle):
246     # TODO: check needle is legal -- but probably we can just accept any RE
247     send_title(None, "Title search for \"" + needle + '"')
248
249     needle_re = re.compile(needle, re.IGNORECASE)
250     all_pages = page_list()
251     hits = filter(needle_re.search, all_pages)
252
253     print "<ul>"
254     for filename in hits:
255         print '<li><p>' + link_tag(filename) + "</p></li>"
256     print "</ul>"
257
258     print_search_stats(len(hits), len(all_pages))
259
260 def print_search_stats(hits, searched):
261     print "<p>%d hits out of %d pages searched.</p>" % (hits, searched)
262
263 def handle_raw(pagename):
264     if not file_re.match(pagename):
265         send_httperror("403 Forbidden", pagename)
266         return
267
268     Page(pagename).send_raw()
269
270 def handle_edit(pagename):
271     if not file_re.match(pagename):
272         send_httperror("403 Forbidden", pagename)
273         return
274
275     pg = Page(pagename)
276     if 'save' in form:
277         if form['file'].value:
278             pg.save(form['file'].file.read(), form['changelog'].value)
279         else:
280             pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value)
281         pg.format()
282     elif 'cancel' in form:
283         pg.msg_text = 'Editing canceled'
284         pg.msg_type = 'notice'
285         pg.format()
286     else: # preview or edit
287         text = None
288         if 'preview' in form:
289             text = form['savetext'].value
290         pg.send_editor(text)
291
292 def make_index_key():
293     links = map(lambda ch: '<a href="#%s">%s</a>' % (ch, ch), 'abcdefghijklmnopqrstuvwxyz')
294     return '<p><center>'+ ' | '.join(links) + '</center></p>'
295
296 def page_list(dirname = None, re = word_re):
297     return sorted(filter(re.match, os.listdir(dirname or data_dir)))
298
299 def send_footer(mod_string=None):
300     if globals().get('debug_cgi', False):
301         cgi.print_arguments()
302         cgi.print_form(form)
303         cgi.print_environ()
304     print '''
305 <div id="footer"><hr />
306 <p class="copyright">
307 <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img class="license" alt="Creative Commons License" src="%s" /></a>
308 <span class="benchmark">generated in %0.3fs</span> by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a> version %s
309 </p>
310 ''' % (relative_url('cc-by-sa.png'), clock() - start_time, __version__)
311     if mod_string:
312         print '<p class="modified">last modified %s</p>' % mod_string
313     print '</div></body></html>'
314
315 class WikiFormatter:
316     """Object that turns Wiki markup into HTML.
317
318     All formatting commands can be parsed one line at a time, though
319     some state is carried over between lines.
320     """
321     def __init__(self, raw):
322         self.raw = raw
323         self.h_level = 0
324         self.in_pre = self.in_html = self.in_table = self.in_li = False
325         self.in_header = True
326         self.list_indents = []
327         self.tr_cnt = 0
328         self.styles = {
329             #wiki   html   enabled?
330             "//":  ["em",  False],
331             "**":  ["b",   False],
332             "##":  ["tt",  False],
333             "__":  ["u",   False],
334             "^^":  ["sup", False],
335             ",,":  ["sub", False],
336             "''":  ["em",  False], # LEGACY
337             "'''": ["b",   False], # LEGACY
338             "``":  ["tt",  False], # LEGACY
339         }
340
341     def _b_repl(self, word):
342         style = self.styles[word]
343         style[1] = not style[1]
344         return ['</', '<'][style[1]] + style[0] + '>'
345
346     def _tit_repl(self, word):
347         if self.h_level:
348             result = '</h%d><p>\n' % self.h_level
349             self.h_level = 0
350         else:
351             self.h_level = len(word) - 1
352             link = permalink(self.line)
353             result = '\n</p><h%d id="%s"><a class="heading" href="#%s">¶</a> ' % (self.h_level, link, link)
354         return result
355
356     def _br_repl(self, word):
357         return '<br />'
358
359     def _rule_repl(self, word):
360         return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
361
362     def _macro_repl(self, word):
363         m = re.compile("\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>").match(word)
364         name = m.group(1)
365         argv = [name]
366         if m.group(2):
367             argv.extend(m.group(2).split('|'))
368         argv = map(str.strip, argv)
369
370         macro = globals().get('_macro_' + name)
371         if not macro:
372             try:
373                 execfile("macros/" + name + ".py", globals())
374             except IOError, err:
375                 if err.errno == errno.ENOENT: pass
376             macro = globals().get('_macro_' + name)
377         if macro:
378             return macro(argv)
379         else:
380             msg = '&lt;&lt;' + '|'.join(argv) + '&gt;&gt;'
381             if not self.in_html:
382                 msg = '<strong class="error">' + msg + '</strong>'
383             return msg
384
385     def _hurl_repl(self, word):
386         m = link_re.match(word)
387         return link_tag(m.group(1), m.group(2))
388
389     def _inl_repl(self, word):
390         m = link_re.match(word)
391         name = relative_url(m.group(1))
392         descr = m.group(2)
393
394         if descr:
395             argv = descr.split('|')
396             descr = argv.pop(0)
397             args = ''
398             if argv:
399                 args = '?' + '&amp;'.join(argv)
400
401             # The "extthumb" nonsense works around a limitation of the HTML block model
402             return '<div class="extthumb"><div class="thumb">' \
403                 + link_inline(name, descr, args) \
404                 + '<div class="caption">' + descr + '</div></div></div>'
405         else:
406             return link_inline(name, name)
407
408     def _html_repl(self, word):
409         self.in_html += 1
410         return word; # Pass through
411
412     def _htmle_repl(self, word):
413         self.in_html -= 1
414         return word; # Pass through
415
416     def _ent_repl(self, s):
417         if self.in_html:
418             return s; # Pass through
419         return {'&': '&amp;',
420                 '<': '&lt;',
421                 '>': '&gt;'}[s]
422
423     def _img_repl(self, word): # LEGACY
424         return self._inl_repl('{{' + word + '}}')
425
426     def _word_repl(self, word): # LEGACY
427         if self.in_html: return word # pass through
428         return link_tag(word)
429
430     def _url_repl(self, word): # LEGACY
431         if self.in_html: return word # pass through
432         return link_tag(word)
433
434     def _email_repl(self, word): # LEGACY
435         if self.in_html: return word # pass through
436         return '<a href="mailto:%s">%s</a>' % (word, word)
437
438     def _li_repl(self, match):
439         if self.in_li:
440             return '</li><li>'
441         else:
442             self.in_li = True
443             return '<li>'
444
445     def _pre_repl(self, word):
446         if word == '{{{' and not self.in_pre:
447             self.in_pre = True
448             return '<pre>'
449         elif self.in_pre:
450             self.in_pre = False
451             return '</pre>'
452         return ''
453
454     def _hi_repl(self, word):
455         return '<strong class="highlight ' + word + '">' + word + '</strong>'
456
457     def _tr_repl(self, word):
458         out = ''
459         if not self.in_table:
460             self.in_table = True
461             self.tr_cnt = 0
462             out = '</p><table><tbody>\n'
463         self.tr_cnt += 1
464         out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
465         return out + ['<td>', '<th>'][word.strip() == '||=']
466
467     def _td_repl(self, word):
468         if self.in_table:
469             return ['</td><td>', '</th><th>'][word.strip() == '||=']
470         return ''
471
472     def _tre_repl(self, word):
473         if self.in_table:
474             return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
475         return ''
476
477     def _indent_level(self):
478         return len(self.list_indents) and self.list_indents[-1]
479
480     def _indent_to(self, new_level):
481         if self._indent_level() == new_level:
482             return ''
483         s = '</p>'
484         while self._indent_level() > new_level:
485             del(self.list_indents[-1])
486             if self.in_li:
487                 s += '</li>'
488                 self.in_li = False # FIXME
489             s += '</ul>\n'
490         while self._indent_level() < new_level:
491             self.list_indents.append(new_level)
492             s += '<ul>\n'
493         s += '<p>'
494         return s
495
496     def _undent(self):
497         res = '</p>'
498         res += '</ul>' * len(self.list_indents)
499         res += '<p>'
500         self.list_indents = []
501         return res
502
503     def replace(self, match):
504         for rule, hit in match.groupdict().items():
505             if hit:
506                 return getattr(self, '_' + rule + '_repl')(hit)
507         else:
508             raise "Can't handle match " + repr(match)
509
510     def print_html(self):
511         print '<div class="wiki"><p>'
512
513         scan_re = re.compile(r"""(?:
514             # Styles and formatting
515               (?P<b>     \*\*|'''|//|''|\#\#|``|__|\^\^|,,)
516             | (?P<tit>   \={2,6})
517             | (?P<br>    \\\\)
518             | (?P<rule>  ^-{3,})
519             | (?P<hi>    \b( FIXME | TODO | DONE )\b )
520
521             # Links
522             | (?P<macro> \<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)
523             | (?P<hurl>  \[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])
524
525             # Inline HTML
526             | (?P<html>  <(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])\b )
527             | (?P<htmle> ( /\s*> | </(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])> ) )
528             | (?P<ent>   [<>&] )
529
530             # Auto links (LEGACY)
531             | (?P<img>   \b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp|ico|ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt))
532             | (?P<word>  \b(?:[A-Z][a-z]+){2,}\b)
533             | (?P<url>   (http|https|ftp|mailto)\:[^\s'\"]+\S)
534             | (?P<email> [-\w._+]+\@[\w.-]+)
535
536             # Lists, divs, spans
537             | (?P<li>    ^\s+[\*\#]\s+)
538             | (?P<pre>   \{\{\{|\s*\}\}\})
539             | (?P<inl>   \{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})
540
541             # Tables
542             | (?P<tr>    ^\s*\|\|(=|)\s*)
543             | (?P<tre>   \s*\|\|(=|)\s*$)
544             | (?P<td>    \s*\|\|(=|)\s*)
545
546             # TODO: highlight search words (look at referrer)
547           )""", re.VERBOSE)
548         pre_re = re.compile("""(?:
549               (?P<pre>\s*\}\}\})
550             | (?P<ent>[<>&])"
551             )""", re.VERBOSE)
552         blank_re = re.compile(r"^\s*$")
553         indent_re = re.compile(r"^\s*")
554         tr_re = re.compile(r"^\s*\|\|")
555         eol_re = re.compile(r"\r?\n")
556
557         # For each line, we scan through looking for magic strings, outputting verbatim any intervening text
558         for self.line in eol_re.split(self.raw.expandtabs()):
559             # Skip pragmas
560             if self.in_header:
561                 if self.line.startswith('#'):
562                     continue
563                 self.in_header = False
564
565             if self.in_pre:
566                 print re.sub(pre_re, self.replace, self.line)
567             else:
568                 if self.in_table and not tr_re.match(self.line):
569                     self.in_table = False
570                     print '</tbody></table><p>'
571
572                 if blank_re.match(self.line):
573                     print '</p><p>'
574                 else:
575                     indent = indent_re.match(self.line)
576                     print self._indent_to(len(indent.group(0))) ,
577                     print re.sub(scan_re, self.replace, self.line)
578
579         if self.in_pre: print '</pre>'
580         if self.in_table: print '</tbody></table><p>'
581         print self._undent()
582         print '</p></div>'
583
584 class Page:
585     def __init__(self, page_name):
586         self.page_name = page_name
587         self.msg_text = ''
588         self.msg_type = 'error'
589
590     def split_title(self):
591         # look for the end of words and the start of a new word and insert a space there
592         return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name)
593
594     def _filename(self):
595         return os.path.join(data_dir, self.page_name)
596
597     def _tmp_filename(self):
598         return os.path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + `os.getpid()` + '#'))
599
600     def exists(self):
601         try:
602             os.stat(self._filename())
603             return True
604         except OSError, err:
605             if err.errno == errno.ENOENT:
606                 return False
607             raise err
608
609     def get_raw_body(self):
610         try:
611             return open(self._filename(), 'rb').read()
612         except IOError, err:
613             if err.errno == errno.ENOENT:
614                 return '' # just doesn't exist, use default
615             if err.errno == errno.EISDIR:
616                 return self.format_dir()
617             raise err
618
619     def format_dir(self):
620         out = '== '
621         pathname = ''
622         for dirname in self.page_name.split('/'):
623             pathname = (pathname + '/' + dirname) if pathname else dirname
624             out += '[[' + pathname + '|' + dirname + ']]/'
625         out += ' ==\n'
626  
627         for filename in page_list(self._filename(), file_re):
628             if img_re.match(filename):
629                 if image_maxwidth:
630                     maxwidth_arg = '|maxwidth=' + str(image_maxwidth)
631                 out += '{{' + self.page_name + '/' + filename + '|' + filename + maxwidth_arg + '}}\n'
632             else:
633                 out += ' * [[' + self.page_name + '/' + filename + ']]\n'
634         return out
635
636     def pragmas(self):
637         if not '_pragmas' in self.__dict__:
638             self._pragmas = {}
639             try:
640                 f = open(self._filename(), 'rt')
641                 attr_re = re.compile(r"^#(\S*)(.*)$")
642                 for line in f:
643                     m = attr_re.match(line)
644                     if not m:
645                         break
646                     self._pragmas[m.group(1)] = m.group(2).strip()
647                     #print "bernie: _pragmas[" + m.group(1) + "] = " + m.group(2) + "<br>\n"
648             except IOError, err:
649                 if err.errno != errno.ENOENT and err.errno != errno.EISDIR:
650                     raise err
651         return self._pragmas
652
653     def pragma(self, name, default):
654         return self.pragmas().get(name, default)
655
656     def can(self, action, default=True):
657         acl = None
658         try:
659             #acl SomeUser:read,write All:read
660             acl = self.pragma("acl", None)
661             for rule in acl.split():
662                 (user, perms) = rule.split(':')
663                 if user == remote_user() or user == "All":
664                     return action in perms.split(',')
665             return False
666         except Exception:
667             if acl:
668                 self.msg_text = 'Illegal acl line: ' + acl
669         return default
670
671     def can_write(self):
672         return self.can("write", True)
673
674     def can_read(self):
675         return self.can("read", True)
676
677     def send_naked(self):
678         if self.can_read():
679             WikiFormatter(self.get_raw_body()).print_html()
680         else:
681             send_guru("Read access denied by ACLs", "notice")
682
683     def format(self):
684         #css foo.css
685         value = self.pragma("css", None)
686         if value:
687             global link_urls
688             link_urls += [ [ "stylesheet", value ] ]
689
690         send_title(self.page_name, self.split_title(),
691             msg_text=self.msg_text, msg_type=self.msg_type, writable=self.can_write())
692         self.send_naked()
693         send_footer(self._last_modified())
694
695     def _last_modified(self):
696         try:
697             from time import localtime, strftime
698             modtime = localtime(os.stat(self._filename())[stat.ST_MTIME])
699         except OSError, err:
700             if err.errno != errno.ENOENT:
701                 raise err
702             return None
703         return strftime(datetime_fmt, modtime)
704
705     def send_editor(self, preview=None):
706         send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type)
707         if not self.can_write():
708             send_guru("Write access denied by ACLs", "error")
709             return
710
711         filename = ''
712         if 'file' in form:
713             filename = form['file'].value
714
715         print ('<p><b>Editing ' + self.page_name
716             + ' for ' + cgi.escape(remote_user())
717             + ' from ' + cgi.escape(get_hostname(remote_host()))
718             + '</b></p>')
719         print '<div class="editor"><form name="editform" method="post" enctype="multipart/form-data" action="%s">' % relative_url(self.page_name)
720         print '<input type="hidden" name="edit" value="%s">' % (self.page_name)
721         print '<input type="input" id="editor" name="changelog" value="Edit page %s" accesskey="c" /><br />' % (self.page_name)
722         print '<textarea wrap="off" spellcheck="true" id="editor" name="savetext" rows="17" cols="100" accesskey="e">%s</textarea>' % cgi.escape(preview or self.get_raw_body())
723         print '<label for="file" accesskey="u">Or Upload a file:</label> <input type="file" name="file" value="%s" />' % filename
724         print """
725             <br />
726             <input type="submit" name="save" value="Save" accesskey="s">
727             <input type="submit" name="preview" value="Preview" accesskey="p" />
728             <input type="reset" value="Reset" />
729             <input type="submit" name="cancel" value="Cancel" />
730             <br />
731             </form></div>
732             <script language="javascript">
733             <!--
734             document.editform.savetext.focus()
735             //-->
736             </script>
737             """
738         print "<p>" + link_tag('EditingTips') + "</p>"
739         if preview:
740             print "<div class='preview'>"
741             WikiFormatter(preview).print_html()
742             print "</div>"
743         send_footer()
744
745     def send_raw(self, mimetype='text/plain'):
746         if self.can_read():
747             body = self.get_raw_body()
748             emit_header(mimetype)
749             print body
750         else:
751             send_title(None, msg_text='Read access denied by ACLs', msg_type='notice')
752
753     def send_image(self, mimetype, args=[]):
754         if 'maxwidth' in args:
755             import subprocess
756             emit_header(mimetype)
757             sys.stdout.flush()
758             subprocess.check_call(['gm', 'convert', self._filename(),
759                 '-scale', args['maxwidth'].value + ' >', '-'])
760         else:
761             self.send_raw(mimetype)
762
763     def _write_file(self, data):
764         tmp_filename = self._tmp_filename()
765         open(tmp_filename, 'wb').write(data)
766         name = self._filename()
767         if os.name == 'nt':
768             # Bad Bill!  POSIX rename ought to replace. :-(
769             try:
770                 os.remove(name)
771             except OSError, err:
772                 if err.errno != errno.ENOENT: raise err
773         os.rename(tmp_filename, name)
774
775     def save(self, newdata, changelog):
776         if not self.can_write():
777             self.msg_text = 'Write access denied by ACLs'
778             self.msg_type = 'error'
779             return
780
781         self._write_file(newdata)
782         rc = 0
783         if post_edit_hook:
784             # FIXME: what's the std way to perform shell quoting in python?
785             cmd = ( post_edit_hook
786                 + " '" + data_dir + '/' + self.page_name
787                 + "' '" + remote_user()
788                 + "' '" + remote_host()
789                 + "' '" + changelog + "'"
790             )
791             out = os.popen(cmd)
792             output = out.read()
793             rc = out.close()
794         if rc:
795             self.msg_text += "Post-editing hook returned %d.\n" % rc
796             self.msg_text += 'Command was: ' + cmd + '\n'
797             if output:
798                 self.msg_text += 'Output follows:\n' + output
799         else:
800             self.msg_text = 'Thank you for your contribution.  Your attention to detail is appreciated.'
801             self.msg_type = 'success'
802
803 def main():
804     for cmd in form:
805         handler = globals().get('handle_' + cmd)
806         if handler:
807             handler(form[cmd].value)
808             break
809     else:
810         query = query_string()
811         if file_re.match(query):
812             if word_re.match(query):
813                 Page(query).format()
814             else:
815                 from mimetypes import MimeTypes
816                 mimetype, encoding = MimeTypes().guess_type(query)
817                 if mimetype:
818                     if mimetype.startswith('image/'):
819                         Page(query).send_image(mimetype=mimetype, args=form)
820                     else:
821                         Page(query).send_raw(mimetype=mimetype)
822                 else:
823                     Page(query).format()
824         else:
825             send_httperror("403 Forbidden", query)
826
827 try:
828     execfile("geekigeeki.conf.py")
829     form = cgi.FieldStorage()
830     main()
831 except Exception:
832     import traceback
833     msg_text = traceback.format_exc()
834     if title_done:
835         send_guru(msg_text, "error")
836     else:
837         send_title(None, msg_text=msg_text)
838     send_footer()
839
840 sys.stdout.flush()