Generic argument parsing and formatting
[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 ext_re = re.compile(r"\.([^\./]+)$")
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 cgi.escape(pathname, quote=True)
81
82 def permalink(s):
83     return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip())
84
85 # Split arg lists like "blah| blah blah| width=100 | align = center",
86 # return a list containing anonymous arguments and a map containing the named arguments
87 def parse_args(s):
88     args = []
89     kwargs = {} 
90     for arg in s.strip('<[{}]>').split('|'):
91         try:
92             key, val = arg.split('=', 1)
93             kwargs[key.strip()] = val.strip()
94         except ValueError:
95             args.append(arg.strip())
96     return (args, kwargs)
97
98 def url_args(kvargs):
99     argv = []
100     for k, v in kvargs.items():
101         argv.append(k + '=' + v)
102     if argv:
103         return '?' + '&amp;'.join(argv)
104     return ''
105
106 # Formatting stuff --------------------------------------------------
107 def emit_header(mime_type="text/html"):
108     print("Content-type: " + mime_type + "; charset=utf-8\n")
109
110 def send_guru(msg_text, msg_type):
111     if not msg_text: return
112     print('<pre id="guru" onclick="this.style.display = \'none\'" class="' + msg_type + '">')
113     if msg_type == 'error':
114         print('    Software Failure.  Press left mouse button to continue.\n')
115     print(msg_text)
116     if msg_type == 'error':
117         print '\n           Guru Meditation #DEADBEEF.ABADC0DE'
118     print('</pre><script language="JavaScript" type="text/javascript" src="%s" defer="defer"></script>' \
119         % relative_url('sys/GuruMeditation.js'))
120
121 def send_title(name, text="Limbo", msg_text=None, msg_type='error', writable=False):
122     global title_done
123     if title_done: return
124
125     # Head
126     emit_header()
127     print('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"')
128     print('  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">')
129     print('<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">')
130
131     print("<head><title>%s: %s</title>" % (site_name, text))
132     print(' <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />')
133     if not name:
134         print(' <meta name="robots" content="noindex,nofollow" />')
135
136     for meta in meta_urls:
137         http_equiv, content = meta
138         print(' <meta http-equiv="%s" content="%s" />' % (http_equiv, relative_url(content)))
139
140     for link in link_urls:
141         rel, href = link
142         print(' <link rel="%s" href="%s" />' % (rel, relative_url(href)))
143
144     if name and writable and privileged_url is not None:
145         print(' <link rel="alternate" type="application/x-wiki" title="Edit this page" href="%s" />' \
146             % (privileged_path() + '?edit=' + name))
147
148     if history_url is not None:
149         print(' <link rel="alternate" type="application/rss+xml" title="RSS" href="%s" />' \
150             % relative_url(history_url + '?a=rss'))
151
152     print('</head>')
153
154     # Body
155     if name and writable and privileged_url is not None:
156         print('<body ondblclick="location.href=\'' + privileged_path() + '?edit=' + name + '\'">')
157     else:
158         print('<body>')
159
160     title_done = True
161     send_guru(msg_text, msg_type)
162
163     # Navbar
164     print('<div class="nav">')
165     print link_tag('FrontPage', site_icon or 'Home', 'navlink')
166     if name:
167         print('  <b>' + link_tag('?fullsearch=' + name, text, 'navlink') + '</b> ')
168     else:
169         print('  <b>' + text + '</b> ')
170     print(' | ' + link_tag('FindPage', 'Find Page', 'navlink'))
171     if 'history_url' in globals():
172         print(' | <a href="' + relative_url(history_url) + '" class="navlink">Recent Changes</a>')
173         if name:
174             print(' | <a href="' + relative_url(history_url + '?a=history;f=' + name) + '" class="navlink">Page History</a>')
175
176     if name:
177         print(' | ' + link_tag('?raw=' + name, 'Raw Text', 'navlink'))
178         if privileged_url is not None:
179             if writable:
180                 print(' | ' + link_tag('?edit=' + name, 'Edit', 'navlink', privileged=True))
181             else:
182                 print(' | ' + link_tag(name, 'Login', 'navlink', privileged=True))
183
184     else:
185         print(' | <i>Immutable Page</i>')
186
187     user = remote_user()
188     if user != 'AnonymousCoward':
189         print(' | <span class="login"><i><b>' + link_tag('User/' + user, user) + '</b></i></span>')
190
191     print('<hr /></div>')
192
193 def send_httperror(status="403 Not Found", query=""):
194     print("Status: %s" % status)
195     send_title(None, msg_text=("%s: on query '%s'" % (status, query)))
196     send_footer()
197
198 def link_tag(params, text=None, link_class=None, privileged=False, **kvargs):
199     if text is None:
200         text = params # default
201     elif img_re.match(text):
202         text = '<img border="0" src="' + relative_url(text) + '" alt="' + text + '" />'
203
204     if not link_class:
205         if is_external_url(params):
206             link_class = 'external'
207         elif file_re.match(params) and Page(params).exists():
208             link_class = 'wikilink'
209         else:
210             params = nonexist_pfx + params
211             link_class = 'nonexistent'
212
213     classattr = 'class="%s" ' % link_class
214     # Prevent crawlers from following links potentially added by spammers or to generated pages
215     if link_class == 'external' or link_class == 'navlink':
216         classattr += 'rel="nofollow"'
217
218     return '<a %shref="%s">%s</a>' % (classattr, relative_url(params, privileged=privileged), text)
219
220 def link_inline(name, descr=None, kvargs={}):
221     if not descr: descr = name
222     url = relative_url(name)
223     if video_re.match(name):
224         return '<video src="%s">Your browser does not support the HTML5 video tag</video>' % url
225     elif img_re.match(name):
226         return '<a href="%s"><img border="0" src="%s" alt="%s" /></a>' % (url, url + url_args(kvargs), descr)
227     elif file_re.match(name) and not ext_re.search(name): # FIXME: this guesses a wiki page
228         return Page(name).send_naked()
229     else:
230         return '<iframe width="100%%" scrolling="auto" frameborder="0" src="%s"><a href="%s">%s</a></iframe>' \
231             % (url, url, name)
232
233 # Search ---------------------------------------------------
234
235 def handle_fullsearch(needle):
236     send_title(None, 'Full text search for "%s"' % (needle))
237
238     needle_re = re.compile(needle, re.IGNORECASE)
239     hits = []
240     all_pages = page_list()
241     for page_name in all_pages:
242         body = Page(page_name).get_raw_body()
243         count = len(needle_re.findall(body))
244         if count:
245             hits.append((count, page_name))
246
247     # The default comparison for tuples compares elements in order,
248     # so this sorts by number of hits
249     hits.sort()
250     hits.reverse()
251
252     print("<ul>")
253     for (count, page_name) in hits:
254         print('<li><p>' + link_tag(page_name))
255         print(' . . . . ' + `count`)
256         print(['match', 'matches'][count != 1])
257         print('</p></li>')
258     print("</ul>")
259
260     print_search_stats(len(hits), len(all_pages))
261
262 def handle_titlesearch(needle):
263     # TODO: check needle is legal -- but probably we can just accept any RE
264     send_title(None, "Title search for \"" + needle + '"')
265
266     needle_re = re.compile(needle, re.IGNORECASE)
267     all_pages = page_list()
268     hits = list(filter(needle_re.search, all_pages))
269
270     print("<ul>")
271     for filename in hits:
272         print('<li><p>' + link_tag(filename) + "</p></li>")
273     print("</ul>")
274
275     print_search_stats(len(hits), len(all_pages))
276
277 def print_search_stats(hits, searched):
278     print("<p>%d hits out of %d pages searched.</p>" % (hits, searched))
279
280 def handle_raw(pagename):
281     if not file_re.match(pagename):
282         send_httperror("403 Forbidden", pagename)
283         return
284
285     Page(pagename).send_raw()
286
287 def handle_edit(pagename):
288     if not file_re.match(pagename):
289         send_httperror("403 Forbidden", pagename)
290         return
291
292     pg = Page(pagename)
293     if 'save' in form:
294         if form['file'].value:
295             pg.save(form['file'].file.read(), form['changelog'].value)
296         else:
297             pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value)
298         pg.format()
299     elif 'cancel' in form:
300         pg.msg_text = 'Editing canceled'
301         pg.msg_type = 'notice'
302         pg.format()
303     else: # preview or edit
304         text = None
305         if 'preview' in form:
306             text = form['savetext'].value
307         pg.send_editor(text)
308
309 # Used by macros/WordIndex and macros/TitleIndex
310 def make_index_key():
311     links = ['<a href="#%s">%s</a>' % (ch, ch) for ch in 'abcdefghijklmnopqrstuvwxyz']
312     return '<p style="text-align: center">' + ' | '.join(links) + '</p>'
313
314 def page_list(dirname = None, re = word_re):
315     return sorted(filter(re.match, os.listdir(dirname or data_dir)))
316
317 def send_footer(mod_string=None):
318     if globals().get('debug_cgi', False):
319         cgi.print_arguments()
320         cgi.print_form(form)
321         cgi.print_environ()
322     print('''
323 <div id="footer"><hr />
324 <p class="copyright">
325 <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/"><img class="license" alt="Creative Commons License" src="%s" /></a>
326 <span class="benchmark">generated in %0.3fs</span> by <a href="http://www.codewiz.org/wiki/GeekiGeeki">GeekiGeeki</a> version %s
327 </p>
328 ''' % (relative_url('cc-by-sa.png'), clock() - start_time, __version__))
329     if mod_string:
330         print('<p class="modified">last modified %s</p>' % mod_string)
331     print('</div></body></html>')
332
333 class WikiFormatter:
334     """Object that turns Wiki markup into HTML.
335
336     All formatting commands can be parsed one line at a time, though
337     some state is carried over between lines.
338     """
339     def __init__(self, raw):
340         self.raw = raw
341         self.h_level = 0
342         self.in_pre = self.in_html = self.in_table = self.in_li = False
343         self.in_header = True
344         self.list_indents = []
345         self.tr_cnt = 0
346         self.styles = {
347             #wiki   html   enabled?
348             "//":  ["em",  False],
349             "**":  ["b",   False],
350             "##":  ["tt",  False],
351             "__":  ["u",   False],
352             "^^":  ["sup", False],
353             ",,":  ["sub", False],
354             "''":  ["em",  False], # LEGACY
355             "'''": ["b",   False], # LEGACY
356             "``":  ["tt",  False], # LEGACY
357         }
358
359     def _b_repl(self, word):
360         style = self.styles[word]
361         style[1] = not style[1]
362         return ['</', '<'][style[1]] + style[0] + '>'
363
364     def _tit_repl(self, word):
365         if self.h_level:
366             result = '</h%d><p>\n' % self.h_level
367             self.h_level = 0
368         else:
369             self.h_level = len(word) - 1
370             link = permalink(self.line)
371             result = '\n</p><h%d id="%s"><a class="heading" href="#%s">¶</a> ' % (self.h_level, link, link)
372         return result
373
374     def _br_repl(self, word):
375         return '<br />'
376
377     def _rule_repl(self, word):
378         return self._undent() + '\n<hr size="%d" noshade="noshade" />\n' % (len(word) - 2)
379
380     def _macro_repl(self, word):
381         try:
382             args, kwargs = parse_args(word)
383             macro = globals().get('_macro_' + args[0])
384             if not macro:
385                 exec(open("macros/" + name + ".py").read(), globals())
386                 macro = globals().get('_macro_' + name)
387             return macro(*args, **kwargs)
388         except Exception:
389             msg = cgi.escape(word)
390             if not self.in_html:
391                 msg = '<strong class="error">' + msg + '</strong>'
392             return msg
393
394     def _hurl_repl(self, word):
395         args, kvargs = parse_args(word)
396         return link_tag(*args, **kvargs)
397
398     def _inl_repl(self, word):
399         args, kvargs = parse_args(word)
400         name = args.pop(0)
401         if len(args):
402             descr = args.pop(0)
403             # The "extthumb" nonsense works around a limitation of the HTML block model
404             return '<div class="extthumb"><div class="thumb">' \
405                 + link_inline(name, descr, kvargs) \
406                 + '<div class="caption">' + descr + '</div></div></div>'
407         else:
408             return link_inline(name, None, kvargs)
409
410     def _html_repl(self, word):
411         if not self.in_html and word.startswith('<div'): word = '</p>' + word
412         self.in_html += 1
413         return word; # Pass through
414
415     def _htmle_repl(self, word):
416         self.in_html -= 1
417         if not self.in_html and word.startswith('</div'): word += '<p>'
418         return word; # Pass through
419
420     def _ent_repl(self, s):
421         if self.in_html:
422             return s; # Pass through
423         return {'&': '&amp;',
424                 '<': '&lt;',
425                 '>': '&gt;'}[s]
426
427     def _img_repl(self, word): # LEGACY
428         return self._inl_repl('{{' + word + '}}')
429
430     def _word_repl(self, word): # LEGACY
431         if self.in_html: return word # pass through
432         return link_tag(word)
433
434     def _url_repl(self, word): # LEGACY
435         if self.in_html: return word # pass through
436         return link_tag(word)
437
438     def _email_repl(self, word): # LEGACY
439         if self.in_html: return word # pass through
440         return '<a href="mailto:%s">%s</a>' % (word, word)
441
442     def _li_repl(self, match):
443         if self.in_li:
444             return '</li><li>'
445         else:
446             self.in_li = True
447             return '<li>'
448
449     def _pre_repl(self, word):
450         if word == '{{{' and not self.in_pre:
451             self.in_pre = True
452             return '<pre>'
453         elif self.in_pre:
454             self.in_pre = False
455             return '</pre>'
456         return ''
457
458     def _hi_repl(self, word):
459         return '<strong class="highlight ' + word + '">' + word + '</strong>'
460
461     def _tr_repl(self, word):
462         out = ''
463         if not self.in_table:
464             self.in_table = True
465             self.tr_cnt = 0
466             out = '</p><table><tbody>\n'
467         self.tr_cnt += 1
468         out = out + '<tr class="' + ['even', 'odd'][self.tr_cnt % 2] + '">'
469         return out + ['<td>', '<th>'][word.strip() == '||=']
470
471     def _td_repl(self, word):
472         if self.in_table:
473             return ['</td><td>', '</th><th>'][word.strip() == '||=']
474         return ''
475
476     def _tre_repl(self, word):
477         if self.in_table:
478             return ['</td></tr>', '</th></tr>'][word.strip() == '||=']
479         return ''
480
481     def _indent_level(self):
482         return len(self.list_indents) and self.list_indents[-1]
483
484     def _indent_to(self, new_level):
485         if self._indent_level() == new_level:
486             return ''
487         s = '</p>'
488         while self._indent_level() > new_level:
489             del(self.list_indents[-1])
490             if self.in_li:
491                 s += '</li>'
492                 self.in_li = False # FIXME
493             s += '</ul>\n'
494         while self._indent_level() < new_level:
495             self.list_indents.append(new_level)
496             s += '<ul>\n'
497         s += '<p>'
498         return s
499
500     def _undent(self):
501         res = '</p>'
502         res += '</ul>' * len(self.list_indents)
503         res += '<p>'
504         self.list_indents = []
505         return res
506
507     def replace(self, match):
508         for rule, hit in list(match.groupdict().items()):
509             if hit:
510                 return getattr(self, '_' + rule + '_repl')(hit)
511         else:
512             raise "Can't handle match " + repr(match)
513
514     def print_html(self):
515         print('<div class="wiki"><p>')
516
517         scan_re = re.compile(r"""(?:
518             # Styles and formatting
519               (?P<b>     \*\*|'''|//|''|\#\#|``|__|\^\^|,,)
520             | (?P<tit>   \={2,6})
521             | (?P<br>    \\\\)
522             | (?P<rule>  ^-{3,})
523             | (?P<hi>    \b( FIXME | TODO | DONE )\b )
524
525             # Links
526             | (?P<macro> \<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)
527             | (?P<hurl>  \[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])
528
529             # Inline HTML
530             | (?P<html>  <(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])\b )
531             | (?P<htmle> ( /\s*> | </(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])> ) )
532             | (?P<ent>   [<>&] )
533
534             # Auto links (LEGACY)
535             | (?P<img>   \b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp|ico|ogm|ogg|mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt))
536             | (?P<word>  \b(?:[A-Z][a-z]+){2,}\b)
537             | (?P<url>   (http|https|ftp|mailto)\:[^\s'\"]+\S)
538             | (?P<email> [-\w._+]+\@[\w.-]+)
539
540             # Lists, divs, spans
541             | (?P<li>    ^\s+[\*\#]\s+)
542             | (?P<pre>   \{\{\{|\s*\}\}\})
543             | (?P<inl>   \{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})
544
545             # Tables
546             | (?P<tr>    ^\s*\|\|(=|)\s*)
547             | (?P<tre>   \s*\|\|(=|)\s*$)
548             | (?P<td>    \s*\|\|(=|)\s*)
549
550             # TODO: highlight search words (look at referrer)
551           )""", re.VERBOSE)
552         pre_re = re.compile("""(?:
553               (?P<pre>\s*\}\}\})
554             | (?P<ent>[<>&])"
555             )""", re.VERBOSE)
556         blank_re = re.compile(r"^\s*$")
557         indent_re = re.compile(r"^\s*")
558         tr_re = re.compile(r"^\s*\|\|")
559         eol_re = re.compile(r"\r?\n")
560         # For each line, we scan through looking for magic strings, outputting verbatim any intervening text
561         #3.0: for self.line in eol_re.split(str(self.raw.expandtabs(), 'utf-8')):
562         for self.line in eol_re.split(str(self.raw.expandtabs())):
563             # Skip pragmas
564             if self.in_header:
565                 if self.line.startswith('#'):
566                     continue
567                 self.in_header = False
568
569             if self.in_pre:
570                 print(re.sub(pre_re, self.replace, self.line))
571             else:
572                 if self.in_table and not tr_re.match(self.line):
573                     self.in_table = False
574                     print('</tbody></table><p>')
575
576                 if blank_re.match(self.line):
577                     print('</p><p>')
578                 else:
579                     indent = indent_re.match(self.line)
580                     #3.0: print(self._indent_to(len(indent.group(0))), end=' ')
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('/','_') + '.' + str(os.getpid()) + '#'))
604
605     def exists(self):
606         try:
607             os.stat(self._filename())
608             return True
609         except OSError as 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 as err:
618             if err.errno == errno.ENOENT:
619                 if default is None:
620                     default = '//[[%s|Describe %s|action=edit]]//' % (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                 file = open(self._filename(), 'rt')
648                 attr_re = re.compile(r"^#(\S*)(.*)$")
649                 for line in file:
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 as err:
656                 if err.errno != errno.ENOENT and err.errno != errno.EISDIR:
657                     raise er
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 as 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 as 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     exec(open("geekigeeki.conf.py").read())
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()