#!/usr/bin/env python from os.path import join, basename, dirname, \ splitext, exists import glob, sys, re import cgi, cgitb from docutils.core import publish_string import em __version__ = '0.1.0' __license__ = 'GPL' __author__ = 'Dinu Gherman' PROG = basename(sys.argv[0]) WIKI_DIR = "/Library/WebServer/Documents/wickiedata/" WIKI_EXT = ".txt" PAGES = {} # HTML snippets (should go into some styles module) HEADER = """\ %%(name)s

%%(name)s

""" % {'image': 'file://'+join(WIKI_DIR, "wickie.jpg")} EDIT_THIS = '\nEdit\n' BUTTONS = """\ RecentChanges FrontPage """ EDIT_AREA = """\

""" FOOTER = "\n\n\n" NEW_PAGE = "Please edit some content for this new page \ in order to save it!" def getWikiPaths(): pat = join(WIKI_DIR, "*" + WIKI_EXT) return glob.glob(pat) def wikiPath2name(path): base = basename(path) return splitext(base)[0], exists(path) def wikiName2path(name): base = name + WIKI_EXT path = join(WIKI_DIR, base) return path, exists(path) def wikiName2link(name, action="show"): anchor = name if action == "new": anchor = anchor + '?' return '`%s <%s?%s=%s>`__' % (anchor, PROG, action, name) def makeButtonsLine(path, edit): name, ex = wikiPath2name(path) d = {'name': name, 'PROG': PROG} s = "\n

\n" if not edit: s = s + EDIT_THIS % d s = s + BUTTONS % d + "

\n" return s def loadPage(path): name, ex = wikiPath2name(path) if ex: return open(path).read() return NEW_PAGE def empyfy(text): wikiNames = re.findall("@[a-zA-z0-9_]+", text) wikiNames = map(lambda name:name[1:], wikiNames) wikiNames = filter(lambda name: name not in PAGES.keys(), wikiNames) for name in wikiNames: PAGES[name] = wikiName2link(name, action="new") return em.expand(text, PAGES) def reSTify(content): settings = {'input_encoding': 'latin-1', 'output_encoding': 'latin-1'} rest = publish_string(content, writer_name='html', settings_overrides=settings) start = rest.find("") p = rest[start+len(""):].find(">") snip = rest[start+len("")+p+2:-23] # magic snip = snip.replace("@", "@") # hack return snip def addPageNames(): for path in getWikiPaths(): name, ex = wikiPath2name(path) if ex: link = wikiName2link(name) PAGES[name] = link def outputHTML(name, path, edit, html, textarea=""): out = sys.stdout.write out("Content-type: text/html\n\n") out(HEADER % {'name': name}) out(makeButtonsLine(path, edit)) out(html) if textarea: out(textarea) out(makeButtonsLine(path, edit)) out(FOOTER) def mainCGI(): cgitb.enable() query = cgi.FieldStorage() qgetval = lambda n: query.getvalue(n, '') show, edit, save, new = \ map(qgetval, "show edit save new".split()) name = show or edit or save or new or "FrontPage" path, ex = wikiName2path(name) textarea = '' page = loadPage(path) if edit: args = {'PROG': PROG, 'content': loadPage(path), 'name': wikiPath2name(path)[0]} textarea = EDIT_AREA % args elif save: area = qgetval('area') open(path, 'w').write(area) addPageNames() mpPage = empyfy(page) html = reSTify(mpPage) outputHTML(name, path, edit, html, textarea) if __name__ == '__main__': mainCGI()