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