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