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