<?php
ini_set("display_errors","1");
ini_set("display_startup_errors","1");
set_magic_quotes_runtime(0);

include("oldinclude/dbcommon.php");
include("oldinclude/##@TABLE.strShortTableName##_variables.php");
##if @BUILDER.arrLanguages.len>1##
include("oldinclude/languages.php");
##endif##


$registered=false;
$onload=' ';
$strMessage="";
$strUsername="";
$strPassword="";
$strEmail="";
$values=array();

include('oldlibs/Smarty.class.php');
$smarty = new Smarty();

$conn=db_connect();

//	Before Process event
if(function_exists("BeforeProcessRegister"))
	BeforeProcessRegister($conn);

##if @BUILDER.bSendActivationLink##
if(@$_GET["a"]=="activate")
{
	$username=base64_decode(@$_GET["u"]);
	$code = @$_GET["code"];
	$strUsername = make_db_value("##@BUILDER.strUserNameField s##",$username);
	$sql = "select ##@BUILDER.strPasswordField ws## from ##@BUILDER.strLoginTable ts## where ##@BUILDER.strUserNameField ws##=".$strUsername;
	$rs = db_query($sql,$conn);
	$verified=false;
##if @BUILDER.bEncryptPasswords##
	if(!$rs || !($data = db_fetch_numarray($rs)) || $code!=md5($username.$data[0]))
##else##
	if(!$rs || !($data = db_fetch_numarray($rs)) || $code!=md5($username.md5($data[0])))
##endif##
	{
		echo ##message SEC_INVALID_REG_CODE##;
		return;
	}
	$sql = "update ##@BUILDER.strLoginTable ts## set ##@BUILDER.strActivationField ws##=1 where ##@BUILDER.strUserNameField ws##=".$strUsername;
	db_exec($sql,$conn);

	$smarty->assign("username",htmlspecialchars($username));
##if !@BUILDER.bEncryptPasswords##
	$smarty->assign("password",htmlspecialchars($data[0]));
##endif##
	$smarty->assign("activated",true);
	$smarty->display("register_success.htm");
	return;
}
##endif##

if(@$_POST["btnSubmit"] == "Register")
{

##if @BUILDER.bCaptcha##
	if(@strtolower(@$_POST["captcha"])!=strtolower(@$_SESSION["captcha"]))
		$strMessage=##message SEC_INVALID_CAPTCHA_CODE##;
##endif##

	$filename_values=array();
##if @BUILDER.nDatabaseType==DATABASE_Oracle##
	$blobs=array();
##endif##
	$files_move=array();

##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach Fields as @f filter @f.strName==@uf##
//	processing ##@f.strName## - start

	$value = postvalue("value_##@f.strName g##");
	$type=postvalue("type_##@f.strName g##");
	if (in_assoc_array("type_##@f.strName g##",$_POST) || in_assoc_array("value_##@f.strName g##",$_POST) || in_assoc_array("value_##@f.strName g##",$_FILES))
	{
##if @f.strEditFormat==EDIT_FORMAT_DATABASE_FILE && @f.ListFormatObj.strFilename##
		$value=prepare_for_db("##@f.strName s##",$value,$type,postvalue("filename_##@f.strName g##"));
##else##
		$value=prepare_for_db("##@f.strName s##",$value,$type);
##endif##
	}
	else
		$value=false;
	if(!($value===false))
	{
##if @f.bCreateThumbnail && (@f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE || @f.strEditFormat==EDIT_FORMAT_FILE)##
		if($value)
		{
	##if @f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE##
			$ext = CheckImageExtension($_FILES["value_##@f.strName g##"]["name"]);
			$thumb = CreateThumbnail($value,##@f.nThumbnailSize##,$ext);
		##if @BUILDER.nDatabaseType==DATABASE_Oracle##
			$blobs["##@f.strThumbnail s##"]=$thumb;
			$values["##@f.strThumbnail s##"]="EMPTY_BLOB()";
		##else##
			$values["##@f.strThumbnail s##"]=$thumb;
		##endif##
	##else##
			$ext = CheckImageExtension($_FILES["file_##@f.strName g##"]["name"]);
			$contents = myfile_get_contents($_FILES["file_##@f.strName g##"]['tmp_name']);
			$thumb = CreateThumbnail($contents,##@f.nThumbnailSize##,$ext);
			$file = GetUploadFolder("##@f.strName s##")."##@f.strThumbnail s##".$value;
			if(file_exists($file))
					@unlink($file);
			$th = fopen($file,"w");
			fwrite($th,$thumb);
			fclose($th);
	##endif##
		}
##endif##
##if @BUILDER.nDatabaseType==DATABASE_Oracle && (@f.strEditFormat==EDIT_FORMAT_DATABASE_FILE || @f.strEditFormat==EDIT_FORMAT_DATABASE_IMAGE)##
		$blobs["##@f.strName s##"]=$value;
		$values["##@f.strName s##"]="EMPTY_BLOB()";
##else##
		$values["##@f.strName s##"]=$value;
##endif##
	}
##if @f.strEditFormat==EDIT_FORMAT_DATABASE_FILE && @f.ListFormatObj.strFilename##
	if($filename)
		$filename_values["##@f.ListFormatObj.strFilename s##"]=$filename;
##endif##			

//	processibng ##@f.strName## - end

##endfor##
##endfor##

	$strUsername = $values["##@BUILDER.strUserNameField s##"];
	$strPassword = $values["##@BUILDER.strPasswordField s##"];
##if @BUILDER.strUserEmailField##
	$strEmail = $values["##@BUILDER.strUserEmailField s##"];
##endif##


//	add filenames to values
	foreach($filename_values as $key=>$value)
		$values[$key]=$value;

//	check if entered username already exists
	if(!strlen($strUsername))
	{
		if($strMessage)
			$strMessage.="<br>";
		$strMessage.=##message USER_NOEMPTY##;
	}
	else
	{
		$strSQL="select count(*) from ##@BUILDER.strLoginTable ts## where ##@BUILDER.strUserNameField ws##=".add_db_quotes("##@BUILDER.strUserNameField s##",$strUsername);
	   	$rs=db_query($strSQL,$conn);
		$data=db_fetch_numarray($rs);
		if($data[0]>0)
		{
			if($strMessage)
				$strMessage.="<br>";
			$strMessage.=##message USERNAME_EXISTS1##." <i>".$strUsername."</i> ".##message USERNAME_EXISTS2##;
		}
	}

##if @BUILDER.bRemindPwdPage##
//	check if entered email already exists
	
	if(!strlen($strEmail))
	{
		if($strMessage)
			$strMessage.="<br>";
		$strMessage.=##message VALID_EMAIL##;
	}
	else
	{
		$strSQL="select count(*) from ##@BUILDER.strLoginTable ts## where ##@BUILDER.strUserEmailField ws##=".add_db_quotes("##@BUILDER.strUserEmailField s##",$strEmail);
	   	$rs=db_query($strSQL,$conn);
		$data=db_fetch_numarray($rs);
		if($data[0]>0)
		{
			if($strMessage)
				$strMessage.="<br>";
			$strMessage.=##message EMAIL_ALREADY1##." <i>".$strEmail."</i> ".##message EMAIL_ALREADY2##;
		}
	}
##endif##
##if @BUILDER.bSendActivationLink##
	$values["##@BUILDER.strActivationField s##"]=0;
##endif##

##if @BUILDER.bStrongPassword##
	if(!checkpassword($values["##@BUILDER.strPasswordField s##"]))
	{
		$msg="";
##if @BUILDER.nPwdLen##
		$fmt=##message SEC_PWD_LEN##;
		$fmt=str_replace("%%","##@BUILDER.nPwdLen##",$fmt);
		$msg.="<br>".$fmt;
##endif##
##if @BUILDER.nPwdUnique##
		$fmt=##message SEC_PWD_UNIQUE##;
		$fmt=str_replace("%%","##@BUILDER.nPwdUnique##",$fmt);
		$msg.="<br>".$fmt;
##endif##
##if @BUILDER.nPwdDigits##
		$fmt=##message SEC_PWD_DIGIT##;
		$fmt=str_replace("%%","##@BUILDER.nPwdDigits##",$fmt);
		$msg.="<br>".$fmt;
##endif##
##if @BUILDER.bPwdUpperLower##
		$fmt=##message SEC_PWD_CASE##;
		$msg.="<br>".$fmt;
##endif##
	if($msg)
		$msg=substr($msg,4);
	if($strMessage)
		$strMessage.="<br>";
	$strMessage.=$msg;
	}
		
##endif##	
	$retval=true;
	if(!$strMessage)
	{
		if(function_exists("BeforeRegister"))
			$retval = BeforeRegister($values);
	}

	if(!$strMessage && $retval)
	{

##if @BUILDER.bEncryptPasswords##
	//	encrypt password
	$originalpassword=$values["##@BUILDER.strPasswordField s##"];
	$values["##@BUILDER.strPasswordField s##"]=md5($values["##@BUILDER.strPasswordField s##"]);
##endif##
//	make SQL string
		$strSQL = "insert into ##@BUILDER.strLoginTable ts## ";
		$strFields="(";
		$strValues="(";
		foreach($values as $akey=>$value)
		{
			$strFields.=AddFieldWrappers($akey).", ";
##if @BUILDER.bSendActivationLink##
			if($akey!="##@BUILDER.strActivationField s##")
				$strValues.=add_db_quotes($akey,$value).", ";
			else
				$strValues.=$value.", ";
##else##
			$strValues.=add_db_quotes($akey,$value).", ";
##endif##
		}
		if(substr($strFields,-2)==", ")
			$strFields=substr($strFields,0,strlen($strFields)-2);
		if(substr($strValues,-2)==", ")
			$strValues=substr($strValues,0,strlen($strValues)-2);
		$strSQL.=$strFields.") values ".$strValues.")";
//	insert new user
##if @BUILDER.nDatabaseType==DATABASE_Oracle##
		$locs=array();
		if(count($blobs))
		{
			$strSQL.=" returning ";
			$blobfields="";
			$blobvars="";
			foreach($blobs as $akey=>$value)
			{
				if(count($locs))
				{
					$blobfields.=",";
					$blobvars.=",";
				}
				$blobfields.=AddFieldWrappers($akey);
				$blobvars.=":".GoodFieldName($akey);
				$locs[$akey]=OCINewDescriptor($conn, OCI_D_LOB);
			}
			$strSQL.=$blobfields." into ".$blobvars;
		}
		$stmt=OCIParse($conn,$strSQL);
		foreach($locs as $akey=>$value)
		{
			OCIBindByName($stmt,":".GoodFieldName($akey),$locs[$akey],-1,OCI_B_BLOB);
		}
		LogInfo($strSQL);
		OCIExecute($stmt, OCI_DEFAULT);
		foreach($locs as $akey=>$value)
		{
			$locs[$akey]->save($blobs[$akey]);
			$locs[$akey]->free();
		}
		OCICommit($conn);
		OCIFreeStatement($stmt);
##else##
		LogInfo($strSQL);
		db_exec($strSQL,$conn);
##endif##

		foreach ($files_move as $file)
			move_uploaded_file($file[0],$file[1]);

##if @BUILDER.bEncryptPasswords##
	$values["##@BUILDER.strPasswordField s##"]=$originalpassword;
##endif##

		if(function_exists("AfterSuccessfulRegistration"))
			AfterSuccessfulRegistration($values);

		$url = "http://".$_SERVER["SERVER_NAME"];
		if($_SERVER["SERVER_PORT"]!=80)
			$url.=":".$_SERVER["SERVER_PORT"];
		$url.=$_SERVER["SCRIPT_NAME"];
##if @BUILDER.bNotifyUser##
//	send email to user
		$message=##message REGMAIL_USER1##." ".$url."\r\n\r\n";
##if @BUILDER.bSendActivationLink##
		$message.= ##message REGMAIL_USER2##.":\r\n";
		$message.= $url."?a=activate&u=".rawurlencode(base64_encode($values["##@BUILDER.strUsernameField s##"]))."&code=";
		$message.=rawurlencode(md5($values["##@BUILDER.strUsernameField s##"].md5($values["##@BUILDER.strPasswordField s##"])));
		$message.="\r\n(".##message REGMAIL_USER3##.")\r\n\r\n";
##endif##
##foreach @BUILDER.Registration.arrUserFields as @f##
		$label = "##Fields[strName==@f].strLabel s##";
		$message.=$label.": ".$values["##@f s##"]."\r\n";
##endfor##
		if(($pos=strpos($strEmail,"\r"))!==FALSE || ($pos=strpos($strEmail,"\n"))!==FALSE)
			$strEmail=substr($strEmail,0,$pos);
		mail($strEmail,##message REGMAIL_USER4##,$message);
##endif##

##if @BUILDER.bNotifyAdmin##
//	send letter to admin
		$message=##message REGMAIL_ADMIN1##." ".$url."\r\n";
##foreach @BUILDER.Registration.arrUserFields as @f##
		$label = "##Fields[strName==@f].strLabel s##";
		$message.=$label.": ".$values["##@f s##"]."\r\n";
##endfor##
		mail("##@BUILDER.strAdminEmail s##",##message REGMAIL_USER4##,$message);
##endif##
//	show Registartion successful message
		$smarty->assign("username",htmlspecialchars($strUsername));
		$smarty->assign("password",htmlspecialchars($strPassword));
##if @BUILDER.bSendActivationLink##
		$smarty->assign("email",$strEmail);
		$smarty->assign("activated",false);
##endif##
		$smarty->display("register_success.htm");
		return;
	}
	else
	{
		if(function_exists("AfterUnsuccessfulRegistration"))
			AfterUnsuccessfulRegistration($values);
	}
	$smarty->assign("message",$strMessage);
}

//	validation stuff
$bodyonload="";
$onsubmit="";
$includes="";


$includes.="<script language=\"JavaScript\" src=\"oldinclude/validate.js\"></script>\r\n";
$includes.="<script language=\"JavaScript\">\r\n";
$includes.="var TEXT_FIELDS_REQUIRED='".addslashes(##message FIELDS_REQUIRED##)."';\r\n";
$includes.="var TEXT_FIELDS_ZIPCODES='".addslashes(##message FIELDS_ZIPCODES##)."';\r\n";
$includes.="var TEXT_FIELDS_EMAILS='".addslashes(##message FIELDS_EMAILS##)."';\r\n";
$includes.="var TEXT_FIELDS_NUMBERS='".addslashes(##message FIELDS_NUMBERS##)."';\r\n";
$includes.="var TEXT_FIELDS_CURRENCY='".addslashes(##message FIELDS_CURRENCY##)."';\r\n";
$includes.="var TEXT_FIELDS_PHONE='".addslashes(##message FIELDS_PHONE##)."';\r\n";
$includes.="var TEXT_FIELDS_PASSWORD1='".addslashes(##message FIELDS_PASSWORD1##)."';\r\n";
$includes.="var TEXT_FIELDS_PASSWORD2='".addslashes(##message FIELDS_PASSWORD2##)."';\r\n";
$includes.="var TEXT_FIELDS_PASSWORD3='".addslashes(##message FIELDS_PASSWORD3##)."';\r\n";
$includes.="var TEXT_FIELDS_STATE='".addslashes(##message FIELDS_STATE##)."';\r\n";
$includes.="var TEXT_FIELDS_SSN='".addslashes(##message FIELDS_SSN##)."';\r\n";
$includes.="var TEXT_FIELDS_DATE='".addslashes(##message FIELDS_DATE##)."';\r\n";
$includes.="var TEXT_FIELDS_TIME='".addslashes(##message FIELDS_TIME##)."';\r\n";
$includes.="var TEXT_FIELDS_CC='".addslashes(##message FIELDS_CC##)."';\r\n";
$includes.="var TEXT_FIELDS_SSN='".addslashes(##message FIELDS_SSN##)."';\r\n";
$includes.="</script>\r\n";

##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach Fields as @f filter @f.strName==@uf && NeedValidation(@f)##
##if @f.strEditFormat!=EDIT_FORMAT_TEXT_FIELD && @f.strEditFormat!=EDIT_FORMAT_TIME##
	$validatetype="";
##else##
  ##if @f.EditFormatObj.strValidateAs==VALIDATE_AS_NUMBER##
	$validatetype="IsNumeric";
  ##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_PASSWORD##
	$validatetype="IsPassword";
  ##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_EMAIL##
	$validatetype="IsEmail";
  ##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_CURRENCY##
	$validatetype="IsMoney";
  ##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_ZIPCODE##
	$validatetype="IsZipCode";
  ##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_PHONENUMBER##
	$validatetype="IsPhoneNumber";
  ##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_STATE##
	$validatetype="IsState";
  ##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_SSN##
	$validatetype="IsSSN";
  ##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_CC##
	$validatetype="IsCC";
  ##elseif @f.EditFormatObj.strValidateAs==VALIDATE_AS_TIME##
	$validatetype="IsTime";
  ##else##
	$validatetype="";
  ##endif##
##endif##
##if @f.EditFormatObj.bRequired##
	$validatetype.="IsRequired";
##endif##
	if($validatetype)
		$bodyonload.="define('value_##@f.strName g##','".$validatetype."','##@f.strLabel js##');";
##endfor##
##endfor##

if($bodyonload)
{
	$onsubmit="return validate();";
	$bodyonload="onload=\"".$bodyonload."\"";
}

$includes.="<script language=\"JavaScript\" src=\"oldinclude/jquery.js\"></script>\r\n";
if ($useAJAX) {
	$includes.="<script language=\"JavaScript\" src=\"oldinclude/ajaxsuggest.js\"></script>\r\n";
}
$includes.="<script language=\"JavaScript\" src=\"oldinclude/jsfunctions.js\"></script>\r\n";
$includes.="<script language=\"JavaScript\">\r\n".
"var locale_dateformat = ".$locale_info["LOCALE_IDATE"].";\r\n".
"var locale_datedelimiter = \"".$locale_info["LOCALE_SDATE"]."\";\r\n".
"var bLoading=false;\r\n".
"var TEXT_PLEASE_SELECT='".addslashes(##message PLEASE_SELECT##)."';\r\n";
$includes.="</script>\r\n";
if ($useAJAX) {
	$includes.="<div id=\"search_suggest\"></div>\r\n";
}

##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach Fields as @f filter @f.strName==@uf && UseCalendar(@f)##
	##if @first##
//	include datepicker files
$includes.="<script language=\"JavaScript\" src=\"oldinclude/calendar.js\"></script>\r\n";
	##endif##
##endfor##
##endfor##


##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach Fields as @f filter @f.strName==@uf && UseRTEBASIC(@f)##
	##if @first##
//	include Rich Text Editor files
$includes.="<script language=\"JavaScript\" type=\"text/javascript\" src=\"oldinclude/richtext.js\"></script>\r\n";
$includes.="<script language=\"JavaScript\">\r\n";
$includes.="var TEXT_VIEW_SOURCE='".addslashes(##message VIEW_SOURCE##)."';\r\n";
$includes.="initRTE('oldinclude/images/', 'oldinclude/', '');\r\n";
$includes.="</script>\r\n";
$onsubmit="updateRTEs();".$onsubmit;
	##endif##
##endfor##
##endfor##


##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach Fields as @f filter @f.strName==@uf && UseRTEFCK(@f)##
##if @first##
include("plugins/fckeditor/fckeditor.php");
##endif##
##endfor##
##endfor##

##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach Fields as @f filter @f.strName==@uf && UseRTEINNOVA(@f)##
##if @first##
$includes .= "<script language=\"Javascript\" src=\"plugins/innovaeditor/scripts/innovaeditor.js\"></script>";
##endif##
##endfor##
##endfor##


$smarty->assign("includes",$includes);
$smarty->assign("bodyonload",$bodyonload);
if(strlen($onsubmit))
	$onsubmit="onSubmit=\"".$onsubmit."\"";
$smarty->assign("onsubmit",$onsubmit);

//	assign values to the controls

if(!count($values))
{
##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach Fields as @f filter @f.strName==@uf && @f.strDefaultValue.len order @f.nAddPageOrder##
	$values["##@f.strName s##"]=##@f.strDefaultValue##;
##endfor##
##endfor##
}

##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach Fields as @f filter @f.strName==@uf && !IsBinaryField(@f) order @f.nAddPageOrder##
$smarty->assign("value_##@f.strName g##",@$values["##@f.strName s##"]);
##endfor##
##endfor##


$readonlyfields=array();

//	show readonly fields
##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach Fields as @f filter @f.strName==@uf && @f.strEditFormat==EDIT_FORMAT_READONLY##
##if @f.strViewFormat==FORMAT_HTML || @f.strViewFormat==FORMAT_FILE_IMAGE || @f.strViewFormat==FORMAT_FILE || @f.strViewFormat==FORMAT_HYPERLINK || @f.strViewFormat==FORMAT_EMAILHYPERLINK || @f.strViewFormat==FORMAT_CHECKBOX##
	$readonlyfields["##@f.strName s##"] = GetData($values,"##@f.strName s##", "##@f.strViewFormat##");
##else##
	$readonlyfields["##@f.strName s##"] = htmlspecialchars(GetData($values,"##@f.strName s##", "##@f.strViewFormat##"));
##endif##
##endfor##
##endfor##

$linkdata="";


$linkdata .= "<script type=\"text/javascript\">\r\n";

if ($useAJAX) {
##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach @TABLE.arrFieldObj as @f filter @f.strName==@uf && @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.bUseCategory##
		$output = loadSelectContent("##@f.strName s##",@$values["##@f.strCategoryControlField s##"],@$values["##@f.strName s##"]);
		$txt = ""; 
		foreach( $output as $value ) {
			$txt .= jsreplace($value)."\\n";
		}
		$linkdata .= "preloadSelectContent('".$txt."', 'value_##@f.strName g##', '".jsreplace(@$values["##@f.strName s##"])."','');\r\n";
##endfor##
##endfor##
}
else
{
##foreach @BUILDER.Registration.arrUserFields as @uf##
##foreach @TABLE.arrFieldObj as @f filter @f.strName==@uf && @f.strEditFormat==EDIT_FORMAT_LOOKUP_WIZARD && @f.bUseCategory##
	//	##@f.strName## - ##@f.strCategoryControlField##
	$linkdata.="bLoading = true;";
	$linkdata.="SetSelection('value_##@f.strCategoryControlField g##', 'value_##@f.strName g##', '".jsreplace(@@$values["##@f.strCategoryControlField s##"])."', '".jsreplace(@$values["##@f.strName s##"])."', arr_##@f.strName g##);";
	$linkdata.="bLoading = false;";
##endfor##
##endfor##
}
$linkdata.="</script>\r\n";


$smarty->assign("linkdata",$linkdata);

$smarty->assign("submitonclick","onclick=\"javascript: if (document.forms.editform.value1_##@BUILDER.strPasswordField g##==undefined) return true; if(document.forms.editform.value_##@BUILDER.strPasswordField g##.value != document.forms.editform.value1_##@BUILDER.strPasswordField g##.value) {alert('".##message DONT_MATCH##."');document.forms.editform.value1_##@BUILDER.strPasswordField g##.value='';return false;} return true;\"");

$templatefile="register.htm";
if(function_exists("BeforeShowRegister"))
	BeforeShowRegister($smarty,$templatefile);

$smarty->display($templatefile);

?>