#!/usr/bin/env python

import sys, os, cgi, cPickle, types #, MySQLdb, md5, time, types
from tools import decodeStr
from cgitools import *
#cgi_token = "Content-type:text/html\n\n"
#error_info = []

data_set = {'password':{'required':0, 'to_decrypt':True, 'to_encrypt':'md5'}, 'password_confirm':{'required':0, 'to_decrypt':True, 'to_encrypt':'md5'}, 'first_name':{'required':1}, 'last_name':{'required':1}, 'email':{'required':1}, 'company':{}, 'street':{}, 'city':{}, 'state':{}, 'zip':{}, 'country':{}, 'phone':{}} # the default value is {'required':0, 'type':'string', 'to_encrypt':'', 'to_upper':0}
field_name = {'password':'user_passwd', 'first_name':'first_name', 'last_name':'last_name', 'company':'company', 'street':'street', 'city':'city', 'state':'state', 'zip':'zip', 'country':'country', 'phone':'phone', 'email':'email'}

def produceStr(v, sep='"'):
	if type(v) is types.StringType: return sep + v + sep
	return repr(v)

my_vars = {'ui_logon':script_path_url+'/ui/logon'}


# read data from cgi form.
form_data = {}
form = cgi.FieldStorage()

orig_values = cPickle.loads(decodeStr(form.getvalue('orig_values')))

rsa_key = ''

t_now = getSec(n=2)

for k,v in data_set.items():
	if form.has_key(k):
		fv = form.getvalue(k)
		if not v.get('to_decrypt', False): fv = fv.strip()
		if not fv:
			if v.get('required', 0): error_info.append("Error: required items (%s) didn't supplied!" % k)
			continue
		if v.get('type', 'string') != 'string': pass # need to some transformation here if there is any data other than string to be used.
		if v.get('to_upper',0): fv = fv.upper()

		if fv == orig_values.get(k, ''): continue
		
		if v.get('to_decrypt', False):
			if rsa_key == '': rsa_key = getRSAkeys()
			if rsa_key: 
				fv = rsaStr(fv, rsa_key[1], rsa_key[2], True, 8, True)
				srv_tag, fv = fv[-4:], fv[:-4]
				t_diff = t_now - Str2Num(srv_tag, hex_str=True)
				if t_diff<0 or t_diff>15: exitWithInfo('Time out error!')

		if v.get('to_encrypt', '') == 'md5': fv = myMD5(fv)
		form_data[k] = fv
	elif v.get('required', 0):
		error_info.append("Error: required items (%s) didn't supplied!" % k)
		#break

# check password
if form_data.has_key('password') and not form_data['password']: del form_data['password']
if form_data.has_key('password') and form_data.has_key('password_confirm') and form_data['password'] != form_data['password_confirm']:
	error_info.append("Error: passwords doesn't match!")

# check other values
for k,v in orig_values.items():
	if form_data.has_key(k) and form_data[k] == v: del form_data[k]

# check email
new_email = None
if form_data.has_key('email'):
	new_email = form_data['email']
	if os.name == 'posix': del form_data['email']
	if not re.match(r'^[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+', new_email): error_info.append('Error: Invalid email address!')

if error_info: exitWithInfo()

if form_data and username not in ('guest', 'demo'): # update db
	kv = []
	for k,v in form_data.items():
		if k in field_name: kv.append("%s=%s" % (field_name[k], produceStr(v)))
	kv = ', '.join(kv)
	sql_statement = ("UPDATE users SET %s WHERE user_name='%s'") % (kv, username)
	inquireDB(sql_statement)
	
if new_email and os.name=='posix': # send confirm email:
	msg = '''To: %s
From: %s
Subject: Confirm registration on WebArray/WebArrayDB

Dear %s:

Please confirm your change of email address - by click the following URL or copy it to a browse's address bar.

%s

Thanks for you interest in WebArray/WebArrayDB.

- WebArray/WebArrayDB
'''
	#msg = "To: %s\nFrom: WebArray at SKCC\nSubject: Confirm registration\n\nDear %s:\n\nPlease confirm your registration - by click the following URL or copy it to a browse's address bar.\n\n%s\n\nThanks for you interest in our analysis system.\n\n- webarray\n"

	from tools import encodeStr
	thd = 'http://%s%s/confirmail/%s' % (http_host, script_path_url, encodeStr(username+'/'+new_email))
	#thd = 'http://'+http_host+'/'+script_path_url+'/confirm/'+encodeStr(form_data['user_id'])
	msg = msg % (new_email, email_admin, form_data.get('first_name', '') or orig_values.get('first_name', username), thd)
	MAIL = '/usr/sbin/sendmail'
	p = os.popen('%s -t' % MAIL, 'w')
	p.write(msg)
	exitcode = p.close()

	print cgi_token

	if exitcode != 0:
		print "An email was send to you. Please check it to confirm your new email (%s), " % new_email
		#print "<p>click <a href='%s'>Here</a> to logon." % my_vars['ui_logon']
	else:
		print '<p> Exit code ', exitcode, '<br>'
	sys.exit(0)

exitWithInfo('<META HTTP-EQUIV="refresh" CONTENT="5;URL=%s">Upated!<p>Wait 5 seconds or click <a href=%s>here</a> to return' % (script_path_url+'/ui/userprofile', script_path_url+'/ui/userprofile'))

#print "click <a href='ui/logon'>Here</a> to logon."
#from

#print cgi.print_environ() 

