<?php

include("inc.all.php");
$q2 = new CDb();
$q3 = new CDb();
$q4 = new CDb();

$q->query("SELECT captcha,arp_type,subscribe_to_my_arp FROM campaigns WHERE id='".$campaign_id."'");
$q->next_record();

if ($q->f("subscribe_to_my_arp")==1 && $q->f("arp_type")==2){


	$query="select * from autoresponder_config where campaign_id='".$campaign_id."' order by id";
	$q2->query($query);

	$switch = false;
	$arp = 1;	
	while ($q2->next_record()){



		if (($q2->f("field") == "url" && strpos($q2->f('value'),'prosender')) || ($q2->f("field") == "url" && strpos($q2->f('value'),'aweber'))){

			$t->set_var("request_email","");			

			$switch = true;

		}
	}

	foreach ($_REQUEST as $post=>$value_post){
		$_REQUEST[$post]=urldecode($value_post);
	}
}
/*if ($q->f(''))	
$q->query("SELECT ip,count FROM sent_ip WHERE ip='$ip'");
$q->next_record();
if ($q->nf()){
	if ($q->f('count')>=3){
				die("<script>
					parent.document.location='".$_REQUEST['prev_url']."&err=6';					
				</script>");			
	}else{
		$q->query("UPDATE sent_ip SET count=count+1 WHERE ip='$ip'");
	}
}else{
	$q->query("INSERT INTO sent_ip SET ip='$ip'");
}
*/
if ($q->f("captcha")=='1'){
	require_once("lib/hn_captcha.class.x1.php");
	// ConfigArray

	$folders=get_setting("site_full_url");
	$folders=preg_replace('/http\:\/\/'.$_SERVER['HTTP_HOST'].'/',"",$folders);
	$CAPTCHA_INIT = array(

            'tempfolder'     => $_SERVER['DOCUMENT_ROOT'].$folders."_tmp/",      // string: absolute path (with trailing slash!) to a writeable tempfolder which is also accessible via HTTP!
			'TTF_folder'     => $_SERVER['DOCUMENT_ROOT'].$folders."fonts/", // string: absolute path (with trailing slash!) to folder which contains your TrueType-Fontfiles.
// mixed (array or string): basename(s) of TrueType-Fontfiles
			'TTF_RANGE'      => array('comic.ttf','impact.ttf'),
            'chars'          => 5,       // integer: number of chars to use for ID
            'minsize'        => 20,      // integer: minimal size of chars
            'maxsize'        => 30,      // integer: maximal size of chars
            'maxrotation'    => 25,      // integer: define the maximal angle for char-rotation, good results are between 0 and 30
            'noise'          => TRUE,    // boolean: TRUE = noisy chars | FALSE = grid
            'websafecolors'  => FALSE,   // boolean
            'refreshlink'    => TRUE,    // boolean
            'lang'           => 'en',    // string:  ['en'|'de']
            'maxtry'         => 3,       // integer: [1-9]
            'badguys_url'    => '/',     // string: URL
            'secretstring'   => 'A very, very secret string which is used to generate a md5-key!',
            'secretposition' => 24,      // integer: [1-32]
            'debug'          => false,
	);
	$captcha = new hn_captcha($CAPTCHA_INIT);
	$validate=$captcha->validate_submit();
//	die($captcha->validate_submit()); 

}else $validate='1';
//die($validate);
//switch($validate){
	// was submitted and has valid keys
	
if ($validate == '1'){

		if (!$member_name){
			$member_name = $_REQUEST['name'];
			$member_email = $_REQUEST['from'];
		}else{
			$member_name = $_REQUEST['member_name'];
			$member_email = $_REQUEST['member_email'];
		}
		preg_match("/^[A-Za-z0-9][\w-.]*[A-Za-z0-9]*@[A-Za-z0-9]*([\w-.]*[A-Za-z0-9]\.)+([A-Za-z]){2,4}$/i",$member_email,$match_user_email);
//die ($member_email);
		if ($member_name == '' || !@$match_user_email[0]){
			$ref=explode("?",$_REQUEST['prev_url']);
			header("Location: ".$ref[0]."?id=".$_GET['campaign_id']."&err=1&ch=1");
			exit;	
		}
		$email_arr[] = $match_user_email[0];
		$i = 0;
		foreach ($_REQUEST as $post=>$value_post){
			preg_match("'^name(\d+)'",$post,$match);
			if ($match[0] && $value_post != ""){
				$i++;
				preg_match("/^[A-Za-z0-9][\w-.]*[A-Za-z0-9]*@[A-Za-z0-9]*([\w-.]*[A-Za-z0-9]\.)+([A-Za-z]){2,4}$/i",$_REQUEST['email'.$match[1]],$match_email);
				if (!@$match_email[0]){
					$ref=explode("?",$_REQUEST['prev_url']);
					header("Location: ".$ref[0]."?id=".$_GET['campaign_id']."&err=2&ch=1");
					exit;
				}
				$domain_mail = explode('@',$match_email[0]);
				if (function_exists('checkdnsrr')){
					if (!checkdnsrr($domain_mail[1], 'MX')){
						$ref=explode("?",$_REQUEST['prev_url']);
						header("Location: ".$ref[0]."?id=".$_GET['campaign_id']."&err=4&ch=1");
						exit;
					}
				}
				$email_arr[] = $match_email[0];
			}
		}
		$initial = count($email_arr);
		$unique = array_unique($email_arr);
		$after = count($unique);
		
		if ($initial != $after){
			$ref=explode("?",$_REQUEST['prev_url']);
			header("Location: ".$ref[0]."?id=".$_GET['campaign_id']."&err=3&ch=1");
			exit;
		}
		$ban_words_arr = array();	
$q->query("SELECT ban_word FROM custom_ban WHERE campaign_id='".$_GET['campaign_id']."' AND ban=1");
while ($q->next_record()) {
	$ban_words_arr[] = $q->f('ban_word');
}
		$query = "SELECT name,email,campaign FROM banlist WHERE name='".$member_name."' AND email='".$member_email."' AND campaign='".$_GET['campaign_id']."'";
		$q->query($query);
		$q->next_record();
	if ($q->nf() == 0)
	{
		
			$q->query("SELECT * FROM members");
			$q->next_record();
		//	$member_email = $q->f("email");
			$aff_url = $q->f("aff_url");
			$admin_name = get_setting('emailing_from_name');  
			$admin_email = get_setting('emailing_from_email');   	  
			$campaign_id = $_GET['campaign_id'];
			
			$insert = "";
			
			$q2->query("SELECT * FROM track WHERE email='".$member_email."' AND  camp_id='".$campaign_id."'");
			$q2->next_record();
			
			$mails_sent = ($q2->f("mails_sent") ? $q2->f("mails_sent") : 0);
			$mails_sent_before = $mails_sent;
			
			$q->query("SELECT * FROM campaigns WHERE id='".$campaign_id."'");
			$q->next_record();
			
			$landing_page = $q->f("landing_page");
//			die ($campaign_id);
			$subscribe_to_my_arp = $q->f("subscribe_to_my_arp");
			$arp_type = $q->f("arp_type");
			$arp_message_subject = stripslashes($q->f("arp_message_subject"));
			$arp_message_body = stripslashes($q->f("arp_message_body"));
			$arp_email = $q->f("arp_email");
			$ip_banned=0;
			$q3->query("SELECT * FROM sent_ip WHERE ip='".getenv("REMOTE_ADDR")."'");
			$q3->next_record();
			
			if  ($q->f("enable_ip_ban")==1 && $q3->f("count") > $q->f("nr_tries")) $ip_banned=1;
	
		if ($ip_banned != 1)
		{ 
			
			if (!$q2->f("id")){
				$q3->query("INSERT INTO track SET name='".addslashes($member_name)."', email='".$member_email."', crypted_email='".md5($member_email)."', camp_id='".$q->f("id")."', ip='".getenv("REMOTE_ADDR")."', aff=1");
			}
			$q3->query("SELECT LAST_INSERT_ID() AS id");
			$q3->next_record();
			
			$sender_id = ($q3->f("id") ? $q3->f("id") : $q2->f("id"));
			
			if ($i >= $q->f("mandatory_number_of_friends")){
				foreach ($_REQUEST as $post=>$value_post){
					preg_match("'^name(\d+)'",$post,$match);
					if ($match[0] && $value_post != ""){
					$cccc = 0;
				foreach ($ban_words_arr as $ban_word_key=>$ban_word_value){
					$ban_word_value = str_replace('.',"\.",$ban_word_value);
					$ban_word_value = str_replace('*',".*",$ban_word_value);
					preg_match("'$ban_word_value'",$_POST["email".$match[1]],$ban_word_match);
					if ($ban_word_match[0]!='')
						$cccc=1;
				}
					if (!$cccc){
						if($q->f('html_text')==2 || $q->f('html_text')==''){
							$br = "<br>";
						}else{
							$br = '
';
						}
						
						$message = $_REQUEST['note'].$br;
						if ($switch){
							$message .= $_REQUEST['body1'];
						}else $message .= $_REQUEST['body'];
						$message = str_replace("[[sitename]]", $q->f("website_name"),$message);
						$message = str_replace("[[your_name]]", $member_name,$message);
						$message = str_replace("[[friend_name]]", $_REQUEST[$match[0]],$message);
						
						
						$subject = $_REQUEST['subject'];
						$subject = str_replace("[[friend_name]]", $_REQUEST[$match[0]],$subject);
						$subject = str_replace("[[your_name]]", $member_name,$subject);
						$no_mail = "";
						if ($q->f("include_do_not_email_me_again_link")){
							$no_mail = "$br If you do not want to recieve this email anymore click on ".($br == '<br>' ? "<a href='".get_setting("site_full_url")."remove_email.php?email=".md5($_REQUEST["email".$match[1]])."&campaign=".$q->f("id")."'>this link</a>" : get_setting("site_full_url")."remove_email.php?email=".md5($_REQUEST["email".$match[1]])."&campaign=".$q->f("id"));
						}
						
						$q2->query("SELECT * FROM track WHERE crypted_email='".md5($_REQUEST["email".$match[1]])."' AND camp_id='".$_GET['campaign_id']."' AND not_mail=1");
						$q2->next_record();
						if ($q->f("enable_link_tracking")){
							$link_track = $br == '<br>' ? "<a href='".get_setting("site_full_url")."track.php?email=".md5($_REQUEST["email".$match[1]])."&campaign=".$q->f("id")."'>".$q->f("link")."</a>" : get_setting("site_full_url")."track.php?email=".md5($_REQUEST["email".$match[1]])."&campaign=".$q->f("id");
						}else{
							$link_track = $br == '<br>' ? "<a href='".$q->f("link")."'>".$q->f("link")."</a>" : $q->f("link");
						}
						$message = str_replace($q->f("link"), $link_track,$message);
						
						if ($q->f("use_aff_link")){
							$aff_link = "$br ".($br == '<br>' ? "<a href='$aff_url'>$aff_url</a>" : $aff_url);
						}else $aff_link = "";
						
						if ($q2->f("id")){
						}else{
							$q2->query("SELECT * FROM track WHERE email='".($_REQUEST["email".$match[1]])."' AND camp_id='".$_GET['campaign_id']."'");
							$q2->next_record();
							if (!$q2->f("id")) {
		
								$q3->query("INSERT INTO track SET name='".$_REQUEST[$match[0]]."', email='".$_REQUEST["email".$match[1]]."', crypted_email='".md5($_REQUEST["email".$match[1]])."', camp_id='".$q->f("id")."', aff='$sender_id'");
								if ($mails_sent == 0) $joiner=1;			
								$mails_sent++;
							}
							$message .= $no_mail;
							if($q->f('html_text')==2 || $q->f('html_text')=='')
								$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
							else{
								$headers = 'Content-type: text/plain' . "\r\n";
							}
							$message = stripslashes($message);
							if ($switch)
								$message=str_replace("(br)",$br,$message);
								else $message = preg_replace("'\r\n'",$br,$message);
							
							$headers .= 'From: '.$member_name."<".$member_email.">";
							
							mail($_REQUEST[$match[0]]." <".$_REQUEST["email".$match[1]].">",$subject,$message,$headers);
							
						}
					}
				}
					
			}
				
		}
			
			
			
					// notify friend for joining
			$q2->query("SELECT * FROM track WHERE email='".$member_email."' AND camp_id='".$_GET['campaign_id']."'  AND not_mail=0");
			$q2->next_record();
		
			if ($q2->f("id")){
				if ($q2->f("aff")>1){
					$aff = $q2->f("aff");
					$joiner_name = $q2->f("name");
					
					$q2->query("SELECT * FROM track WHERE id='".$aff."'");
					$q2->next_record();
					$nr_joined_before = $q2->f("nr_joined");
					if ($joiner == 1){
						$nr_joined = $q2->f("nr_joined") + 1;
						$q3->query("UPDATE track SET nr_joined='".$nr_joined."' WHERE id='".$aff."'");
						}
					$q3->query("SELECT * FROM campaigns WHERE id='".$q2->f("camp_id")."'");
					$q3->next_record();
					if ($q3->f("send_join_notification")&& $joiner){
						
						$message = $q3->f("join_email_body");
						$message = str_replace("[[sitename]]", $q3->f("website_name"),$message);
						$message = str_replace("[[your_name]]", $q2->f("name"),$message);
						$message = str_replace("[[link]]", $q3->f("link"),$message);
						$message = str_replace("[[admin_profile_name]]", get_setting("emailing_from_name"),$message);
			
						$subject = $q3->f("join_email_subject");
						$subject = str_replace("[[your_name]]", $q2->f("name"),$subject);
						
						$header = "From: ".get_setting("emailing_from_name")."<".get_setting("emailing_from_email").">";
						mail ($q2->f("name")." <".$q2->f("email").">",stripslashes($subject),stripslashes($message),$header);
					}
					if ($q3->f("use_joined_bonus") && ($nr_joined >= $q3->f("number_of_friends_to_qualify_bonus2") && $nr_joined_before < $q3->f("number_of_friends_to_qualify_bonus2"))){
						$message = $q3->f("gift_email_body2");
						$message = str_replace("[[sitename]]", $q3->f("website_name"),$message);
						$message = str_replace("[[your_name]]", $q2->f("name"),$message);
						$message = str_replace("[[gift_url2]]", $q3->f("gift_url2"),$message);
						$message = str_replace("[[admin_profile_name]]", get_setting("emailing_from_name"),$message);
						$message = str_replace("[[link]]", $q3->f("link"),$message);
						$subject = $q3->f("gift_email_subject_line2");
						$subject = str_replace("[[your_name]]", $q2->f("name"),$subject);
						
						$headers = "From: ".get_setting("emailing_from_name")."<".get_setting("emailing_from_email").">";
						mail ($q2->f("name")." <".$q2->f("email").">",stripslashes($subject),stripslashes($message),$headers);
					}
				}
			
				if($q->f("use_reward_email_just_taf") == 1){
					if($mails_sent >= $q->f("number_of_friends_to_qualify_bonus1") && $mails_sent_before < $q->f("number_of_friends_to_qualify_bonus1")){
						$message = $q->f("gift_email_body1");
						$message = str_replace("[[sitename]]", $q->f("website_name"),$message);
						$message = str_replace("[[your_name]]", $member_name,$message);
						$message = str_replace("[[gift_url]]", $q->f("gift_url"),$message);
						$message = str_replace("[[admin_profile_name]]", $admin_name,$message);
							
						$subject = $q->f("gift_email_subject_line1");
						$subject = str_replace("[[your_name]]", $member_name,$subject);
						if($q->f('html_text')==2 || $q->f('html_text')==''){
							$br = "<br>";
						}else{
							$br = '
';
						}
						if($q->f('html_text')==2 || $q->f('html_text')=='')
								$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
							else{
								$headers = 'Content-type: text/plain' . "\r\n";
							}
						$message = preg_replace("'\r\n'",$br,$message);
						$headers .= ("From: ".$admin_name."<".$admin_email.">");
						mail($member_name." <".$member_email.">",stripslashes($subject),stripslashes($message),$headers);
					}
				}
				
				if($q->f("send_confirmation_to_sender") == 1){		
					$message = $q->f("ty_email_body");
					$message = str_replace("[[sitename]]", $q->f("website_name"),$message);
					$message = str_replace("[[your_name]]", $member_name,$message);
					$message = str_replace("[[link]]", $q->f("link"),$message);
					$message = str_replace("[[admin_profile_name]]", $admin_name,$message);
					
					$subject = $q->f("ty_email_subject");
					$subject = str_replace("[[your_name]]", $member_name,$subject);
					$headers= ("From: ".$admin_name."<".$admin_email.">");
					mail($member_name." <".$member_email.">",stripslashes($subject),stripslashes($message),$headers);
				}
			
			}
			$q->query("UPDATE track SET mails_sent='".$mails_sent."' WHERE  email='".$member_email."'");
			$q3->query("SELECT * FROM sent_ip WHERE ip='".getenv("REMOTE_ADDR")."'");
			$q3->next_record();
			if ($q3->nf()==0) $q4->query("INSERT INTO sent_ip SET ip='".getenv("REMOTE_ADDR")."',count=count+1");
			else $q4->query("UPDATE sent_ip SET ip='".getenv("REMOTE_ADDR")."',count=count+1");
		
		}else{ ?>
			<script language="javascript">
			alert("You are not allowed to send emails any more.You have submitted the form too many times.");
			</script>
			<?php 
			$ref=explode("?",$_REQUEST['prev_url']);
					echo "<script>window.location='".$ref[0]."?id=".$_GET['campaign_id']."&err=1&ch=1'</script>";
					exit;	
		}
	}else{ ?>
		<script language="javascript">
		alert("This name and email is banned for this campaign");
		</script>
		<?php 
		$ref=explode("?",$_REQUEST['prev_url']);
				echo "<script>window.location='".$ref[0]."?id=".$_GET['campaign_id']."&err=1&ch=1'</script>";
				exit;	
	}
		if ($subscribe_to_my_arp==1 && $arp_type==1){ 
		
			$arp_message_body = str_replace('[[sender_name]]',$member_name,$arp_message_body);
			$arp_message_subject = str_replace('[[sender_name]]',$member_name,$arp_message_subject);
			$eol="\r\n";// for qmail use $eol="\n";
			$headers = $eol."X-Mailer: PHP v".phpversion().$eol."MIME-Versin: 1.0";
			@mail($arp_email, stripslashes($arp_message_subject), stripslashes($arp_message_body), "From: ".stripslashes($_REQUEST['member_name'])." <".$_REQUEST['member_email'].">".$headers);
		
		}

		if ($landing_page != "" && !$switch){
			preg_match("'^http.*'",$q->f("landing_page"),$match);
			$match[0] ? $landing_page = $q->f("landing_page") : $landing_page = "http://".$q->f("landing_page");
			echo '<script language="javascript">
			parent.location = "'.$landing_page.'";
		
		</script>
		';
		exit;
		}elseif ($landing_page != "" && $switch){
			preg_match("'^http.*'",$q->f("landing_page"),$match);
			$match[0] ? $landing_page = $q->f("landing_page") : $landing_page = "http://".$q->f("landing_page");
			header("Location: $landing_page");
			exit;
		}	die($landing_page);	

	}elseif ($validate=='2'){
//		die('cici');
		$str=$_REQUEST['prev_url'];
			if (strpos($str,"?")){

				header("Location: ".$_REQUEST['prev_url']."&err=5&ch=1");
				exit;
			}else {				
//				echo $_REQUEST['prev_url']."&err=5";
				header("Location: ".$_REQUEST['prev_url']."?err=5&ch=1");
				exit;
			}
				
		break;
	// was submitted, has bad keys and also reached the maximum try's
	}elseif ($validate=='3'){
		//if(!headers_sent() && isset($captcha->badguys_url)) header('location: '.$captcha->badguys_url);
		//		echo "<p><br>Reached the maximum try's of ".$captcha->maxtry." without success!";
		//		echo "<br><br><a href=\"".$_SERVER['PHP_SELF']."?download=yes&id=1234\">New DEMO</a></p>";
		$str=$_REQUEST['prev_url'];
				if (strpos($str,"?")){
					header("Location: ".$_REQUEST['prev_url']."&err=5&ch=1");
					exit;
				}else {
					header("Location: ".$_REQUEST['prev_url']."?err=5&ch=1");
					exit;
				}
//			echo "You have reached the maximum tries... you cannot signup at this time";
	break;
	// was not submitted, first entry
	}

?>