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