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