X-Git-Url: https://codewiz.org/gitweb?a=blobdiff_plain;f=geekigeeki.py;h=8de46ab91cbf4d2b14e4ce25753a0848545c311c;hb=fbc4d6639e75dd726fdcadc1129ae0900468e9d2;hp=abaa4338ee109158cc2fd4f90009423fe990e4f2;hpb=1ef0274d5e544e83d31eb4b17d1bb517fdcb1c60;p=geekigeeki.git diff --git a/geekigeeki.py b/geekigeeki.py index abaa433..8de46ab 100755 --- a/geekigeeki.py +++ b/geekigeeki.py @@ -1,8 +1,9 @@ -#! /usr/bin/env python +#!/usr/bin/python +# -*- coding: utf-8 -*- # # Copyright 1999, 2000 Martin Pool # Copyright 2002 Gerardo Poggiali -# Copyright 2007 Bernardo Innocenti +# Copyright 2007, 2008 Bernie Innocenti # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -22,15 +23,17 @@ __version__ = '$Id$'[4:12] from time import clock start_time = clock() -import cgi, sys, string, os, re, errno, stat +import cgi, sys, os, re, errno, stat from os import path, environ # Regular expression defining a WikiWord # (but this definition is also assumed in other places) -file_re = re.compile(r"^\b([A-Za-z0-9_\.\-]+)\b$") -word_re = re.compile(r"^\b([A-Z][a-z]+){2,}\b$") -img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg)$", re.IGNORECASE) +word_re = re.compile(r"^\b((([A-Z][a-z0-9]+){2,}/)*([A-Z][a-z0-9]+){2,})\b$") +# FIXME: we accept stuff like foo/../bar and we shouldn't +file_re = re.compile(r"^\b([A-Za-z0-9_\-][A-Za-z0-9_\.\-/]*)\b$") +img_re = re.compile(r"^.*\.(png|gif|jpg|jpeg|bmp|ico)$", re.IGNORECASE) url_re = re.compile(r"^[a-z]{3,8}://[^\s'\"]+\S$") +link_re = re.compile("(?:\[\[|{{)([^\s\|]+)(?:\s*\|\s*([^\]]+)|)(?:\]\]|}})") title_done = False @@ -56,25 +59,35 @@ def get_hostname(addr): try: from socket import gethostbyaddr return gethostbyaddr(addr)[0] + ' (' + addr + ')' - except: + except Exception, er: return addr -# Formatting stuff -------------------------------------------------- +def relative_url(pathname, privileged=False): + if not (url_re.match(pathname) or pathname.startswith('/')): + if privileged: + url = privileged_path() + else: + url = script_name() + pathname = url + '/' + pathname + return pathname -def emit_header(type="text/html"): - print "Content-type: " + type + "; charset=utf-8" - print +def permalink(s): + return re.sub(' ', '-', re.sub('[^a-z0-9_ ]', '', s.lower()).strip()) -def send_guru(msg, msg_type): - if msg is None or msg == '': return +# Formatting stuff -------------------------------------------------- +def emit_header(mime_type="text/html"): + print "Content-type: " + mime_type + "; charset=utf-8\n" + +def send_guru(msg_text, msg_type): + if not msg_text: return print '
'
     if msg_type == 'error':
         print '    Software Failure.  Press left mouse button to continue.\n'
-    print msg
+    print msg_text
     if msg_type == 'error':
         print '      Guru Meditation #DEADBEEF.ABADC0DE'
     print '
' - # FIXME: This simple JS snippet is harder to pass than ACID 3.0 + # FIXME: This little JS snippet is harder to pass than ACID 3.0 print """ """ -def send_title(name, text="Limbo", msg=None, msg_type='error'): +def send_title(name, text="Limbo", msg_text=None, msg_type='error', writable=False): global title_done if title_done: return @@ -112,37 +125,51 @@ def send_title(name, text="Limbo", msg=None, msg_type='error'): print ' ' if not name: print ' ' - if globals().has_key('css_url'): - print ' ' % css_url + + for link in link_urls: + rel, href = link + print ' ' % (rel, relative_url(href)) + + if name and writable and privileged_url is not None: + print ' ' \ + % (privileged_path() + '?edit=' + name) + + if history_url is not None: + print ' ' \ + % relative_url(history_url + '?a=rss') + print '' # Body - if name and privileged_url is not None: + if name and writable and privileged_url is not None: print '' else: print '' title_done = True - send_guru(msg, msg_type) + send_guru(msg_text, msg_type) # Navbar print '' -def link_tag(params, text=None, ss_class=None, authentication=False): +def link_tag(params, text=None, ss_class=None, privileged=False): if text is None: text = params # default classattr = '' @@ -161,15 +188,13 @@ def link_tag(params, text=None, ss_class=None, authentication=False): # Prevent crawlers from following links potentially added by spammers or to generated pages if ss_class == 'external' or ss_class == 'navlink': classattr += 'rel="nofollow" ' - if authentication: - path = privileged_path() - else: - path = script_name() - return '%s' % (classattr, path, params, text) + elif url_re.match(params): + classattr += 'rel="nofollow" ' + return '%s' % (classattr, relative_url(params, privileged=privileged), text) # Search --------------------------------------------------- -def do_fullsearch(needle): +def handle_fullsearch(needle): send_title(None, 'Full text search for "%s"' % (needle)) needle_re = re.compile(needle, re.IGNORECASE) @@ -196,7 +221,7 @@ def do_fullsearch(needle): print_search_stats(len(hits), len(all_pages)) -def do_titlesearch(needle): +def handle_titlesearch(needle): # TODO: check needle is legal -- but probably we can just accept any RE send_title(None, "Title search for \"" + needle + '"') @@ -214,45 +239,39 @@ def do_titlesearch(needle): def print_search_stats(hits, searched): print "

%d hits out of %d pages searched.

" % (hits, searched) -#TODO: merge into do_savepage() -def do_edit(pagename): - Page(pagename).send_editor() - -def do_raw(pagename): +def handle_raw(pagename): Page(pagename).send_raw() -def do_savepage(pagename): - global form +def handle_edit(pagename): pg = Page(pagename) - if 'preview' in form: - pg.send_editor(form['savetext'].value) - elif 'save' in form: - pg.save_text(form['savetext'].value) - pg.send_page() + if 'save' in form: + if form['file'].value: + pg.save(form['file'].file.read()) + else: + pg.save(form['savetext'].value.replace('\r\n', '\n')) + pg.format() elif 'cancel' in form: - pg.msg = 'Editing canceled' + pg.msg_text = 'Editing canceled' pg.msg_type = 'notice' - pg.send_page() - else: - raise 'What did you press?' + pg.format() + else: # preview or edit + text = None + if 'preview' in form: + text = form['savetext'].value + pg.send_editor(text) def make_index_key(): - s = '

' - links = map(lambda ch: '%s' % (ch, ch), - string.lowercase) - s = s + string.join(links, ' | ') - s = s + '

' - return s + links = map(lambda ch: '%s' % (ch, ch), 'abcdefghijklmnopqrstuvwxyz') + return '

'+ ' | '.join(links) + '

' -def page_list(): - return filter(word_re.match, os.listdir(data_dir)) +def page_list(dir = None, re = word_re): + return filter(re.match, os.listdir(dir or data_dir)) def send_footer(name, mod_string=None): if globals().get('debug_cgi', False): cgi.print_arguments() - cgi.print_form(cgi.FieldStorage()) + cgi.print_form(form) cgi.print_environ() - global __version__ print '' -# ---------------------------------------------------------- -# Macros -def _macro_TitleSearch(*vargs): - return _macro_search("titlesearch") - -def _macro_FullSearch(*vargs): - return _macro_search("fullsearch") - -def _macro_search(type): - if form.has_key('value'): - default = form["value"].value - else: - default = '' - return """
""" % (type, default) - -def _macro_WordIndex(*vargs): - s = make_index_key() - pages = list(page_list()) - map = {} - word_re = re.compile('[A-Z][a-z]+') - for name in pages: - for word in word_re.findall(name): - try: - map[word].append(name) - except KeyError: - map[word] = [name] - - all_words = map.keys() - all_words.sort() - last_letter = None - # set title - for word in all_words: - letter = string.lower(word[0]) - if letter != last_letter: - s = s + ';

%s

' % (letter, letter) - last_letter = letter - - s = s + '%s
    ' % word - links = map[word] - links.sort() - last_page = None - for name in links: - if name == last_page: continue - s = s + '
  • ' + Page(name).link_to() - s = s + '
' - return s - - -def _macro_TitleIndex(*vargs): - s = make_index_key() - pages = list(page_list()) - pages.sort() - current_letter = None - for name in pages: - letter = string.lower(name[0]) - if letter != current_letter: - s = s + '

%s

' % (letter, letter) - current_letter = letter - else: - s = s + '
' - s = s + Page(name).link_to() - return s - - -# ---------------------------------------------------------- -class PageFormatter: +class WikiFormatter: """Object that turns Wiki markup into HTML. All formatting commands can be parsed one line at a time, though @@ -334,34 +288,42 @@ class PageFormatter: """ def __init__(self, raw): self.raw = raw - self.is_em = self.is_b = 0 self.h_level = 0 - self.h_count = 0 + self.in_pre = self.in_html = self.in_table = self.in_li = False + self.in_header = True self.list_indents = [] - self.in_pre = False - self.in_table = False self.tr_cnt = 0 - self.in_var = False - self.in_header = True + self.styles = { + #wiki html enabled? + "//": ["em", False], + "''": ["em", False], + "**": ["b", False], + "'''": ["b", False], + "##": ["tt", False], + "``": ["tt", False], + "__": ["u", False], + "^^": ["sup", False], + ",,": ["sub", False] + } - def _emph_repl(self, word): - if len(word) == 3: - self.is_b = not self.is_b - return ['', ''][self.is_b] - else: - self.is_em = not self.is_em - return ['', ''][self.is_em] + def _b_repl(self, word): + style = self.styles[word] + style[1] = not style[1] + return ['' def _tit_repl(self, word): if self.h_level: - result = '' % self.h_level + result = '

\n' % self.h_level self.h_level = 0 else: self.h_level = len(word) - 1 - self.h_count += 1 - result = '* ' % (self.h_level, self.h_count, self.h_count) + link = permalink(self.line) + result = '\n

¶ ' % (self.h_level, link, link) return result + def _br_repl(self, word): + return '
' + def _rule_repl(self, word): return self._undent() + '\n
\n' % (len(word) - 2) @@ -369,7 +331,7 @@ class PageFormatter: return Page(word).link_to() def _img_repl(self, word): - path = script_name() + '/' + word; + path = relative_url(word) return '' % (path, path) def _url_repl(self, word): @@ -378,36 +340,75 @@ class PageFormatter: else: return '%s' % (word, word) - def _hurl_repl(self, word): - m = re.compile("\[\[(\S+)([^\]]*)\]\]").match(word) + def _macro_repl(self, word): + m = re.compile("\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>").match(word) name = m.group(1) - descr = m.group(2).strip() or name + argv = [name] + if m.group(2): + argv.extend(m.group(2).split('|')) + argv = map(str.strip, argv) macro = globals().get('_macro_' + name) + if not macro: + execfile("macros/" + name + ".py", globals()) + macro = globals().get('_macro_' + name) if macro: - return apply(macro, (name, descr)) - elif img_re.match(name): - return '%s' % (name, name, descr) - elif url_re.match(name): - return '%s' % (name, descr) - elif name.startswith('/'): - return '%s' % (name, descr) + return macro(argv) + else: + return '<<' + '|'.join(argv) + '>>' + + def _hurl_repl(self, word): + m = link_re.match(word) + name = m.group(1) + descr = m.group(2) + if descr is None: + descr = name + elif img_re.match(m.group(2)): + descr = '' + + return link_tag(name, descr, 'wikilink') + + def _inl_repl(self, word): + m = link_re.match(word) + name = m.group(1) + descr = m.group(2) or name + name = relative_url(name) + argv = descr.split('|') + descr = argv.pop(0) + + if argv: + args = '?' + '&'.join(argv) else: - return link_tag(name, descr) + args = '' + + if descr: + # The "extthumb" nonsense works around a limitation of the HTML block model + return '
%s
%s
' \ + % (name, name + args, descr, descr) + else: + return '' % (name, name + args) def _email_repl(self, word): return '%s' % (word, word) def _html_repl(self, word): + self.in_html += 1 return word; # Pass through def _ent_repl(self, s): + if self.in_html and s == '>': + self.in_html -= 1 + return '>' return {'&': '&', '<': '<', '>': '>'}[s] def _li_repl(self, match): - return '
  • ' + if self.in_li: + return '
  • ' + else: + self.in_li = True + return '
  • ' def _pre_repl(self, word): if word == '{{{' and not self.in_pre: @@ -419,22 +420,7 @@ class PageFormatter: return '' def _hi_repl(self, word): - if word == 'FIXME': - cl = 'error' - elif word == 'DONE': - cl = 'success' - elif word == 'TODO': - cl = 'notice' - return '' + word + '' - - def _var_repl(self, word): - if word == '{{' and not self.in_var: - self.in_var = True - return '' - elif self.in_var: - self.in_var = False - return '' - return '' + return '' + word + '' def _tr_repl(self, word): out = '' @@ -443,16 +429,17 @@ class PageFormatter: self.tr_cnt = 0 out = '

    \n' self.tr_cnt += 1 - return out + '' + return out + ['' + return ['', ''][word.strip() == '||='] return '' def _indent_level(self): @@ -464,6 +451,9 @@ class PageFormatter: s = '

    ' while self._indent_level() > new_level: del(self.list_indents[-1]) + if self.in_li: + s += '' + self.in_li = False # FIXME s += '\n' while self._indent_level() < new_level: self.list_indents.append(new_level) @@ -481,7 +471,7 @@ class PageFormatter: def replace(self, match): for type, hit in match.groupdict().items(): if hit: - return apply(getattr(self, '_' + type + '_repl'), (hit,)) + return getattr(self, '_' + type + '_repl')(hit) else: raise "Can't handle match " + `match` @@ -490,97 +480,99 @@ class PageFormatter: # For each line, we scan through looking for magic # strings, outputting verbatim any intervening text - # TODO: highlight search words (look at referer) + # TODO: highlight search words (look at referrer) scan_re = re.compile( r"(?:" # Formatting - + r"(?P'{2,3})" + + r"(?P\*\*|'''|//|''|##|``|__|\^\^|,,)" + r"|(?P\={2,6})" + + r"|(?P
    \\\\)" + r"|(?P^-{3,})" - + r"|(?P<(/|)(div|span|iframe)[^<>]*>)" - + r"|(?P[<>&])" + r"|(?P\b(FIXME|TODO|DONE)\b)" # Links - + r"|(?P\b[a-zA-Z0-9_-]+\.(png|gif|jpg|jpeg|bmp))" + + r"|(?P\<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>)" + + r"|(?P\[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\])" + + # Inline HTML + + r"|(?P<(/|)(br|hr|div|form|iframe|input|span))" + + r"|(?P[<>&])" + + # Auto links (LEGACY) + + r"|(?P\b[a-zA-Z0-9_/-]+\.(png|gif|jpg|jpeg|bmp|ico))" + r"|(?P\b(?:[A-Z][a-z]+){2,}\b)" - + r"|(?P\[\[\S+[^\]]*\]\])" + r"|(?P(http|https|ftp|mailto)\:[^\s'\"]+\S)" + r"|(?P[-\w._+]+\@[\w.-]+)" # Lists, divs, spans - + r"|(?P
  • ^\s+\*)" - + r"|(?P
    (\{\{\{|\s*\}\}\}))"
    -            + r"|(?P(\{\{|\}\}))"
    +            + r"|(?P
  • ^\s+[\*#] +)" + + r"|(?P
    \{\{\{|\s*\}\}\})"
    +            + r"|(?P\{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})"
     
                 # Tables
    -            + r"|(?P
  • ^\s*\|\|\s*)" - + r"|(?P\s*\|\|\s*$)" - + r"|(?P^\s*\|\|(=|)\s*)" + + r"|(?P\s*\|\|(=|)\s*$)" + + r"|(?P
    ' + out = out + '
    ', ''][word.strip() == '||='] - def _tre_repl(self, word): + def _td_repl(self, word): if self.in_table: - return '
    ', ''][word.strip() == '||='] return '' - def _td_repl(self, word): + def _tre_repl(self, word): if self.in_table: - return '' + return ['
    \s*\|\|\s*)" + + r"|(?P
    \s*\|\|(=|)\s*)" + r")") pre_re = re.compile( r"(?:" + r"(?P
    \s*\}\}\})"
    +            + r"|(?P[<>&])"
                 + r")")
             blank_re = re.compile(r"^\s*$")
             indent_re = re.compile(r"^\s*")
             tr_re = re.compile(r"^\s*\|\|")
             eol_re = re.compile(r"\r?\n")
    -        raw = string.expandtabs(self.raw)
    -        for line in eol_re.split(raw):
    +        for self.line in eol_re.split(self.raw.expandtabs()):
                 # Skip ACLs
                 if self.in_header:
    -                if line.startswith('#'):
    -                   continue
    +                if self.line.startswith('#'):
    +                    continue
                     self.in_header = False
     
                 if self.in_pre:
    -                print re.sub(pre_re, self.replace, line)
    +                print re.sub(pre_re, self.replace, self.line)
                 else:
    -                if self.in_table and not tr_re.match(line):
    +                if self.in_table and not tr_re.match(self.line):
                         self.in_table = False
                         print '

    ' - if blank_re.match(line): + if blank_re.match(self.line): print '

    ' else: - indent = indent_re.match(line) + indent = indent_re.match(self.line) print self._indent_to(len(indent.group(0))) - print re.sub(scan_re, self.replace, line) + print re.sub(scan_re, self.replace, self.line) if self.in_pre: print '' if self.in_table: print '

    ' print self._undent() print '

    ' -# ---------------------------------------------------------- class Page: def __init__(self, page_name): self.page_name = page_name - self.msg = '' + self.msg_text = '' self.msg_type = 'error' - self.attrs = {} def split_title(self): - # look for the end of words and the start of a new word, - # and insert a space there + # look for the end of words and the start of a new word and insert a space there return re.sub('([a-z])([A-Z])', r'\1 \2', self.page_name) - def _text_filename(self): + def _filename(self): return path.join(data_dir, self.page_name) def _tmp_filename(self): - return path.join(data_dir, ('#' + self.page_name + '.' + `os.getpid()` + '#')) + return path.join(data_dir, ('#' + self.page_name.replace('/','_') + '.' + `os.getpid()` + '#')) def exists(self): try: - os.stat(self._text_filename()) + os.stat(self._filename()) return True except OSError, er: if er.errno == errno.ENOENT: return False - else: - raise er + raise er def link_to(self): word = self.page_name @@ -591,17 +583,36 @@ class Page: def get_raw_body(self): try: - return open(self._text_filename(), 'rt').read() + return open(self._filename(), 'rb').read() except IOError, er: if er.errno == errno.ENOENT: return '' # just doesn't exist, use default + if er.errno == errno.EISDIR: + return self.format_dir() raise er + def format_dir(self): + out = '== ' + path = '' + for dir in self.page_name.split('/'): + path = (path + '/' + dir) if path else dir + out += '[[' + path + '|' + dir + ']]/' + out += ' ==\n' + + for file in page_list(self._filename(), file_re): + if img_re.match(file): + if image_maxwidth: + maxwidth_arg = '|maxwidth=' + str(image_maxwidth) + out += '{{' + self.page_name + '/' + file + '|' + file + maxwidth_arg + '}}\n' + else: + out += ' * [[' + self.page_name + '/' + file + ']]\n' + return out def get_attrs(self): - if self.attrs: + if 'attrs' in self.__dict__: return self.attrs + self.attrs = {} try: - file = open(self._text_filename(), 'rt') + file = open(self._filename(), 'rt') attr_re = re.compile(r"^#(\S*)(.*)$") for line in file: m = attr_re.match(line) @@ -610,25 +621,26 @@ class Page: self.attrs[m.group(1)] = m.group(2).strip() #print "bernie: attrs[" + m.group(1) + "] = " + m.group(2) + "
    \n" except IOError, er: - if er.errno != errno.ENOENT: + if er.errno != errno.ENOENT and er.errno != errno.EISDIR: raise er return self.attrs + def get_attr(self, name, default): + return self.get_attrs().get(name, default) + def can(self, action, default=True): - attrs = self.get_attrs() + acl = None try: - # SomeUser:read,write All:read - acl = attrs["acl"] + #acl SomeUser:read,write All:read + acl = self.get_attr("acl", None) for rule in acl.split(): - (user,perms) = rule.split(':') + (user, perms) = rule.split(':') if user == remote_user() or user == "All": - if action in perms.split(','): - return True - else: - return False + return action in perms.split(',') return False except Exception, er: - pass + if acl: + self.msg_text = 'Illegal acl line: ' + acl return default def can_write(self): @@ -637,21 +649,28 @@ class Page: def can_read(self): return self.can("read", True) - def send_page(self): - page_name = None - if self.can_write(): - page_name = self.page_name - send_title(page_name, self.split_title(), msg=self.msg, msg_type=self.msg_type) + def send_naked(self): if self.can_read(): - PageFormatter(self.get_raw_body()).print_html() + WikiFormatter(self.get_raw_body()).print_html() else: send_guru("Read access denied by ACLs", "notice") - send_footer(page_name, self._last_modified()) + + def format(self): + #css foo.css + value = self.get_attr("css", None) + if value: + global link_urls + link_urls += { "stylesheet": value } + + send_title(self.page_name, self.split_title(), + msg_text=self.msg_text, msg_type=self.msg_type, writable=self.can_write()) + self.send_naked() + send_footer(self.page_name, self._last_modified()) def _last_modified(self): try: from time import localtime, strftime - modtime = localtime(os.stat(self._text_filename())[stat.ST_MTIME]) + modtime = localtime(os.stat(self._filename())[stat.ST_MTIME]) except OSError, er: if er.errno != errno.ENOENT: raise er @@ -659,18 +678,23 @@ class Page: return strftime(datetime_fmt, modtime) def send_editor(self, preview=None): - send_title(None, 'Edit ' + self.split_title(), msg=self.msg, msg_type=self.msg_type) + send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type) if not self.can_write(): send_guru("Write access denied by ACLs", "error") return + file = '' + if 'file' in form: + file = form['file'].value + print ('

    Editing ' + self.page_name + ' for ' + cgi.escape(remote_user()) + ' from ' + cgi.escape(get_hostname(remote_host())) + '

    ') - print '
    ' % (script_name(), self.page_name) - print '' % (self.page_name) - print """""" % (preview or self.get_raw_body()) + print '
    ' % relative_url(self.page_name) + print '' % (self.page_name) + print '' % (preview or self.get_raw_body()) + print 'Or upload a file: ' % file print """
    @@ -682,36 +706,47 @@ class Page: print "

    " + Page('EditingTips').link_to() + "

    " if preview: print "
    " - PageFormatter(preview).print_html() + WikiFormatter(preview).print_html() print "
    " send_footer(self.page_name) - def send_raw(self): - if not self.can_read(): - send_title(None, msg='Read access denied by ACLs', msg_type='notice') - return - emit_header("text/plain") - print self.get_raw_body() + def send_raw(self, mimetype='text/plain'): + if self.can_read(): + body = self.get_raw_body() + emit_header(mimetype) + print body + else: + send_title(None, msg_text='Read access denied by ACLs', msg_type='notice') + + def send_image(self, mimetype, args=[]): + if 'maxwidth' in args: + import subprocess + emit_header(mimetype) + sys.stdout.flush() + subprocess.check_call(['gm', 'convert', self._filename(), + '-scale', args['maxwidth'].value + ' >', '-']) + else: + self.send_raw(mimetype) - def _write_file(self, text): + def _write_file(self, data): tmp_filename = self._tmp_filename() - open(tmp_filename, 'wt').write(text.replace('\r\n', '\n')) - text = self._text_filename() + open(tmp_filename, 'wb').write(data) + name = self._filename() if os.name == 'nt': # Bad Bill! POSIX rename ought to replace. :-( try: - os.remove(text) + os.remove(name) except OSError, er: if er.errno != errno.ENOENT: raise er - os.rename(tmp_filename, text) + os.rename(tmp_filename, name) - def save_text(self, newtext): + def save(self, newdata): if not self.can_write(): - self.msg = 'Write access denied by ACLs' + self.msg_text = 'Write access denied by ACLs' self.msg_type = 'error' return - self._write_file(newtext) + self._write_file(newdata) rc = 0 if post_edit_hook: # FIXME: what's the std way to perform shell quoting in python? @@ -721,39 +756,26 @@ class Page: + "' '" + remote_host() + "'" ) out = os.popen(cmd) - msg = out.read() + output = out.read() rc = out.close() if rc: - self.msg += "Post-editing hook returned %d.\n" % rc - self.msg += 'Command was: ' + cmd + '\n' - if msg: - self.msg += 'Output follows:\n' + msg + self.msg_text += "Post-editing hook returned %d.\n" % rc + self.msg_text += 'Command was: ' + cmd + '\n' + if output: + self.msg_text += 'Output follows:\n' + output else: - self.msg = 'Thank you for your contribution. Your attention to detail is appreciated.' + self.msg_text = 'Thank you for your contribution. Your attention to detail is appreciated.' self.msg_type = 'success' -#TODO: merge into send_raw() -def send_verbatim(filename, mime_type='application/octet-stream'): - pathname = path.join(data_dir, filename) - data = open(pathname, 'rb').read() - emit_header(mime_type) - sys.stdout.write(data) - # Main --------------------------------------------------------------- try: execfile("geekigeeki.conf.py") - form = cgi.FieldStorage() - handlers = { 'fullsearch': do_fullsearch, - 'titlesearch': do_titlesearch, - 'edit': do_edit, - 'raw': do_raw, - 'savepage': do_savepage } - - for cmd in handlers.keys(): - if form.has_key(cmd): - apply(handlers[cmd], (form[cmd].value,)) + for cmd in form: + handler = globals().get('handle_' + cmd) + if handler: + handler(form[cmd].value) break else: path_info = environ.get('PATH_INFO', '') @@ -764,22 +786,30 @@ try: if file_re.match(query): if word_re.match(query): - Page(query).send_page() - elif img_re.match(query): - #FIXME: use correct mime type - send_verbatim(query, 'image/jpeg') + Page(query).format() else: - send_verbatim(query) + from mimetypes import MimeTypes + type, encoding = MimeTypes().guess_type(query) + #type = type or 'text/plain' + #Page(query).send_raw(mimetype=type) + if type: + if type.startswith('image/'): + Page(query).send_image(mimetype=type,args=form) + else: + Page(query).send_raw(mimetype=type) + else: + Page(query).format() else: print "Status: 404 Not Found" - send_title(None, msg='Can\'t work out query: ' + query) -except: + send_title(None, msg_text='Can\'t work out query: ' + query) + send_footer(None) +except Exception: import traceback - msg=traceback.format_exc() + msg_text = traceback.format_exc() if title_done: - send_guru(msg, "error") + send_guru(msg_text, "error") else: - send_title(None, msg=msg) + send_title(None, msg_text=msg_text) send_footer(None) sys.stdout.flush()