#!/usr/bin/python
import os
import cgi
import sys
import string
import HTMLgen as HT
import md5


passwdset = {"rob":'c14cbc2fbd8635718333a38bde71b5b8', "acenteno":'33b5b53d310a1bbf81a589810ae2f75c', "xwang":'33b5b53d310a1bbf81a589810ae2f75c','wim1':'d99fd5560a2c64e944eaf6400887c201', 'iuser':'32250170a0dca92d53ec9624f336ca24', 'president':'92e4a57be64063328311b8995175d01a', 'presidentelect':'d99fd5560a2c64e944eaf6400887c201', 'pastpresident':'219cedf04ad69b3d78fa2f8a80f4d701', 'treasurer':'14ea3380ecfbededb01a3ba954e93bef', 'secretary':'b36e2aacc5d0d07f3f17ab4d3de13c0d', 'membershipchair':'b6becb2b1fd02a1937f0ca6ebc9053b1', 'memberatlarge1':'3a73e0f41689cc48349bb97928150857', 'memberatlarge2':'1bd4d3aad9d28e35676a9f7119019d26', 'g2beditor':'54cf336cef5196e0424a5b041ea01c1c', 'webmaster1':'1de4a071cd5ab018934f28aa622ee9d2', 'webmaster2':'3ec63ed019cae5a4f98c194b5f098605', 'electionchair':'f5e33c368e6477374fd1f43c7454070e', 'membershipchair':'d547089b94e297ca50cef52a18d6b4c9', 'awardchair':'a0b4551d7b8636fe82cf5e8bf04a59f9'}

cgidir = "/cgi-bin/"
complextrait_org_htmlPath = "/Library/WebServer/complextrait.org/CTCWebsite"
mbl_org_htmlPath = "/Library/WebServer/mbl.org/prombl"
nervenet_org_htmlPath = "/Library/WebServer/nervenet.org"
ibang_org_htmlPath = "/Library/WebServer/ibangs.org/public_html"

htmltemplate = """
<html>
<head>
	<title>Edit HTML (Some Restrictions apply)</title>
	<base href="http://%s/">
	<LINK REL="stylesheet" TYPE="text/css" HREF='http://www.webqtl.org/css/general.css'>
</head>
<script>

function editHTML(thisForm, execCommand){
	if (execCommand == "preview"){
		windowName = 'formTarget' + (new Date().getTime());
		newWindow = open("",windowName,"menubar=1,toolbar=1,location=1,resizable=1,status=1,scrollbars=1,directories=1,width=600");
		newWindow.focus();
		thisForm.target = windowName;
		thisForm.preview.value = "newWindow";
		thisForm.submit();
	}
	else if (execCommand == "submit"){
		windowName = 'formTarget' + (new Date().getTime());
		newWindow = open("",windowName,"menubar=1,toolbar=1,location=1,resizable=1,status=1,scrollbars=1,directories=1,width=600");
		newWindow.focus();
		thisForm.target = windowName;
		thisForm.preview.value = "";
		thisForm.submit();
	}
	else{
	}
}
</script>
<body>
%s
</body>
</html>
"""

print 'Content-type: text/html\n'

if os.environ.has_key('REQUEST_METHOD') and os.environ.has_key('HTTP_REFERER'):
	formdata = cgi.FieldStorage()
	sys.stderr = sys.stdout
	
	path = formdata.getvalue('path')
	preview = formdata.getvalue('preview')
	newHtmlCode = formdata.getvalue('htmlSrc')
	uname = formdata.getvalue('uname')
	passwd = formdata.getvalue('passwd')
	
	#retrieve file to be edited
	refURL = os.environ['HTTP_REFERER']
	import urlparse
	addressing_scheme, network_location, filepath, parameters, query, fragment_identifier = urlparse.urlparse(refURL)
	#print (addressing_scheme, network_location, filepath, parameters, query, fragment_identifier)
	network_location = string.lower(network_location)
	#print network_location
	if string.find(network_location, "complextrait.org")>0:
		htmlPath = complextrait_org_htmlPath
	elif string.find(network_location, "mbl.org")>0:
		htmlPath = mbl_org_htmlPath
	elif string.find(network_location, "nervenet.org")>0:
		htmlPath = nervenet_org_htmlPath
	elif string.find(network_location, "ibangs.org")>0:
		htmlPath = ibang_org_htmlPath
	else:
		print "Error occured while trying to edit the html file."
		sys.exit(0)
		
	if filepath == '/' or filepath == '':
		if string.find(network_location, "ibangs.org")>0:
			filepath = '/index.php'
		else:
			filepath = '/main.html'

		
	fileName = htmlPath + filepath
	
	if newHtmlCode:
		newHtmlCode = string.replace(newHtmlCode,"&amp;nbsp", "&nbsp")
		
	
	if path and preview:
		#preview
		print newHtmlCode
	elif path:
		try:
			if not uname or not passwd:
				raise ValueError
			uname = string.strip(uname)
			passwd = string.strip(passwd)
			if uname not in passwdset.keys() or passwdset[uname] != md5.md5(passwd).hexdigest():
				raise ValueError
				
			#edit result
			fileName =  htmlPath + path
			
			newfileName = fileName +'.old'
			os.system("/bin/cp -f %s %s" % (fileName, newfileName))
			fp = open(fileName, 'wb')
			fp.write(newHtmlCode)
			fp.close()
			os.system("chmod 777 %s" % fileName)
			TD_LR = HT.Paragraph(valign="top",colspan=2,bgcolor="#eeeeee", height=200)
			mainTitle = HT.Paragraph("Edit HTML")
			mainTitle.__setattr__("class","title")
			url = HT.Href(text = "page", url =path, cssclass = "normal", target="_blank")
			intro = HT.Blockquote("This ",url, " has been succesfully modified. ")
			TD_LR.append(mainTitle, intro)
			print htmltemplate % (network_location, TD_LR)
		except:
			print "You don't have permission to modify this page. <BR> Please enter correct username and password."
	else:	
		fp = open(fileName,'rb')
		htmlCode = fp.read()
		htmlCode = string.replace(htmlCode, "&nbsp","&amp;nbsp")
		fp.close()
		form = HT.Form( cgi= cgidir + 'edithtml.py', name='editHtml',submit=HT.Input(type='hidden'))
		inputBox = HT.Textarea(name='htmlSrc', cols="100", rows=30,text=htmlCode)
		
		hddn = {'FormID':'editHtml', 'path':filepath, 'preview':''}
		for key in hddn.keys():
			form.append(HT.Input(name=key, value=hddn[key], type='hidden'))
		userField = HT.Input(type='text',name='uname', size=12, maxlength=40)
		passwdField = HT.Input(type='password',name='passwd', size=12, maxlength=40)
		previewButton = HT.Input(type='button',name='previewhtml', value='Preview',cssclass="button", onClick= "editHTML(this.form, 'preview');")
		submitButton = HT.Input(type='button',name='submitchange', value='Submit Change',cssclass="button", onClick= "editHTML(this.form, 'submit');")
		resetButton = HT.Input(type='reset',cssclass="button")
		form.append(HT.Center(inputBox, HT.P(),"User Name : ", userField, "&nbsp;"*5, "Password : ", passwdField, HT.P(), previewButton, submitButton, resetButton))
		
		TD_LR = HT.Paragraph()
		mainTitle = HT.Paragraph("Edit HTML")
		mainTitle.__setattr__("class","title")
		intro = HT.Blockquote("You may edit the HTML source code in the editbox below, or you can copy the content of the editbox to your favorite HTML editor. ")
		intro2 = HT.Blockquote(HT.Strong("File Path : %s " % fileName))
		if htmlPath == ibang_org_htmlPath:
			intro3 = HT.Blockquote("To upload files, please click ", HT.Href(url = "http://www.ibangs.org/upload/test.html", text="here", target="_blank"), ".")
			intro4 = HT.Blockquote("Getting started with HTML? click ", HT.Href(url = "http://www.w3.org/MarkUp/Guide/", text="here", target="_blank"), ".")
			intro5 = HT.Blockquote("To add comments use the following code <!--Modified by Wim Crusio Sept 1, 2005--> for more information click ", HT.Href(url = "http://www.netmechanic.com/news/vol6/beginner_no17.htm", text="here", target="_blank"), ".")
		else:
			intro3 = ""
			intro4 = ""
			intro5 = ""
		TD_LR.append(mainTitle, intro, intro2, intro3, intro4, intro5, HT.Center(form))
		print htmltemplate % (network_location, TD_LR)
else:
	print "Error occured while trying to edit the html file."
