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