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