#!/usr/bin/env python """A script to edit a website, like an inverse-wiki.""" import sys, os, re, cgi script = os.environ.get('SCRIPT_NAME') method = os.environ.get('REQUEST_METHOD') r_head = re.compile(r'(?sm)
(.*?)') r_body = re.compile(r'(?sm)(.*?)') html = (lambda s: s.lstrip())(""" \n \n%s\n \n%s\n """) if method == 'POST': form = cgi.FieldStorage() form.__call__ = lambda s: form[s].value def serve(status, body): sys.stdout.write("Status: %s\r\n" % status) sys.stdout.write("Content-Type: text/html; charset=utf-8\r\n\r\n") sys.stdout.write(body) sys.exit() def edit(): filename = os.environ.get('QUERY_STRING') or 'index.html' if not filename.endswith('.') and filename.isalpha(): filename += '.html' elif not (filename.endswith('.html') and filename[:-5].isalpha()): serve(500, "Filename must match [A-Za-z]+\.html
\n") result = "" if not os.path.isfile(filename): result += "Warning: %s does not currently exist!
\n" % filename current = "" else: current = open(filename, 'r').read() current = current.replace('\r\n', '\n') current = current.replace('\r', '\n') if current.count(' 1 or current.count(''): serve(500, "Unable to grok <! or <? sections.
\n") try: head = r_head.search(current).group(1) body = r_body.search(current).group(1) except AttributeError: serve(500, "Couldn't find html:(head|body) elements.
\n") current = head.strip() + '\n\n' + body.strip() result += '\n' serve(200, result) def post(): text = form('text') filename = form('filename') text = text.replace('\r\n', '\n') text = text.replace('\r', '\n') # If there's a comment, PI, DOCTYPE, or CDATA section, barf start = text.lstrip()[:15] if start.startswith(' 1 or text.count(''): serve(500, "Unable to grok <! or <? sections.
\n") else: if text.count('Unable to grok <! or <? sections.\n") if not start.startswith('html:(head|body) are automatically added.\n") i = text.find('\n\n') if i < 0: serve(500, "Input must contain a blank line.
\n") head, body = text[:i], text[i:] headlines = [] for line in head.splitlines(): if line.startswith('Title: '): line = 'Wrote %s bytes to %s.
\n' serve(200, msg % (len(text), filename, filename)) def main(): if method == 'GET': edit() elif method == 'POST': post() else: serve(501, "Method must be either GET or POST
\n") if __name__=="__main__": import cgitb cgitb.enable() main()