1 #!/usr/bin/env python 2 3 """ 4 Handle Confluence wiki requests employing special identifiers that should map to 5 wiki pages. 6 """ 7 8 from urllib import quote 9 import cgi, os, sys 10 11 # Location of the mapping. 12 13 MAPPING_ID_TO_PAGE = "mapping-id-to-page.txt" 14 15 # An empty string means that the wiki is anchored at the site root. 16 17 URL_PREFIX = "" 18 19 # See the scripts/tiny.py program for similar code in a stand-alone program. 20 21 from base64 import b64decode 22 from struct import unpack 23 24 def identifier(s): 25 if len(s) > 6: 26 return None 27 bytes = b64decode(s.replace("-", "/").replace("_", "+") + "=" * (6 - len(s))) 28 return str(unpack("<I", bytes + "\x00" * (4 - len(bytes)))[0]) 29 30 # Utility functions. 31 32 def fail(pageid): 33 print """\ 34 Status: 404 Page not found 35 Content-Type: text/html 36 37 <html> 38 <head><title>Bad Page Identifier</title></head> 39 <body> 40 <h1>Bad Page Identifier</h1> 41 <p>The identifier given in the URL%s does not seem to refer to a page in this wiki.</p> 42 </body> 43 </html> 44 """ % (pageid and " (%s)" % pageid or "") 45 sys.exit(0) 46 47 def redirect(pagename): 48 location = "%s/%s" % (URL_PREFIX, quote(pagename)) 49 50 print """\ 51 Status: 302 Redirect to page 52 Location: %s 53 Content-Type: text/html 54 55 <html> 56 <head><title>Redirecting to Page</title></head> 57 <body> 58 <h1>Redirecting to Page</h1> 59 <p>If you see this message, try following <a href="%s">this link</a>.</p> 60 </body> 61 </html> 62 """ % (location, cgi.escape(location, True)) 63 sys.exit(0) 64 65 def find(f, pageid): 66 for line in f.xreadlines(): 67 columns = line.strip().split("\t") 68 if columns[0] == pageid: 69 redirect(columns[1]) 70 71 def main(): 72 args = cgi.parse_qs(os.environ.get("QUERY_STRING", "")) 73 path = os.environ.get("PATH_INFO", "").strip("/") 74 75 pageid = args.get("pageId", [None])[0] or identifier(path) 76 if pageid is None: 77 fail(pageid) 78 79 f = open(MAPPING_ID_TO_PAGE) 80 try: 81 # With an identifier, find the corresponding page name. 82 83 find(f, pageid) 84 85 # Didn't find the page. 86 87 fail(pageid) 88 89 finally: 90 f.close() 91 92 if __name__ == "__main__": 93 main() 94 95 # vim: tabstop=4 expandtab shiftwidth=4