#! /usr/bin/python
# pastebin.py 
#
# Written by Arne Schwabe <arne@rfc2549.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.


import MySQLdb
import cgi
import cgitb
import time
import pythoncolor
#cgitb.enable()

fs = cgi.FieldStorage()

db = MySQLdb.connect(user="arne",passwd="gummibaum",db="arne")
c = db.cursor()


print "Content-Type: text/html\n"

def printheader():
	print """<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
	<title>python pastebin - collaborative irc debugging</title>
	<link rel="stylesheet" type="text/css" media="screen" href="pastebin.css" />
	</head>


	<body>

	<p style="display: none;">This site is developed to XHTML and CSS2 W3C standards.
	If you see this paragraph, your browser does not support those standards and you
	need to upgrade.  Visit <a href="http://www.webstandards.org/upgrade/" >WaSP</a>
	for a variety of options.</p>

	<div id="titlebar">pastebin - collaborative irc debugging - Layout and Idea from <a href="pastebin.com">pastebin.com</a>
	<a href="pastebin.py?id=1" class="alt">view source</a>
	</div>
	<div id="menu">
	<h1>Recent Posts</h1>
	"""
	printrecent()
	
	print """
	<form method="get" action="modindex.py">
	<h1>Python Module Index</h1>
	<input type="text" size="14" name="module"/>
	<input type="submit" value="go"/>
	</form>
	"""

	"""
	<form method="get" action="http://www.php.net/search.php">
	<h1>PHP Manual</h1>
	<input type="text" size="9" name="pattern"/>
	<input type="hidden" name="show" value="quickref"/>
	<input type="submit" value="go"/>
	</form>
	"""



	"""<form method="get" action="http://www.mysql.com/doc/search.php">
	<h1>MySQL Manual</h1>
	<input type="text" size="9" name="q"/>
	<input type="submit" value="go"/>
	</form>"""
	print """
	<p>
	   <a href="http://validator.w3.org/check/referer"><img
			src="http://www.w3.org/Icons/valid-xhtml10"
		   alt="Valid XHTML 1.0!" height="31" width="88" border="0"/></a>
	</p>

	</div>

	<div id="content">"""


def printnew():
	print """<h1>New posting</h1><form name="editor" method="post" action="pastebin.py">
	<b>Name</b><br />
	<input type="text" maxlength="20" size="20" name="who" value="" />
	<input type="submit" name="paste" value="Send"/>
<br />
	<select name="typ">
	
	<option value="python">Python</option>
	<option value="plaintext">Plain Text</option>
	</select>
	<br />
	<!-- <input type="checkbox" name="remember" value="1" />Remember my name in a cookie -->
	<br /><br />
	
	<b>Code:</b> To ensure legibility, keep your code lines under 80 characters long.<br />
	Include comments to indicate what you need feedback on.<br />
	<textarea class="codeedit" name="code" cols="80" rows="10">
	</textarea>

	</form>
	"""


def printrecent():
	print "<ul>"
	c.execute("SELECT id,who,datetime FROM pastebin ORDER BY datetime DESC LIMIT 10")
	for result in c.fetchall():
		print "<li><a href=\"pastebin.py?id=%d\">%s</a><br />	%s</li>" % (result[0:2]+ (format_date(result[2]),))

	print "</ul>"
	print "<a href=\"pastebin.py\">New paste</a>"
	
def newpost(pasted):
	pasted = pasted[:7048]
	if len(pasted) < 20:
		print "Pasted text is shorter then 20 chars"
	else:
		who = fs.getfirst("who","Anonymous")
		typ = fs.getfirst("typ","plaintext")
		c.execute("INSERT INTO pastebin (who,text,datetime,typ) VALUES (%s,%s,now(),%s)",(who,pasted,typ))
		c.execute("SELECT id FROM pastebin ORDER BY datetime DESC LIMIT 1")
		result = c.fetchone()
		print "Access your paste under <a href=\"pastebin.py?id=%d\">pastebin.de/?id=%d</a>" % (result + result)
		

def printmain():
	pasted = fs.getfirst("code",None)
	if pasted:
		newpost(pasted)
	else:
		try:
			id = int(fs.getfirst("id","0"))
		except Exception:
			id = 0
		if id:
			printcode(id)
		else:
			printnew()

def addlines(code):
	rstr = ''
	i = 0
	for line in code.split("\n"):
		i += 1
		rstr += "<span class=\"cl\"> %03d </span> %s\n" % (i,line)

	return rstr
	

def format_date(date):
	pt = int(date.ticks())

	at = int( time.time())
	td = at -pt

	min = True
	tstr = ""
	if td > 86400:
		tstr = "%d days " % ((td + 86400) / (3600*24)) 
		td = td % 86400
		min = False
	if td > 3600:
		tstr += "%d h " % ((td + 3600) / 3600) 
		td = td % 3600
		
	if td > 60 and min:
		tstr += "%d min " % ((td + 60) / 60)

	tstr += " ago"
		

	return tstr
	
	

def printcode(id):
	if id ==1:
		code = file("pastebin.py").read()
		code =code.replace("gummibaum","hidden")
		# To hide the password
		time = ""
		who = "Arne Schwabe"
		typ = "python"
		
	else:
		c.execute("SELECT who,datetime,text,typ FROM pastebin where id=%s", id)
		result = c.fetchone()
		if result == None:
			print "ID <b>%d</b> not found in database" % id
			return
		time = format_date(result[1])
		who = cgi.escape(result[0])
		code = result[2]
		typ = result[3]

	#code= cgi.escape(code)
	if typ  == "python":
		code =pythoncolor.Parser(code).format()


	
	code = addlines(code)
	print """<h1>Posted by %s %s</h1><pre><code>%s</code></pre>""" % (who,time,code)
	
	

def printfooter():
	print """
	</div>

	</body>
	</html>
	"""
def main():
	printheader()
	printmain()
	printfooter()


if __name__=="__main__":
	main()
