#!/usr/bin/python """Simple CGI to implement blogthis-style bookmarklets. Useful for keeping a lightweight list of websites you like, such as for a linkblog. http://www.nelson.monkey.org/~nelson/weblog/ Takes several URL quoted arguments: t Title of a page u URL of a page q A quote selected from page n The name of the user who created the entry These arguments are then appended to a tab separated datafile. Some light cleansing of the arguments is applied Name is checked against trustedNames, and the entry is only recorded if the name matches. This is a light form of security. Also a special hack - if the argument 'p=name' is passed in to CGI, emit HTML that contains the bookmarklet for the given name. """ import cgi, re, os, time import cgitb; cgitb.enable() # List of trusted names trustedNames = ['nelson'] # Where to write the output datafile = "/home/nelson/blosxom/linkblog/entries/links.dat" def recordData(): "Parse out the CGI paramters and store them in a file" stripRE = re.compile(r'[\r\n\t]') # these get replaced with ' ' title = stripRE.sub(' ', formdata.getfirst('t', '')) url = stripRE.sub(' ', formdata.getfirst('u', '')) quote = stripRE.sub(' ', formdata.getfirst('q', '')).strip() name = stripRE.sub(' ', formdata.getfirst('n', '')) now = int(time.time()) ip = os.environ['REMOTE_ADDR'] if name not in trustedNames: print 'Content-Type: text/plain\r\n\r\nName %s not trusted.\r\n' % name return fp = file(datafile, "a+") fp.write("%d\t%s\t%s\t%s\t%s\t%s\n" % (now, name, ip, url, title, quote)) fp.close() print 'Content-Type: text/plain' print print '%s\r\n%s\r\n%s\r\n%s\r\n' % (quote, title, url, name) def strippedBookmarklet(myURL, name): "Return the bookmarklet stripped to one line" s = bookmarklet % (myURL, name) return s, re.sub(r'[\r\n ]', '', s) def emitBookmarklet(myURL, name): "Emit the bookmarklet as HTML" (textBM, bm) = strippedBookmarklet(myURL, name) print 'Content-Type: text/html\r\n' print 'Note Bookmarklet' print 'Bookmarklet' % bm print '

%s
' % textBM print '' bookmarklet=""" d=document; t=d.selection ? d.selection.createRange().text : d.getSelection(); t=window.prompt('Note:', t); void( window.open('%s' + '?t=' + escape(d.title) + '&u=' + escape(d.location.href) + '&q=' + escape(t) + '&n=' + escape('%s'), '_blank', 'width=250,height=165') ); """ # Invoke in one of two modes: CGI &p=, or CGI normal formdata = cgi.FieldStorage() myURL = "http://%s%s" % (os.environ['SERVER_NAME'], os.environ['SCRIPT_NAME']) if formdata.has_key('p'): emitBookmarklet(myURL, formdata.getfirst('p')) elif formdata.has_key('u'): recordData() else: raise "You didn't invoke this right"