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