<?php
/*
 * \SentraDesigner\fills\Form\render.scripts\script.vtd.php
 */
If (defined('ErrorLogging_ALL')) {
	error_reporting(E_ALL);		// trap everything!
	ini_set('display_errors', TRUE);
	ini_set('html_errors', TRUE);
}
If (!defined('I_am_Online')) {
	define ("I_am_Online",'TRUE');
}
If (substr(PHP_OS,0,3) == 'WIN') {
	If (!function_exists('getmxrr')) {
		function getmxrr($hostname, &$mxhosts) {
  		$mxhosts = array();
  		exec('nslookup -type=mx '.$hostname, $result_arr);
  		foreach($result_arr as $line) {
				if (preg_match("/.*mail exchanger = (.*)/", $line, $matches))
					$mxhosts[] = $matches[1];
  	  }
  	 	return( count($mxhosts) > 0 );
		}//--End of workaround
	}
}
$GLOBALS["sendemailto"] = 'undefined';
$GLOBALS["uploadedsrc"] = array();
$GLOBALS["uploadeddest"] = array();
$GLOBALS["uploadready"] = false;
$GLOBALS["FORMvars"] = array();

$files2delete = array();
$TotalWidth = '100';
$LeftWidth 	= '25';
$RightWidth = '75';

require_once(SENTRA_SCRIPT_HOME.'formgriddy.class.php');
$FormGriddy = new FormGriddy(array($LeftWidth,$RightWidth),$TotalWidth);

require_once(SENTRA_SCRIPT_HOME."form_file_io.php");
require_once(SENTRA_SCRIPT_HOME."form.class.functions.php");
require_once(SENTRA_SCRIPT_HOME."gen.form.class.php");

// Create or retrieve the unique UserID which is an ID allocated to a certain visitor
// Collect user input vars from POST & GET ports
$GETPOSTvars = $_REQUEST;
#$GETPOSTvars = array_merge($_POST, $_GET);

If (isset($GETPOSTvars['MyUserID_{{ID}}'])) {
	$UserID = $GETPOSTvars['MyUserID_{{ID}}'];
} Else {
	$UserID=md5(uniqid(rand(),true));
	$UserID = str_replace(".","",form_get_real_ip())."__".md5(uniqid(rand(),true));
}

$GLOBALS['FormError'] = unserialize(str_replace(SECURE_HEADER,"",file_get_contents(SENTRA_HOME."{{formTXTfilename}}")));

// 1. get form's global parameter from file
$formXMLdata = unserialize(str_replace(SECURE_HEADER,"",file_get_contents(SENTRA_HOME."{{formXMLfilename}}")));

// 2. Get rendering parameter from file:
$formpara = unserialize(str_replace(SECURE_HEADER,"",file_get_contents(SENTRA_HOME."{{formparafilename}}")));
// Handover some defines via formpara
$formpara['FORMsID'] 				= "{{ID}}";
$formpara['uniqueID'] 			= "{{UNIQUE}}";
$formpara['UPLOAD'] 				= "savedupload";
$formpara['THUMBFILEPREFIX']= "Thumb.";
$formpara['UserID'] 				= $UserID;
$formpara['SelectMode'] 		= 'standard';
$formpara['RadioMode']			= 'fancy';
$formpara['CheckMode']			= 'fancy';
$formpara['thumb_width'] 		= '128';
$formpara['form_tpl'] 			= '<!--
	\SentraDesigner\fills\Form\Formtpl\form.tpl

	Template with form frame work
 	-->
<if name="Compile">
<div id="fmw{{form_ID}}" class="wells wells-{{fmwstyle}} hidden">
	{{WarningText}}
</div>
<else />
	<if name="ShowWarning">
<div id="fmw{{form_ID}}" class="wells wells-{{fmwstyle}}">
	<else />
<div id="fmw{{form_ID}}" class="wells wells-{{fmwstyle}} hidden">
	</if>
	{{WarningText}}
</div>
</if>
<form data-piwik-ignore class="form{{formclass}}" id="{{form_ID}}" name="{{formname}}" enctype="{{formenctype}}" method="{{formmethod}}" action="{{formaction}}">
{{FieldSets}}
</form>

<script src="{{ValidatePass}}jquery.validate.js"></script>
<script>
{{validation}}
$("#{{form_ID}}").validate({
	rules:{
		captcha_value:{
			required:true,
			remote:"{{captchacheckPath}}captcha-check.php"
		}
	},
	errorLabelContainer: $("#fmw{{form_ID}}")

});
</script>

<!--
	END:: Template with form frame work
 	-->
';

if (isset($formpara['archivedata'])) {
	#dis arch# begin
	$Path = SENTRA_HOME."assets/data/formdata_{{UNIQUE}}/";
	$Files = STR_GetFileList($Path, "*");

	for ($x=0;$x < count($Files);$x++) {

		if ((filemtime($Path.$Files[$x]) < time()-(60*30)) || (strpos($Files[$x],".lst") > 0) ||
				(strpos($Files[$x],".dsc") > 0) || (strpos($Files[$x],".php") > 0)) {
			if ($Files[$x] != ".htaccess" && $Files[$x] != ".index.php") unlink($Path.$Files[$x]);
		}
	}
	#dis arch# end

	if (!file_exists(SENTRA_HOME."assets/data/formdata_{{UNIQUE}}/folder-content.txt")) {
		file_put_contents(SENTRA_HOME."assets/data/formdata_{{UNIQUE}}/folder-content.txt",$formpara['archivedata']['description']);
	}
// create an unique filename for storing the link list to html-/csv-messages file
//	$formpara['linklistfilename'] = "/{{linklist}}_link.lst"; defined in plugin_render.php
	$formpara['linklistfilename'] = str_replace("{{linklist}}",
																							$formpara['UserID'],
																							$formpara['linklistfilename']);
	$linklist=retrieve_linklist($formpara);
}
/* Specify the standard receiver address of form inputs */
/* "sendemailto" may be replaced by a "sendmessageto"-feature in the form */
$GLOBALS["sendemailto"] = $formpara['mailto'];

$form = new vtdHTML5form($formXMLdata, $formpara, $FormGriddy);

// ======================================================================
// Visitor pressed the link to the entered message:
// ======================================================================
If (isset($_GET['MyUserID_{{ID}}'])) {
	$randomlinkindex=$_GET['MyUserID_{{ID}}'];
	$linklist=retrieve_linklist($formpara);
	If (is_bool($linklist)) {	// means: the path to the archive folder is not set or is not found
		// No link to the stored message found
		echo "<br />Could not find the corresponding message. Please inform the owner of this site.";
	} Else {
		If (isset($linklist[$randomlinkindex]['htmlfile']) &&
			file_exists($linklist[$randomlinkindex]['htmlfile'])) {
			echo str_replace(".,",";",file_get_contents($linklist[$randomlinkindex]['htmlfile']));
		} Else {
		// No link to the stored message found
		echo "<br />Could not find the message corresponding to your UserID. Please inform the owner of this site.";
		}
	}

} Else {

	// *********************************************************************************************
	// *********************************************************************************************
	//                                        Main Program
	// *********************************************************************************************
	// *********************************************************************************************
	$render_form = TRUE;

	// 1. See if user has entered data and if so then validate the data:
	if (isset($GETPOSTvars["action"]) && $GETPOSTvars["action"] == "submit" && $GETPOSTvars["id"] == "{{ID}}") {
/*
		Assume all entered data are correct; If the analysis process yields erroneous results, $render_form is set
		to TRUE resulting in that the form is presented again with warnings around the erroneous data:
*/
		$render_form = FALSE;

		// Analyse sent form input:
		// In case of file upload, there is no corresponding GET or POST data available, just some info in the super global $_FILES
//print_r('<br>'.__FILE__.':<br>LINE: '.__LINE__.'<br>count(FILES) = '.count($_FILES));
		If (count($_FILES) > 0) {
			// As a consequnce we store $_FILES and something more into a special descriptor file
			foreach ($_FILES as $name => $value) {
				$descrpath = form_move_uploaded_file($name,				// index in $_FILES
																							 $formpara);
				If (!is_bool($descrpath)) {
					If (file_exists($descrpath)) {
					$info = unserialize(file_get_contents($descrpath));
					foreach($info as $name => $value) {	// copy infos on uploaded files into the received data array
						$GETPOSTvars[$name]['name'] 		= $value['name'];
						$GETPOSTvars[$name]['type'] 		= $value['type'];
						$GETPOSTvars[$name]['size'] 		= $value['size'];
						$GETPOSTvars[$name]['tmp_name'] = $value['tmp_name'];
						$GETPOSTvars[$name]['error'] 	  = $value['error'];
						If (isset($value["dstfilename"])) $GETPOSTvars[$name]["dstfile"]  					= $value["dstfilename"];
						If (isset($value[$name]['relfilepath']))$GETPOSTvars[$name]['relfilepath'] 	= $value[$name]['relfilepath'];
						//  for preview purposes create a thumbnail image if the uploaded file is an image file
						SWITCH ($value["type"]) {
							case "image/gif":
							case "image/x-png":
							case "image/png":
							case "image/jpeg":
							case "image/pjpeg":
								$status = create_thumbnail($name, $formpara, $value);
								If (!is_bool($status)) $GETPOSTvars[$name]['thumbnailpath']=$status;
							break;
							default:
								break;
						}
					}
					}
				}
			}
		} Else {
		}
        // here we must check already uploaded files
        //
		$user_input = array();
    $VCARD_values = array();					// array with received user input indexed by form's var names

		// form_Analyze_GETPOST_data() returns TRUE if no input error was found. In that case $render_form must be set to FALSE
		$retarray = $form -> form_Analyze_GETPOST_data ($GETPOSTvars,$formpara,$formXMLdata,$user_input, $VCARD_values);
		$render_form		= !$retarray[0];
		$user_input = $retarray[1];
		$VCARD_values 	= $retarray[2];

		/* create server vars and set them to the entered values which can be used by SENTRA users */
		foreach ($GLOBALS["FORMvars"] as $key => $value) {
			$$key = $value;
		}

	} Else {
	// Fill user input array with dummy values in order to prevent failures during rendering
		$nTABs = count($formXMLdata['page'][0]['tab']);
		If ($nTABs > 6) $nTABs = 6;
		$user_input = $formXMLdata;
		for ($it=0; $it < $nTABs; $it++) {
			$user_input['page'][0]['tab'][$it]['status'] = TRUE;
			for ($fs=0; $fs < count($formXMLdata['page'][0]['tab'][$it]['fieldset']); $fs++) {
				$user_input['page'][0]['tab'][$it]['fieldset'][$fs] =
					$form -> form_prefill_fieldset_user_input(
								$user_input['page'][0]['tab'][$it]['fieldset'][$fs],
								$formXMLdata['page'][0]['tab'][$it]['fieldset'][$fs]
					);
			}
		}
	}
	// 2. Render form if required
	If ($render_form) {
		 echo $form -> form_rendering($user_input);	/* Produces $formHTML */

	} Else {
		// final processing of sent material if everything is correct:
		// and don't forget to delete temporary files
		$nTABs = count($user_input['page'][0]['tab']);
		$realIP = form_get_real_ip();
		// convert user inputs into csv format
			$csvstring = $form -> form_userinput2csv ($user_input);
		//$csvstring[0]['tabcaption'] => TAB's caption
		// 		 			[0]['fslegend'] 	=> fieldset legend
		// 		 			[0]['input'][0] 	=> vname;Vorname;Hans
		// 		 				  				[1] 	=> nname;Nachname;Dampf
		// 		 				  				[2] 	=> email;Email;e@mail.ad
		// 		 				  				[3] 	=> message;Nachricht;To make matters worse, if someone picks the wrong provider, instead of signing in to the service they’re trying to use, they might end up signing up again, thereby creating a second account. While a website can do its best to match accounts from different services, there’s no completely accurate way (that I know of) to determine whether a Twitter and a Facebook account definitively belong to the same person.
		// 		 				  				[4] 	=> empty (submit button)
		// compile HTML-message with results:
			$HTMLmessage = '
		<table class="form_results" id="table_{{ID}}">
			<tr>
<!--				<td colspan="2">&nbsp;</td> -->
				<td>Datum:</td>
				<td>'.date(" D, Y-M-d").'</td>
			</tr>
			<tr>
<!--				<td colspan="2">&nbsp;</td> -->
				<td>Zeit:</td>
				<td>'.date("G:i:s").'</td>
			</tr>
			<tr>
<!--				<td colspan="2">&nbsp;</td> -->
				<td>IP-Adresse:</td>
				<td>'.$realIP.'</td>
			</tr>
			';
		for ($it=0; $it < $nTABs; $it++) {
			If ($csvstring[$it]['tabcaption'] != "dummy" && $csvstring[$it]['tabcaption'] != "") {
				$HTMLmessage .= '
			<tr>
				<td class="TABhead" colspan="5">TAB '.str_replace(".,",";",$csvstring[$it]['tabcaption']).'</td>
			</tr>';
			}
			$HTMLmessage .= '
			<tr>
<!--				<td colspan="2">&nbsp;</td> -->
				<td><b>Label</b></td>
				<td><b>Wert</b></td>
			</tr>';
			for ($fs=0; $fs < count($formXMLdata['page'][0]['tab'][$it]['fieldset']); $fs++) {
					If ($csvstring[$it][$fs]['fslegend'] != "") {
						$HTMLmessage .= '
			<tr>
				<td>&nbsp;</td>
				<td class="fieldsethead" colspan="4">'.str_replace(".,",";",$csvstring[$it][$fs]['fslegend']).'</td>
			</tr>';
					}
					for ($l=0;$l<count($csvstring[$it][$fs]['input']);$l++) {
						$tmpary = explode(";",$csvstring[$it][$fs]['input'][$l]);
						If (is_array($tmpary) && count($tmpary)==3) {
							$HTMLmessage .= '
			<tr>
<!--				<td colspan="2">&nbsp;</td> -->
				<td>'.str_replace(".,",";",htmlspecialchars($tmpary[1])).'</td>
				<td>'.str_replace(".,",";",str_replace("\r\n","<br />",htmlspecialchars($tmpary[2]))).'</td>
			</tr>
';
						}
					}
			}
				$HTMLmessage .= '		</table>';
		}
		#send tpl# begin
		require_once(SENTRA_SCRIPT_CORE."pagemill.php");
		$pm = new PageMill();
		$germanweekdays = array('Mon' => 'Montag',
														'Tue' => 'Dienstag',
														'Wed' => 'Mittwoch',
														'Thu' => 'Donnerstag',
														'Fri' => 'Freitag',
														'Sat' => 'Samstag',
														'Sun' => 'Sonntag');
		$tmp = array("DATE" => $germanweekdays[date("D")].date(", d.M.Y"),
		            "TIME" => date("G:i:s"),
		            "DATE-LABEL" => "Datum:" ,
		            "TIME-LABEL" => "Zeit:" ,
		            "IP" => $realIP,
		            "IP-LABEL" => "IP-Adresse"
		            );

		$pm->setVariableArray($tmp);

		for ($it=0; $it < $nTABs; $it++) {
			for ($fs=0; $fs < count($formXMLdata['page'][0]['tab'][$it]['fieldset']); $fs++) {
				for ($l=0;$l<count($csvstring[$it][$fs]['input']);$l++) {
					$tmpary = explode(";",$csvstring[$it][$fs]['input'][$l]);
					If (is_array($tmpary) && count($tmpary)==3) {
					    $tmp = array('LABEL' => str_replace(".,",";",htmlspecialchars($tmpary[1])),
					                'VALUE' => str_replace(".,",";",str_replace("\r\n","<br />",htmlspecialchars($tmpary[2]))));
					    $pm->addLoop('results', $tmp);
					}
				}
			}
		}
		$HTMLmessage = $pm->writeFile(SENTRA_SCRIPT_HOME.'form_mail.tpl');
		$HTMLmessage = str_replace("\t","",$HTMLmessage);
		unset ($pm);
		#send tpl# end

// Check if visitor sent the identical form content once again:
		if (checkRefresh("{{ID}}")) {
	    echo $GLOBALS['FormError']['multiple_send'];
    } else {
			// Here we store the message if it shall be stored:
    	setCheckString("{{ID}}");
			if (!isset($formpara['thankmode'])) $formpara['thankmode'] = "simple";
			if ( $formpara['thankmode'] == "simple") {
				$AcknowledgeMessage = str_replace('{{SIGN}}','',$formpara['acknowledge-message']);
				preg_match_all('/{{([a-z0-9_\-]*?)}}/i', $AcknowledgeMessage, $matches, PREG_SET_ORDER);
				//$matches = Array ([0] => Array ( [0] => {{vname}} [1] => vname )
				//									[1] => Array ( [0] => {{nname}} [1] => nname ) )
				foreach($matches as $key => $replaces) {
					$AcknowledgeMessage = str_replace($replaces[0],$GETPOSTvars[$replaces[1]],$AcknowledgeMessage);
				}
				echo "<br /><br />".$AcknowledgeMessage."<br /><br />";
			}	else {
				/* render ordinary paragraphs produced in SENTRA */
				for ($x = 0; $x < count($formpara['thankspara']);$x++) {
					STR_MakeParagraph(SENTRA_HOME.'assets/content/'.$formpara['thankspara'][$x].'.php',true);
				}
			}
			// Store user inputs into csv-file?
			If (isset($formpara['archivedata']['format']) && $formpara['archivedata']['format']=="csv") {
				$currentdatetime = $germanweekdays[date("D")].date("d-m-Y").'-'.date('G_i_s');
				$csvfile  = strtolower(SENTRA_HOME."assets/data/".$formpara['messagefolder']."/".$currentdatetime."_".$formpara['UserID'].".csv");
				$htmlfile = strtolower(SENTRA_HOME."assets/data/".$formpara['messagefolder']."/".$currentdatetime."_".$formpara['UserID'].".html");
				$SERVER_PORT = $_SERVER['SERVER_PORT'];
				if (isset($_SERVER)) {
					$SERVER_NAME = $_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'];
					$SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
					$HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off');
				} elseif (isset($HTTP_SERVER_VARS)) {
					$SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME'];
					$SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME'];
					$HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off';
				} else {
					die("Whether _SERVER nor HTTP_SERVER_VARS are defined on this server. Please inform the owner of this web site.");
				}
		  	if ($HTTPS == '1' || $HTTPS == 'on') {
		  		$SCHEME = 'https:';
		  	} else {
		  		$SCHEME = 'http:';
		  	}
              #dis arch# begin

##				 $linktomymessage = $SCHEME."".$SERVER_NAME.$SCRIPT_NAME.'?MyUserID_{{ID}}='.$formpara['UserID'];
##				 $linktomycsvfile = $SCHEME."".$SERVER_NAME."/assets/data/".$formpara['messagefolder']."/".$currentdatetime."_".$formpara['UserID'].".csv";
##
##				/* Add this message to the list of links to messages: */
##				 $linklist=retrieve_linklist($formpara);
##				 $linklist[$formpara['UserID']]['htmlfile'] = $htmlfile;
##				 $linklist[$formpara['UserID']]['csvfile']  = $csvfile;
##				 store_linklist($linklist, $formpara);
##				 $linklist=retrieve_linklist($formpara);
##
##				/* save htmlmessage to file: */
##				 $fp = fopen($htmlfile,"wb");
##				 fwrite($fp,$HTMLmessage);
##				 fclose($fp);
##
##				/* save csv file: */
##				 $fp = fopen($csvfile,"wb");
##				 If ($fp) {
##					 for ($it=0; $it < $nTABs; $it++) {
##						 fwrite($fp, PHP_EOL.$csvstring[$it]['tabcaption'].';');
##						 for ($fs=0; $fs < count($formXMLdata['page'][0]['tab'][$it]['fieldset']); $fs++) {
##							 fwrite($fp, "\r\nfieldset ".$csvstring[$it][$fs]['fslegend'].';');
##							 fwrite($fp, "\r\n;Variable;Label;Wert");
##							 for ($l=0;$l<count($csvstring[$it][$fs]['input']);$l++) {
##								 $tmpary = explode(";",$csvstring[$it][$fs]['input'][$l]);
##								 If (is_array($tmpary) && count($tmpary)==3) {
##									 fwrite($fp, "\r\n;".$tmpary[0].";".$tmpary[1].';'.$tmpary[2]);
##								 }
##							 }
##						 }
##					 }
##					 fclose($fp);
##				 }
##
##				/* Present results on screen (show only a link to the HTML-file): */
##				echo '<br /><a href="'.$linktomymessage.'">Folgen Sie diesem Link, um Ihre eingegebenen Daten zu überprüfen...</a>';
/*
*/
                #dis arch# end

			}

			// Send information email to the recipient. don't send if the host is localhost
			If (!is_int(strpos('http://localhost',$_SERVER['SERVER_NAME']))) {
					require_once(SENTRA_SCRIPT_CORE."mail.php");

				// mail subject: Replace place holder with coresponding values:
				$mailsubject = $formpara['mailsubject'];
				preg_match_all('/{{([a-z0-9_\-]*?)}}/i', $mailsubject, $matches, PREG_SET_ORDER);
				//$matches = Array ([0] => Array ( [0] => {{vname}} [1] => vname )
				//									[1] => Array ( [0] => {{nname}} [1] => nname ) )
				foreach($matches as $key => $replaces) {
					$mailsubject = str_replace($replaces[0],$GETPOSTvars[$replaces[1]],$mailsubject);
				}
				$mail = new ComposeMail($GLOBALS["sendemailto"],FrmData::PrepareValue ($mailsubject));
				$mail->sh_fromAddr($formpara['mailfrom']);
				$mail->sh_fromName($formpara['mailfromname']);
				$style = file_get_contents(SENTRA_SCRIPT_HOME."form-style.css");
				$mail->style = "<style>".$style."</style>";

				// Uploaded file(s)
				$uploadedsrc = array();
				$uploadeddest = array();
				if (isset($_POST['uploadedsrc'])) {
					$uploadedsrc = explode("|",$_POST['uploadedsrc']);
					$uploadeddest = explode("|",$_POST['uploadeddest']);
				}
				$already_attached = array();
				If (isset($info)) {
					foreach($info as $name => $value) {
						If (file_exists($value['relfilepath'])) {
							$Upinfo = pathinfo($value['relfilepath']);
							array_push ($already_attached, $Upinfo['basename']);
							$mail->addAttachFromFile($value['relfilepath'],$value['type'],"attachment",$fdescrip="",$fid="",$value['name']);
						}
					}
				}
        // Already Uploaded file(s)


        if (!empty($uploadedsrc)) {
        	for ($x=0; $x < count($uploadedsrc);$x++) {
        		if (!in_array($uploadedsrc[$x],$already_attached)) {
        			//echo "->".SENTRA_HOME.$formpara['messagespath'];
        			$mail->addAttachFromFile(SENTRA_HOME.$formpara['messagespath']."/".$uploadedsrc[$x],
        															 FrmData::mime_content_type(SENTRA_HOME.$formpara['messagespath']."/".$uploadedsrc[$x]),
        															 "attachment",$fdescrip="",$fid="",
        															 $uploadeddest[$x]);
        			}
        		}
        	}
//				$pos = strpos(" ".$formpara['mailsubject'],"{{email}}");
				If (isset($GETPOSTvars[$formpara['replyto']]) && $GETPOSTvars[$formpara['replyto']] != "") {
					$replyto = $GETPOSTvars[$formpara['replyto']];
					$mail->sh_replyto($replyto);
				}
				If (isset($formpara['mailcc']) AND $formpara['mailcc'] != "") $mail->sh_CarbonCopy($formpara['mailcc']);
				If (isset($formpara['mailbcc']) AND $formpara['mailbcc'] != "") $mail->sh_BlindCarbonCopy($formpara['mailbcc']);
                #dis arch# begin
				//If (isset($linktomymessage))$HTMLmessage .= '<br/><br/>Link to HTML-archive: <a href="'.$linktomymessage.'">'.$linktomymessage.'</a>';
                #dis arch# end
		// csv-files are processed separately by the admin tool. As a consequence no link to the file is shown in the info message:
		#		If (isset($linktomycsvfile))$HTMLmessage .= '<br/><br/>Link to CSV-archive: <a href="'.$linktomycsvfile.'">'.$linktomycsvfile.'</a>';

				if (isset($formpara['vcardlist'])) {
					$mode="0";
					if (isset($formpara['vcardlist']['vcard_type'])) {
						$mode = $formpara['vcardlist']['vcard_type'];
						unset ($formpara['vcardlist']['vcard_type']);
					}
					switch ($mode) {
						case "0":
							require_once(SENTRA_SCRIPT_HOME."vcard.php");
							break;
						case "1":
							require_once(SENTRA_SCRIPT_HOME."vcard-ol.php");
							break;
						case "2":
							require_once(SENTRA_SCRIPT_HOME."vcard-tb.php");
							break;
						case "3":
							require_once(SENTRA_SCRIPT_HOME."vcard-olo.php");
							break;
						default:
							require_once(SENTRA_SCRIPT_HOME."vcard.php");
							break;
					}

					$vcard = new vcard();
          if (isset($formpara['vcardlist']['vcard_char'])) {
          	$vcard->charset = $formpara['vcardlist']['vcard_char'];
          }
					foreach ($formpara['vcardlist'] as $key=>$val) {
						If (isset($VCARD_values[$val]))
						$vcard->data[$key]=$VCARD_values[$val];
					}
          $vc = FrmData::RandomString(12);

          file_put_contents(SENTRA_PLUGIN_TEMP.$vc.".vcf", $vcard->build());
          $files2delete[] = SENTRA_PLUGIN_TEMP.$vc.".vcf";

					$mail->addAttachFromFile( SENTRA_PLUGIN_TEMP.$vc.".vcf",
                        "text/x-vcard; charset=".$vcard->charset,
                        "attachment",
                        "",
                        "",
                        "kontakt.vcf");
				}
				$mail->addHTMLBodyPart(str_replace("\\","",$HTMLmessage));
				$mail->BuildAndSendMessage();
				// Delete uploaded files from the archive?
        foreach ($files2delete as $f) {
         @unlink ($f);
        }

				If (isset($GETPOSTvars['ULdel'])) {
					foreach($GETPOSTvars['ULdel'] as $key => $value) {
						$tmp = explode("--",$value);
						$kill = $tmp[0];
						$killwhat = $tmp[1];
						If ($kill == 1) {
							form_delete_uploaded_files($formpara,$killwhat);
							form_delete_uploaded_files($formpara,$formpara['THUMBFILEPREFIX'].$killwhat);
						}
					}
				}
			}
		}
	}
}
?>
