#!/usr/bin/env python """ d8uvlist.py (cgi) - Directory Lister Author: Sean B. Palmer, inamidst.com """ import cgitb; cgitb.enable() import sys, os, re, time, textwrap from string import Template pathbase = '' base = os.environ.get('DOCUMENT_ROOT') r_title = re.compile(r'(?i)([^<]+)') bufsize = 2048 def format(text, variables): text = Template(text).substitute(variables) return textwrap.dedent(text) def htmltitle(fn): if not fn.endswith('.html'): return None try: f = open(fn) except: return None else: html = '' while True: s = f.read(bufsize) if not s: break html += s m = r_title.search(html) if m: f.close() return m.group(1) f.close() return None def modified(path): mtime = os.path.getmtime(path) return time.strftime('%Y-%m-%d at %H:%M', time.gmtime(mtime)) def header(status, mime=None): mime = mime or 'text/html; charset=utf-8' if status != 200: print "Status: %s" % status print "Content-Type: %s" % mime print def head(uripath): parent = os.path.normpath(os.path.join(uripath, '..')) variables = {'uripath': uripath, 'parent': parent, 'prettypath': uripath.lstrip('/') or '/', 'prettyparent': parent.lstrip('/') or '/'} print format("""\ d8uv.org - $uripath index

$prettypath index:

""", variables) def directory(localpath): desc = os.path.join(localpath, '.description') if os.path.isfile(desc): f = open(desc) print '

%s

' % f.read() f.close() print '' print '' for pathname in sorted(os.listdir(localpath)): path, name = os.path.split(pathname) pathname = os.path.join(localpath, pathname) if name.startswith('.'): continue if not os.path.isdir(name): basename, ext = os.path.splitext(name) if ext == '.html': title = htmltitle(pathname) if title is None: title = basename else: title = basename line = '' print line % (basename, title, modified(pathname)) else: line = '' print line % (name, name) print '
Name:Made on:
%s%s
%s/
' def foot(): print '' print '' def source(scriptname): script = os.path.join(base, '.' + scriptname) f = open(script) print f.read() f.close() sys.exit() def main(): uripath = os.environ.get('REQUEST_URI') scriptname = os.environ.get('SCRIPT_NAME') scriptpath, ext = os.path.splitext(scriptname) if uripath == scriptpath: header(200, 'text/plain') source(scriptname) uripath, filename = os.path.split(uripath) if not uripath.endswith('/'): uripath += '/' localpath = os.path.join(base, '.' + uripath) header(200) head(uripath) directory(localpath) foot() if __name__=="__main__": main()