from StringIO import StringIO
from trac.wiki.formatter import wiki_to_html

def execute(hdf, txt, env):
	db = env.get_db_cnx()
	out = StringIO()
	
	txt = txt or ''
	args = txt.split('|')
	name = args.pop(0).replace('\'', '\'\'')
	sql = "SELECT text from wiki where name = '%s' order by version desc limit 1" % name
	cs = db.cursor()
	cs.execute(sql)
	
	row = cs.fetchone()
	if row == None:
		return ''
	text = row[0]
	
	i = 0
	for arg in args:
		text = text.replace('{{%d}}' % (i+1), args[i])
		i += 1
	
	out.write(wiki_to_html(text, env, None))
	
	return out.getvalue()
