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