X-Git-Url: https://codewiz.org/gitweb?p=geekigeeki.git;a=blobdiff_plain;f=geekigeeki.py;h=d63850fb57b8e55494930871cc8f4f23271b3b5c;hp=aa54781073b62048ff81f144243ecebfca6f9ae8;hb=ae02752908b5369019933b080324189ee373bed2;hpb=021fb390a791a3f990df0a4b9a51527cc47fb69b diff --git a/geekigeeki.py b/geekigeeki.py index aa54781..d63850f 100755 --- a/geekigeeki.py +++ b/geekigeeki.py @@ -1,16 +1,16 @@ #!/usr/bin/python # -*- coding: utf-8 -*- # -# Copyright 1999, 2000 Martin Pool -# Copyright 2002 Gerardo Poggiali -# Copyright 2007, 2008, 2009 Bernie Innocenti +# Copyright (C) 1999, 2000 Martin Pool +# Copyright (C) 2002 Gerardo Poggiali +# Copyright (C) 2007, 2008, 2009, 2010 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 -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. You should have received a copy -# of the GNU General Public License along with this program. -# If not, see . +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . __version__ = '4.0-' + '$Id$'[4:11] @@ -22,14 +22,13 @@ import cgi, sys, os, re, errno, stat, glob image_ext = 'png|gif|jpg|jpeg|bmp|ico' video_ext = "ogg|ogv|oga" # Not supported by Firefox 3.5: mkv|mpg|mpeg|mp4|avi|asf|flv|wmv|qt -image_re = re.compile(r".*\.(" + image_ext + "|" + video_ext + ")", re.IGNORECASE) -video_re = re.compile(r".*\.(" + video_ext + ")", re.IGNORECASE) +image_re = re.compile(r".*\.(" + image_ext + "|" + video_ext + ")$", re.IGNORECASE) +video_re = re.compile(r".*\.(" + video_ext + ")$", re.IGNORECASE) # FIXME: we accept stuff like foo/../bar and we shouldn't -file_re = re.compile(r"([A-Za-z0-9_\-][A-Za-z0-9_\.\-/]*)") -url_re = re.compile(r"[a-z]{3,8}://[^\s'\"]+\S") +file_re = re.compile(r"([A-Za-z0-9_\-][A-Za-z0-9_\.\-/ ]*)$") +url_re = re.compile(r"[a-z]{3,8}://[^\s'\"]+\S$") ext_re = re.compile(r"\.([^\./]+)$") -# CGI stuff --------------------------------------------------------- def config_get(key, default=None): return globals().get(key, default) @@ -106,11 +105,12 @@ def url_args(kvargs): return '?' + '&'.join(argv) return '' -# Formatting stuff -------------------------------------------------- def emit_header(mtime=None, mime_type="text/html"): if mtime: print("Last-Modified: " + strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime(mtime))) - print("Content-type: " + mime_type + "; charset=utf-8\n") + if mime_type: + print("Content-type: " + mime_type + "; charset=utf-8") + print('') def send_guru(msg_text, msg_type): if not msg_text: return @@ -120,92 +120,24 @@ def send_guru(msg_text, msg_type): print(cgi.escape(msg_text)) if msg_type == 'error': print '\n Guru Meditation #DEADBEEF.ABADC0DE' - print('' \ + print('' \ % relative_url('sys/GuruMeditation.js')) -def send_title(name, text="Limbo", msg_text=None, msg_type='error', writable=False, mtime=None): - global title_done - if title_done: return - - # Head - emit_header(mtime) - print('') - print('') - - print("%s: %s" % (config_get('site_name', "Unconfigured Wiki"), text)) - print(' ') - if not name: - print(' ') - - for http_equiv, content in config_get('meta_urls', {}): - print(' ' % (http_equiv, relative_url(content))) - - for link in config_get('link_urls', {}): - rel, href = link - print(' ' % (rel, relative_url(href))) - - editable = name and writable and is_privileged() - if editable: - print(' ' \ - % relative_url('?a=edit&q=' + name, privileged=True)) - - history = config_get('history_url') - if history is not None: - print(' ' \ - % relative_url(history + '?a=rss')) - - print('') - - # Body - if editable: - print('') - else: - print('') - - title_done = True - send_guru(msg_text, msg_type) - - # Navbar - print('') - -def send_httperror(status="403 Not Found", query=""): +def send_httperror(status="403 Not Found", query="", trace=False): print("Status: %s" % status) - send_title(None, msg_text=("%s: on query '%s'" % (status, query))) - send_footer() + msg_text = "%s: on query '%s'" % (status, query) + if trace: + import traceback + msg_text += '\n\n' + traceback.format_exc() + page = Page() + page.send_title(msg_text=msg_text) + page.send_footer() def link_tag(dest, text=None, privileged=False, **kvargs): if text is None: text = humanlink(dest) elif image_re.match(text): - text = '' + text + '' + text = '' + text + '' link_class = kvargs.get('class', kvargs.get('cssclass', None)) if not link_class: @@ -247,14 +179,12 @@ def link_inline_glob(pattern, descr=None, kvargs={}): else: return link_inline(pattern, descr, kvargs) -# Search --------------------------------------------------- - -def print_search_stats(hits, searched): - print("

%d hits out of %d pages searched.

" % (hits, searched)) +def search_stats(hits, searched): + return "%d hits out of %d pages searched.\n" % (hits, searched) def handle_fullsearch(query, form): needle = form['q'].value - send_title(None, 'Full text search for "' + needle + '"') + Page().send_title(text='Full text search for "' + needle + '"') needle_re = re.compile(needle, re.IGNORECASE) hits = [] @@ -265,59 +195,50 @@ def handle_fullsearch(query, form): if count: hits.append((count, page_name)) - # The default comparison for tuples compares elements in order, - # so this sorts by number of hits + # The default comparison for tuples compares elements in order, so this sorts by number of hits hits.sort() hits.reverse() - print("
    ") + out = '' for (count, page_name) in hits: - print('
  • ' + link_tag(page_name)) - print(' . . . . ' + `count`) - print(['match', 'matches'][count != 1]) - print('

  • ') - print("
") + out += ' * [[' + page_name + ']] . . . ' + str(count) + ' ' + ['match', 'matches'][count != 1] + '\n' - print_search_stats(len(hits), len(all_pages)) + out += search_stats(len(hits), len(all_pages)) + WikiFormatter(out).print_html() def handle_titlesearch(query, form): needle = form['q'].value - send_title(None, 'Title search for "' + needle + '"') + Page().send_title(text='Title search for "' + needle + '"') needle_re = re.compile(needle, re.IGNORECASE) all_pages = page_list() hits = list(filter(needle_re.search, all_pages)) - print("
    ") + out = '' for filename in hits: - print('
  • ' + link_tag(filename) + "

  • ") - print("
") + out += ' * [[' + filename + ']]\n' - print_search_stats(len(hits), len(all_pages)) + out += search_stats(len(hits), len(all_pages)) + WikiFormatter(out).print_html() def handle_raw(pagename, form): - if not file_re.match(pagename): - send_httperror("403 Forbidden", pagename) - return - Page(pagename).send_raw() -def handle_edit(pagename, form): - if not file_re.match(pagename): - send_httperror("403 Forbidden", pagename) - return +def handle_atom(pagename, form): + Page(pagename).send_atom() - pg = Page(form['q'].value) +def handle_edit(pagename, form): + pg = Page(form['q'].value) if 'save' in form: if form['file'].value: pg.save(form['file'].file.read(), form['changelog'].value) else: pg.save(form['savetext'].value.replace('\r\n', '\n'), form['changelog'].value) - pg.format() + pg.send() elif 'cancel' in form: pg.msg_text = 'Editing canceled' pg.msg_type = 'notice' - pg.format() + pg.send() else: # preview or edit text = None if 'preview' in form: @@ -325,16 +246,13 @@ def handle_edit(pagename, form): pg.send_editor(text) def handle_get(pagename, form): - if file_re.match(pagename): - # FIMXE: this is all bullshit, MimeTypes bases its guess on the extension! - from mimetypes import MimeTypes - mimetype, encoding = MimeTypes().guess_type(pagename) - if mimetype: - Page(pagename).send_raw(mimetype=mimetype, args=form) - else: - Page(pagename).format() - else: - send_httperror("403 Forbidden", pagename) + if not ext_re.search(pagename): # FIXME: no extension guesses a wiki page + Page(pagename).send() + else: + # FIMXE: this is all bullshit, MimeTypes bases its guess on the extension! + from mimetypes import MimeTypes + mimetype, encoding = MimeTypes().guess_type(pagename) + Page(pagename).send_raw(mimetype=mimetype, args=form) # Used by sys/macros/WordIndex and sys/macros/TitleIndex def make_index_key(): @@ -347,16 +265,6 @@ def page_list(dirname=None, search_re=None): search_re = re.compile(r"^\b((([A-Z][a-z0-9]+){2,}/)*([A-Z][a-z0-9]+){2,})\b$") return sorted(filter(search_re.match, os.listdir(dirname or '.'))) -def send_footer(mtime=None): - if config_get('debug_cgi', False): - cgi.print_arguments() - cgi.print_form(form) - cgi.print_environ() - link_inline("sys/footer", kvargs = { - 'LAST_MODIFIED': strftime(config_get('datetime_fmt', '%a %d %b %Y %I:%M %p'), localtime(mtime)) - }) - print("") - def _macro_ELAPSED_TIME(*args, **kvargs): return "%03f" % (clock() - start_time) @@ -364,11 +272,7 @@ def _macro_VERSION(*args, **kvargs): return __version__ class WikiFormatter: - """Object that turns Wiki markup into HTML. - - All formatting commands can be parsed one line at a time, though - some state is carried over between lines. - """ + """Object that turns Wiki markup into HTML.""" def __init__(self, raw, kvargs=None): self.raw = raw self.kvargs = kvargs or {} @@ -388,7 +292,6 @@ class WikiFormatter: ",,": ["sub", False], "''": ["em", False], # LEGACY "'''": ["b", False], # LEGACY - "``": ["tt", False], # LEGACY } def _b_repl(self, word): @@ -552,7 +455,7 @@ class WikiFormatter: scan_re = re.compile(r"""(?: # Styles and formatting ("--" must cling to a word to disambiguate it from the dash) - (?P \*\* | // | \#\# | __ | --\b | \b-- | \^\^ | ,, | ''' | '' | `` ) + (?P \*\* | // | \#\# | __ | --\b | \b-- | \^\^ | ,, | ''' | '' ) | (?P \={2,6}) | (?P
\\\\) | (?P ^-{3,}) @@ -560,8 +463,8 @@ class WikiFormatter: | (?P --) # Links - | (?P \<\<([^\s\|\>]+)(?:\s*\|\s*([^\>]+)|)\>\>) - | (?P \[\[([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\]\]) + | (?P \<\<[^\>]+\>\>) + | (?P \[\[[^\]]+\]\]) # Inline HTML | (?P <(br|hr|div|span|form|iframe|input|textarea|a|img|h[1-5])\b ) @@ -577,7 +480,7 @@ class WikiFormatter: # Lists, divs, spans and inline objects | (?P
  • ^\s+[\*\#]\s+) | (?P
       \{\{\{|\s*\}\}\})
    -            | (?P   \{\{([^\s\|]+)(?:\s*\|\s*([^\]]+)|)\}\})
    +            | (?P   \{\{[^\}]+\}\})
     
                 # Tables
                 | (?P    ^\s*\|\|(=|)\s*)
    @@ -614,8 +517,8 @@ class WikiFormatter:
                         print('

    ') else: indent = indent_re.match(self.line) - #3.0: print(self._indent_to(len(indent.group(0))), end=' ') print(self._indent_to(len(indent.group(1)), indent.group(2))) + # Stand back! Here we apply the monster regex that does all the parsing print(re.sub(scan_re, self.replace, self.line)) if self.in_pre: print('

    ') @@ -623,11 +526,18 @@ class WikiFormatter: print(self._indent_to(0)) print('

    ') +class HttpException(Exception): + def __init__(self, error, query): + self.error = error + self.query = query + class Page: - def __init__(self, page_name): - self.page_name = page_name + def __init__(self, page_name="Limbo"): + self.page_name = page_name.rstrip('/'); self.msg_text = '' self.msg_type = 'error' + if not file_re.match(self.page_name): + raise HttpException("403 Forbidden", self.page_name) def split_title(self): # look for the end of words and the start of a new word and insert a space there @@ -668,19 +578,20 @@ class Page: out = '== ' pathname = '' for dirname in self.page_name.strip('/').split('/'): - pathname = (pathname + '/' + dirname) if pathname else dirname + pathname = (pathname and pathname + '/' ) + dirname out += '[[' + pathname + '|' + dirname + ']]/' out += ' ==\n' + images_out = '\n' for filename in page_list(self._filename(), file_re): if image_re.match(filename): maxwidth = config_get('image_maxwidth', '400') if maxwidth: maxwidth = ' | maxwidth=' + str(maxwidth) - out += '{{' + self.page_name + '/' + filename + ' | ' + humanlink(filename) + maxwidth + ' | class=thumbleft}}\n' + images_out += '{{' + self.page_name + '/' + filename + ' | ' + humanlink(filename) + maxwidth + ' | class=thumbleft}}\n' else: out += ' * [[' + self.page_name + '/' + filename + ']]\n' - return out + return out + images_out def pragmas(self): if not '_pragmas' in self.__dict__: @@ -723,26 +634,119 @@ class Page: def can_read(self): return self.can("read", True) + def send_title(self, name=None, text="Limbo", msg_text=None, msg_type='error'): + global title_done + if title_done: return + + # HEAD + emit_header(self._mtime()) + print('\n') + print("%s: %s" % (config_get('site_name', "Unconfigured Wiki"), text)) + print(' ') + if not name: + print(' ') + + for http_equiv, content in config_get('meta_urls', {}): + print(' ' % (http_equiv, relative_url(content))) + + for link in config_get('link_urls', {}): + rel, href = link + print(' ' % (rel, relative_url(href))) + + editable = name and self.can_write() and is_privileged() + if editable: + print(' ' \ + % relative_url('?a=edit&q=' + name, privileged=True)) + + history = config_get('history_url') + if history is not None: + print(' ' \ + % relative_url(history + '?a=rss')) + + print('') + + # BODY + if editable: + print('') + else: + print('') + + title_done = True + send_guru(msg_text, msg_type) + + if self.pragma("navbar", "on") != "on": + return + + # NAVBAR + print('') + + def send_footer(self): + if config_get('debug_cgi', False): + cgi.print_arguments() + cgi.print_form(form) + cgi.print_environ() + footer = self.pragma("footer", "sys/footer") + if footer != "off": + link_inline(footer, kvargs = { + 'LAST_MODIFIED': strftime(config_get('datetime_fmt', '%Y-%m-%dT%I:%M:%S%p'), localtime(self._mtime())) + }) + print("") + def send_naked(self, kvargs=None): if self.can_read(): WikiFormatter(self.get_raw_body(), kvargs).print_html() else: send_guru("Read access denied by ACLs", "notice") - def format(self): + def send(self): #css foo.css value = self.pragma("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(), mtime=self._mtime()) + self.send_title(name=self.page_name, text=self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type) + self.send_naked() + self.send_footer() + + def send_atom(self): + emit_header(self._mtime(), 'application/atom+xml') + self.in_html = True + link_inline("sys/atom_header", kvargs = { + 'LAST_MODIFIED': strftime(config_get('datetime_fmt', '%a, %d %b %Y %I:%M:%S %p'), localtime(self._mtime())) + }) + self.in_html = False self.send_naked() - send_footer(mtime=self._mtime()) + self.in_html = True + link_inline("sys/atom_footer") + self.in_html = False def send_editor(self, preview=None): - send_title(None, 'Edit ' + self.split_title(), msg_text=self.msg_text, msg_type=self.msg_type) + self.send_title(text='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 @@ -759,11 +763,11 @@ class Page: print("
    ") WikiFormatter(preview).print_html() print("
    ") - send_footer() + self.send_footer() def send_raw(self, mimetype='text/plain', args=[]): if not self.can_read(): - send_title(None, msg_text='Read access denied by ACLs', msg_type='notice', mtime=self._mtime()) + self.send_title(msg_text='Read access denied by ACLs', msg_type='notice') return emit_header(self._mtime(), mimetype) @@ -829,13 +833,9 @@ try: else: send_httperror("403 Forbidden", query_string()) +except HttpException, e: + send_httperror(e.error, query=e.query) except Exception: - import traceback - msg_text = traceback.format_exc() - if title_done: - send_guru(msg_text, "error") - else: - send_title(None, msg_text=msg_text) - send_footer() + send_httperror("500 Internal Server Error", query=query_string(), trace=True) sys.stdout.flush()