#DESCRIPTION: convert LaTeX into PNG in MoinMoin wiki
# uses free online service, such as http://ltx4u.net 
# Instructions are for v1.9, runnning wsgi.  Permissions slightly different if running as cgi  
# (1) Drop this file into data/plugin/macro as LTX.py. (should be readable by apache)
# (2) Create a new directory ltxpngs in your public_html directory, writeable by apache
# (3) Create a file ltxlog.html within that directory, writable by apache
# (4) restart wsgi, or restart webserver
# Example usage in MoinMoin wiki: 
# <<LTX(\int_0^\infty e^{-x^2}dx)>>

def execute(macro, eqn):
	import urllib2,md5,os,urllib,time
### start user configuration (set as appropriate):
	ltxurl=r'http://d.ltx4u.net/?' #free external site the converts LaTeX to a PNG  
	ltxdir='/var/www/html/ltxpngs/' #path to store the pngs. (Owner is apache for wsgi)
	ltxlog='ltxlog.html' #name of writable logfile withn ltxdir. (Owner is apache for wsgi)
	httpdir='http://kidcode.us/ltxpngs/' #path for webserver to find the pngs
	pngper=0644 #the permissions required for your webserver to serve the PNG
	pretex=r'\Large ' #optional prepend to all the LaTeX commands you send
### end user configuration
	eqn=urllib.quote(pretex+eqn) # important step to replace blanks by %20
	hx=md5.md5(ltxurl+eqn).hexdigest() # "unique" hex string for PNG file name
	ltxpng=hx+'.png' #the file name
# If the PNG does not exist, go get it from ltxurl: 
	if not os.path.isfile(ltxdir+ltxpng):
		response=urllib2.urlopen(ltxurl+eqn) # connect to PNG service
		data=response.read() # retrieve the PNG
		oup = open(ltxdir+ltxpng,'w') # for writing the PNG on your server
		oup.write(data) # write the PNG file
		oup.close()
		os.chmod(ltxdir+ltxpng,pngper) # change the permissions as needed
		logfile=open(ltxdir+ltxlog,'a') 
		print >>logfile,time.ctime(),ltxurl+eqn,ltxpng # record a log entry 
		logfile.close()
	str='<img src="'+httpdir+ltxpng+'">'  #return this html to your wiki page
	return str or " "
