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