#!/usr/bin/env python

import dbm, re, cgi, cgitb; cgitb.enable()
f = cgi.FieldStorage()
r = f.has_key('redirect')
q = f['q'].value
from nytutils import cleanLink

def findLink(x):
    db = dbm.open('itemurls.dbm')
    out = db.get(x, None)
    if out and out.lower().startswith('http://select.nytimes.com'): return True
    return out

oq = cleanLink(q)
q = findLink(oq)
if isinstance(q, str): q += '&pagewanted=all'

print "Content-Type: text/html"
if r and q and q is not True:
	print "Status: 301 Redirect"
	print "Location:", q
print
print '<html><head><title>New York Times Link Generator</title><link rel="stylesheet" href="/style.css" /></head><body><h1>New York Times Link Generator</h1>'

if q is True:
    print "<p>That's a <a href='http://select.nytimes.com/'>Times Select</a> article -- you have to subscribe to Times Select to read it.</p>"
elif q:
    print "<p>Here's the archive link for that article:</p>"
    print '<p><a href="'+q+'">'+q+'</a></p>'
    print '<p><code>&lt;a href="'+q.replace('&', '&amp;amp;') + '"&gt;</code></p>'

    print '<p>More info: <a href="http://backend.userland.com/2003/06/16#a265">Accessing the NY Times archive through their RSS feeds</a>.</p>'
else:
    print "<p>Sorry, I couldn't find a link for that article.</p><ol><li>It has to be a proper NYT URL. It should look like this: <code>http://www.nytimes.com/2004/02/19/politics/19RESE.html</code></li><li>The URL can't be too old. (This service only goes back to June 2003.)</li><li>The URL can't be too new. It can take up to an hour for new URLs to be added to this site.</li><li>Maybe it's a special URL. Some pages are special and aren't included in this program. (For example, op-eds under TimesSelect won't work.)</li></ol><p>If even that doesn't work, or you have some other comment, <a href='mailto:me@aaronsw.com'>let us know</a>.</p>"
#<p>Finally, try adding <code>/partner/rssnyt</code> onto the end, as in:</p><p><code>"+oq+"/partner/rssnyt</code></p>

ignore = '''<div style="border: solid 1px red; padding: .3em ">
<p><strong>News:</strong> The server that powers this site has suffered a catastrophic hard drive crash. If you'd like to help support us as we rebuild this and our other sites, feel free to <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=me%40aaronsw%2ecom&item_name=Server+Support">make a donation</a>.</p>
<p>A very special thanks to Jay Beaton for helping us rebuild our links database.</p>
</div>'''

print '<p><a href="genlink">Return to the submission form.</a></p>'

print '<address>Site by <a href="http://www.aaronsw.com/">Aaron Swartz</a> (<a href="_genlink.py">source code</a>); content by <a href="http://www.nytimes.com/">the New York Times</a>.</address></body></html>'
