<?php
if(!$ETOOLS_SECRET) {
    ob_start();
}

require_once "../lib/etools2.php";
require_once "../display_fields.php";
require_once "../lib/crypt.php";
require_once "../lib/misc.php";
require_once "../lib/thread.php";

$user_id=checkuser(3);

/*
* Get access sets
*/
$view_access_arr=has_right_array('View contacts',$user_id);
$edit_access_arr=has_right_array('Edit contacts',$user_id);
$del_access_arr=has_right_array('Delete contacts',$user_id);
$viewedit_access_arr=array_unique(array_merge($view_access_arr,$edit_access_arr));
$viewedit_access=join(',',$viewedit_access_arr);
if(!$viewedit_access) {
	$viewedit_access='NULL';
}
$view_access=join(',',$view_access_arr);
if(!$view_access) {
	$view_access='NULL';
}
$edit_access=join(',',$edit_access_arr);
if(!$edit_access) {
	$edit_access='NULL';
}
$del_access=join(',',$del_access_arr);
if(!$del_access) {
	$del_access='NULL';
}

if($op=='add')
$title='Add a member';
else $title="Manage Members";
include "top.php";

/*
* Show prompt to choose form if no one was chosen
*/

if(!$form_id) {
	if($op=='add') {
		echo "<p>From this section you can add emails and new user information
	    to your database.";
	}
	else {
		echo "<p>From this section you will be able to manage emails and user
	    information in your database.";
	}
	echo "<br><br>
	<font size=-1>Click on the Email List below to continue<br>
	<table border=1 cellpadding=0 cellspacing=0 width=100% bordercolor=#CCCCCC style='border-collapse:collapse;'>
	<tr background=../images/title_bg.jpg>
	    <td class=Arial11Grey><b>Email List</b></td>
	    <td class=Arial11Grey><b>Interest Groups</b></td>
	</tr>";
	switch($op) {
		case 'add':
		$condition=$edit_access;
		break;
		case 'edit':
		$condition=$edit_access;
		break;
		case 'del':
		$condition=$del_access;
		break;
		default:
		$condition="$viewedit_access,$del_access";
		break;
	}
	$q=sqlquery("
	select form_id,name from forms
	where form_id in ($condition)
	order by name");
	while(list($form_id,$form)=sqlfetchrow($q)) {
		if($i++ % 2) {
			$bgcolor='f4f4f4';
		}
		else {
			$bgcolor='f4f4f4';
		}
		$link="http://$server_name2/users/register.php?form_id=$form_id";
		$form2=castrate($form);
		$total=count_subscribers($form2);
		$sub=count_subscribed($form2,$form_id,1);
		$unsub=$total-$sub;

		echo "<tr bgcolor=#$bgcolor>
	    <td><a href=$PHP_SELF?form_id=$form_id&op=$op><u>$form</u></a> ($sub subscribed users) ($unsub un-subscribed users)</td>
	    <td>".formatdbq("
		select name from contact_categories,forms_intgroups
		where contact_categories.category_id=forms_intgroups.category_id and
		    forms_intgroups.form_id='$form_id'","$(name)<br>")."</td>";
	}
	echo "</table>";
	include "bottom.php";
	exit();
}

/* prevent from using until the user add at least one field to the form */
list($fields_count)=sqlget("
    select count(*) from form_fields
    where form_id='$form_id' and type not in (".join(',',$dead_fields).")");
if(!$fields_count) {
	echo "You must add a valid field for that form by going <a href=form_fields.php><u>here</u></a>.";
	include "bottom.php";
	exit();
}


list($form)=sqlget("select name from forms where form_id='$form_id'");
$form2=castrate($form);


/* if the operation was requested, get the array of categories for the record */
if($id) {
	$category_id=array();
	$q1=sqlquery("
	select contact_categories.category_id
	from contact_categories,contacts_intgroups_$form2
	where contact_categories.category_id=contacts_intgroups_$form2.category_id and
		contacts_intgroups_$form2.contact_id='$id'");
	while(list($tmp_id)=sqlfetchrow($q1)) {
		$category_id[]=$tmp_id;
	}
}

/*
* Download contacts
*/
if($dlall_x || $dlselected_x || $op=='download') {
	if($dlselected_x) {
		$filter=join($id,',');
		if($filter)
		$filter=" where contact_id in ($filter)";
		else $filter=" where contact_id in (NULL)";
		$tables=$group_by='';
	}
	else if($op=='download' && $query) {
		$filter="where ".stripslashes($query);
	}
	else $tables=$group_by='';

	if(!$delim)
	if($format)
	switch($format) {
		case 'csv':
		default:
		$delim=',';
		$ext='csv';
		break;
		case 'tab':
		$delim="\t";
		$ext='txt';
		break;
	}
	else {
		$delim=',';
	}
	switch($delim) {
		case ',':
		$ext='csv';
		break;
		case 'tab':
		$ext='txt';
		$delim="\t";
		break;
		default:
		$ext='txt';
		break;
	}
	if(!$delim2)
	$delim2=':';

	if($form_id && !in_array($form_id,$viewedit_access_arr))
	exit();

	ob_end_clean();

	header("Content-type: application/octet-stream");
	header("Content-Disposition: attachment; filename=contacts_$form2".(date('mjY')).".$ext");
	$q=sqlquery("
	select type,name from form_fields
	where form_id='$form_id' and
	    (type not in (".join(',',$dead_fields).") or type=8)
	order by sort asc");
	$fields=array();
	$i=$password_i=0;
	$out='';
	while(list($type,$field)=sqlfetchrow($q)) {
		$out.="\"$field\"$delim";
		$i++;
		if($type!=8) {
			$field_types[]=$type;
			$fields[]=castrate($field);
		}
		else {
			$password_i=$i;
		}
	}
	/**
	 * add 4 fields	
	 * @since 28.10.2005
	 */	
	$out.="\"User Confirmed IP\"$delim";
	$out.="\"User Confirm Date\"$delim";

	$out.="\"Un-Subscribe IP\"$delim";
	$out.="\"Un-Subscribe Date\"$delim";
	
	
	
	$out.="\"Interest Groups\"$delim\"Action\"\n";
	$fields2=join(',',$fields);
	$fields2 = $fields2 ? $fields2.',' : '';
	$q=sqlquery("
	select contact_id,cipher_init_vector,user_id, {$fields2}
	`confirm_ip`, `confirm_date`, `un_subscribe_ip`, `un_subscribe_date`
	from contacts_$form2 $tables
	$filter
	$group_by");
	while($contact=sqlfetchrow($q)) {
				
		if($password_i) {
			list($password)=sqlget("select password from user where user_id='$contact[user_id]'");
		}
		$intgroups=$category_id=$intgrp_id=array();
		$q1=sqlquery("
	    select name,contact_categories.category_id
	    from contact_categories,contacts_intgroups_$form2
	    where contact_categories.category_id=contacts_intgroups_$form2.category_id and
		contacts_intgroups_$form2.contact_id=$contact[0]");
		while(list($intgrp,$intgrp_id)=sqlfetchrow($q1)) {
			$intgroups[]=$intgrp;
			$category_id[]=$intgrp_id;
		}
		
		
		for($i=3;$i<=count($contact)/2;$i++) {
			$key=$fields[$i-3];
			if(in_array($field_types[$i-3],$multival_arr2)) {
				if ($contact[$i] <> '') {
					$contact_i = array();
					$contact_result=sqlquery("
			select name from contacts_$form2"."_$key"."_options
			where contacts_$form2"."_$key"."_option_id IN ($contact[$i])");
					while ($contact_row = sqlfetchrow($contact_result)) {
						array_push($contact_i, $contact_row['name']);
					}
					$contact[$i] = join($delim2, $contact_i);
				}
			} 
			elseif(in_array($field_types[$i-3],$multival_arr)) {
				list($contact[$i])=sqlget("
		    select name from contacts_$form2"."_$key"."_options
		    where contacts_$form2"."_$key"."_option_id='$contact[$i]'");
			} 
			else if(in_array($field_types[$i-3],$secure_fields)) {
				$contact[$i]=decrypt($contact[$i],$cipher_key,$contact[1]);
			}
			/* boolean fields */
			else if(in_array($field_types[$i-3],$checkbox_arr)) {
				if($contact[$i]) {
					$contact[$i]='Yes';
				}
				else {
					$contact[$i]='No';
				}
			}
			/* email format */
			else if($field_types[$i-3]==25) {
				$contact[$i]=$email_format_arr[$contact[$i]];
			}			
			
			else {
				if($password_i && $password_i==$i-2) {
					$out.="\"$password\"$delim";
					$password_i = false;
				}				
				$total_cnt = count($contact)/2-$i; #hack см. SELECT выше
				if($total_cnt <= 4 && $total_cnt <> 0) {
					
					error_log($contact[$i]."\n", 3, "../asd.txt");
					
					$out.="\"".$contact[$i]."\"$delim";
				}
			}
						
			if($password_i && $password_i==$i-2) {
				$out.="\"$password\"$delim";
			}
			if($key) {
				$out.="\"$contact[$i]\"$delim";
			}			

		}
		$out.="\"";
		$out.=join($delim2,$intgroups)."\"$delim\"A\"\n";
	}
	if($delim=="\t")
	$out=str_replace("\"",'',$out);
	echo $out;
	

	exit();
}

/*
* Import contacts
*/
if($import_x /*=='Import'*/) {
	define("INSIDE", 1);
	$BR = "<br>";
	$FONT1 = "<font color=red>";
	$FONT2 = "</font>";
	$PAUSE = "<!---->";
	include("contacts_import.php");

}

if($op=='delread') {
	sqlquery("delete from email_reads where stat_id='$stat_id' and email='$email'");
	$op='edit';
}

/*
* Add/edit form
*/
if($op=='add' || $op=='edit') {
	/* cash all the form fields, produce the hashed names from it
	* and put it in array with real names */
	$field_type=array();
	$q=sqlquery("
        select field_id,name,type from form_fields
        where form_id='$form_id'");
	while(list($f_id,$name,$type)=sqlfetchrow($q)) {
		$hashed=castrate($name);
		$field_type[$hashed]=$type;
		if($type==8) {
			$password_field=$hashed;
		}
	}
	BeginForm();
	if($op=='add') {
		FrmEcho("<tr bgcolor=#f4f4f4><td colspan=2 class=Arial11Grey>
	From this page you can add a new member to the <b>$form email
	list</b>. To forward an email that is stored in the system then
	you should fill out the <b>Send Stored Email</b> drop-down field
	below and an email will be immediately sent to the user. If
	you want to add emails to the <b>Send Stored Email</b> drop-down then
	you can add an email in the <b><a href=email_campaigns.php?op=add>Add New Campaign</a></b> section.
	</td></tr>");
	}
	if($op=='edit' && ($form_id && in_array($form_id,$viewedit_access_arr))) {
		$contact=sqlget("select * from contacts_$form2 where contact_id='$id'");
		list($password)=sqlget("select password from user where user_id='$contact[user_id]'");
		$contact[$password_field]=$password;
		$iv=$contact['cipher_init_vector'];
		$intgrp=array();
		$q=sqlquery("select category_id from contacts_intgroups_$form2
		     where contact_id='$id'");
		while(list($tmpgrp)=sqlfetchrow($q)) {
			$intgrp[]=$tmpgrp;
		}
	}
	else if($op=='add' && in_array($form_id,$edit_access_arr)) {
		$contact=array();
		$intgrp=array();
		$q=sqlquery("select category_id from forms_intgroups where form_id='$form_id'");
		while(list($c)=sqlfetchrow($q)) {
			$intgrp[]=$c;
		}
	}
	else {
		include "bottom.php";
		exit();
	}
	if($op=='edit') {
		//list($added,$modified,$mod_user_id,$ip,$confirm_ip,$confirm_date,$un_subscribe_ip,$un_subscribe_date) =
		$result = sqlget("
	    select date_format(added,'%M %d, %Y %h:%i %p') as `added`,
		date_format(modified,'%M %d, %Y %h:%i %p') as `modified`,
		mod_user_id, ip,
		confirm_ip, un_subscribe_ip, 
		date_format(confirm_date,'%M %d, %Y %h:%i %p') as `confirm_date`,
		date_format(un_subscribe_date,'%M %d, %Y %h:%i %p') as `un_subscribe_date`
	    from contacts_$form2
	    where contact_id='$id'");
		
		$added			= $result['added'];
		$modified		= $result['modified'];
		$mod_user_id	= $result['mod_user_id'];
		$ip				= $result['ip'];
		$confirm_ip		= $result['confirm_ip'];
		$confirm_date	= $result['confirm_date'];
		$un_subscribe_ip	= $result['un_subscribe_ip'];
		$un_subscribe_date	= $result['un_subscribe_date'];
		
		list($mod_user)=sqlget("select name from user where user_id='$mod_user_id'");
		FrmEcho("<tr bgcolor=#f4f4f4><td colspan=2 class=Arial11Grey>You are viewing a record in the $form email list.</td></tr>
	    <tr bgcolor=#f4f4f4><td class=Arial11Grey>Record Added:</td><td class=Arial11Grey>$added</td></tr>");
		if($ip) {
			FrmEcho("<tr bgcolor=#f4f4f4><td class=Arial11Grey>Record Signed up under IP:</td><td class=Arial11Grey>$ip</td></tr>");
		}
		
		($confirm_ip) ? FrmEcho("<tr bgcolor=#f4f4f4><td class=Arial11Grey>User Confirmed IP: </td><td class=Arial11Grey>$confirm_ip</td></tr>") : '';
		($confirm_date) ? FrmEcho("<tr bgcolor=#f4f4f4><td class=Arial11Grey>User Confirm Date: </td><td class=Arial11Grey>$confirm_date</td></tr>") : '';
		($un_subscribe_ip) ? FrmEcho("<tr bgcolor=#f4f4f4><td class=Arial11Grey>Un-Subscribe IP: </td><td class=Arial11Grey>$un_subscribe_ip</td></tr>") : '';
		($un_subscribe_date) ? FrmEcho("<tr bgcolor=#f4f4f4><td class=Arial11Grey>Un-Subscribe Date: </td><td class=Arial11Grey>$un_subscribe_date</td></tr>") : '';
		
		FrmEcho("<tr bgcolor=#f4f4f4><td class=Arial11Grey>Record last modified by $mod_user:</td><td class=Arial11Grey>$modified</td></tr>");				
	}
	InputField('Send stored email:','f_campaign[]',array('type'=>'select',
	'SQL'=>"select email_id as id,name from email_campaigns",
	'combo'=>array(''=>'- None -'),'default'=>'','fparam'=>' multiple size=5'));

	InputField('Interest Groups:','f_intgrp[]',array('type'=>'select','fparam'=>' multiple size=5',
	'default'=>$intgrp,'SQL'=>"
	    select name,contact_categories.category_id as id
	    from contact_categories,forms_intgroups
	    where contact_categories.category_id=forms_intgroups.category_id and
	        forms_intgroups.form_id='$form_id' and
		forms_intgroups.form_id in ($viewedit_access)
	    order by forms_intgroups.sort asc",'combo'=>array(''=>''),'required'=>'no'));
	if($op=='edit') {
		display_fields("form",'def_contact_value',1,
		"form_id=$form_id and (type not in (".join(',',$dead_fields).") or type=8)".
		(in_array($form_id,$edit_access_arr)?"":" and type<>8"),$form_id,
		array('validator_param'=>array('exclude_myself'=>1),'email_validator'=>'validator_email4'));

		FrmEcho("<tr bgcolor=white><td class=Arial11Grey>Bounces:</td><td class=Arial11Grey>$contact[bounces]");
		if($contact['bounces'])
		FrmEcho("&nbsp;&nbsp;
		<a href=$PHP_SELF?op=reset_bounces&id=$id&form_id=$form_id><u>Reset to 0</u></a></td></tr>");
	} else {
		display_fields("form", 'def_contact_value', 1,
		"form_id=$form_id".
		(in_array($form_id,$edit_access_arr)?"":" and type<>8"),$form_id,
		array('email_validator'=>'validator_email4'));
	}

	frmecho("<input type=hidden name=op value=$op>
	<input type=hidden name=id value=$id>
	<input type=hidden name=form_id value=$form_id>");

	/* display email view statistics */
	list($email_field)=sqlget("
	select name from form_fields where form_id='$form_id' and type=24");
	if($email_field) {
		$email_field=castrate($email_field);
		$email=$contact[$email_field];
		$q=sqlquery("
	    select email_reads.stat_id,email_campaigns.name,count(*)
	    from email_campaigns,email_reads,email_stats
	    where email_campaigns.email_id=email_stats.email_id and
		email_stats.stats_id=email_reads.stat_id and
		email_reads.email='$email'
	    group by email_campaigns.name asc
	    limit $store_user_campaign");
		$numrows=sqlnumrows($q);
		if($numrows) {
			frmecho("<tr bgcolor=white><td colspan=3>
		<table border=1 cellpadding=0 cellspacing=0 width=100% bordercolor=#CCCCCC style='border-collapse:collapse;'>
		    <tr background=../images/title_bg.jpg>
			<td class=Arial12Blue><b>Campaign Name</b></td>
			<td class=Arial12Blue><b>First Read</b></td>
			<td class=Arial12Blue><b>Number of times read</b></td>
			<td class=Arial12Blue><b>Delete</b></td>
		    </tr>");
			while(list($stat_id,$campaign,$count)=sqlfetchrow($q)) {
				list($d)=sqlget("
		    select min(unix_timestamp(d)) from email_reads
		    where stat_id='$stat_id' and email='$email'");
				frmecho("<tr bgcolor=#f4f4f4>
		    <td class=Arial11Grey>$campaign</td>
		    <td class=Arial11Grey>".date('m-d-Y h:i a',$d)."</td>
		    <td class=Arial11Grey>$count</td>
		    <td class=Arial11Grey><a href=$PHP_SELF?op=delread&stat_id=$stat_id&id=$id&email=$email&form_id=$form_id onclick=\"javascript:return confirm('Are you sure?')\"><img src=../images/trash_small.gif border=0></a></td></tr>");
			}
			frmecho("</table></td></tr></table>");
		}
		else sqlfree($q);
	}
	if(in_array($form_id,$edit_access_arr))
	EndForm('Update','../images/update.jpg');
	else
	FrmEcho("</table></form>");
	FrmEcho("<a href=$PHP_SELF?start=$start&form_id=$form_id&sort=$sort&query=".urlencode(stripslashes($query))."&group_by=".urlencode($group_by)."&tables=$tables><u>Go back to the search page</u></a>");
	ShowForm();
}

/*
* update in the database
*/
if($check=='Update' && !$bad_form) {
	$fields=$u_fields=$member_fields=$member_u_fields=$vals=$member_vals=array();
	$iv='';
	$subscr_passed=0;

	/* walk through posted fields and construct query */
	while(list($field,$val)=each($HTTP_POST_VARS)) {
		$tmp_arr=explode('_z_',$field);
		if($tmp_arr[0]=='form') {
			array_shift($tmp_arr);
			$field=array_shift($tmp_arr);
			$subfield=array_shift($tmp_arr);
			/* handle the date fields */
			if($subfield=='day' || $subfield=='month' || $subfield=='year') {
				if($HTTP_POST_VARS["form_z_$field"."_z_year"] &&
				$HTTP_POST_VARS["form_z_$field"."_z_month"]) {
					$val=$HTTP_POST_VARS["form_z_$field"."_z_year"].'-'.$HTTP_POST_VARS["form_z_$field"."_z_month"];
					if($HTTP_POST_VARS["form_z_$field"."_z_day"]) {
						$val.='-'.$HTTP_POST_VARS["form_z_$field"."_z_day"];
					}
					else {
						$val.='-01';
					}
					$HTTP_POST_VARS["form_z_$field"."_z_year"]='';
					$HTTP_POST_VARS["form_z_$field"."_z_month"]='';
					$HTTP_POST_VARS["form_z_$field"."_z_day"]='';
				}
				else {
					continue;
				}
			}
			/* encrypt field if necessary */
			if(in_array($field_type[$field],$secure_fields)) {
				if($iv) {
					$encrypted=encrypt($val,$cipher_key,$iv);
				}
				else {
					$encrypted=encrypt($val,$cipher_key);
					$iv=$encrypted['iv'];
					$fields[]='cipher_init_vector';
					$vals[]=addslashes($iv);
					$u_fields[]="cipher_init_vector='".addslashes($iv)."'";
				}
				$fields[]=castrate($field);
				$vals[]=addslashes($encrypted['data']);
				$u_fields[]=castrate($field)."='".addslashes($encrypted['data'])."'";
			}
			else if(!in_array($field_type[$field],$dead_fields)) {
				if (in_array($field_type[$field], array(26,27,28))) {
					$val = join(',', $val);
				}
				$val=addslashes(stripslashes($val));
				if($field_type[$field]==7 || $field_type[$field]==24) {
					$member_fields[]="name";
					$member_vals[]=$val;
					$member_u_fields[]="name='$val'";
					$entered_email = $val;
				}
				$fields[]=$field;
				$vals[]=$val;
				$u_fields[]="`$field`='$val'";
			}
			if($field_type[$field]==8) {
				$member_fields[]="password";
				$member_vals[]=$val;
				$member_u_fields[]="password='$val'";
			}
			if($field_type[$field]==6) {
				$subscr_passed=1;
			}
		}
	}
	$fields[]="approved";	
	$vals[]=$strict_require_user ? '3' : '2';
	if(!$subscr_passed) {
		list($subscribe_field)=sqlget("
	    select name from form_fields where form_id='$form_id' and type=6");
		if($subscribe_field) {
			$subscribe_field=castrate($subscribe_field);
			$u_fields[]="$subscribe_field='0'";
		}
	}
	$b_fields = $fields;
	$b_vals	  = $vals;
	$fields=join(',',$fields);
	$vals=join("','",$vals);
	$u_fields=join(',',$u_fields);
	$member_fields=join(',',array_unique($member_fields));
	$member_vals=join("','",array_unique($member_vals));
	$member_u_fields=join(',',array_unique($member_u_fields));
	#    if($vals) {
	$vals="'$vals'";
	#    }
	if($member_vals) {
		$member_vals="'$member_vals'";
	}
	list($membership)=sqlget("
	select count(*) from form_fields where type in (7,24) and active=1 and form_id='$form_id'");


	if($op=='add' && in_array($form_id,$edit_access_arr)) {
		$contacts_nr=get_contacts_number();
		if(!$max_contacts || $contacts_nr<$max_contacts) {
			$q=sqlquery("
				insert into contacts_$form2 ($fields,added,ip)
				values ($vals,now(),'$REMOTE_ADDR')");
					$id=sqlinsid($q);
			if($strict_require_user) {
				/**
				 * Отправка Confirm email
				 */		
				$hash=md5(microtime());
				sqlquery("
				insert into validate_emails (form_id,contact_id,hash)
				values ('$form_id','$id','$hash')");
								
				list($email_field_name)=sqlget("SELECT `name` FROM `form_fields` WHERE `type` = '24' AND `form_id` ='$form_id'");
				$email_field_name = castrate($email_field_name);
	
				$email = '';
				foreach ($b_fields as $bk=>$bv) {
					if($bv == $email_field_name) {
						$email = $b_vals[$bk];
						break;
					}
				}
				if($email) {
					list($form_name) = sqlget("SELECT `name` FROM `forms` WHERE `form_id`='$form_id'");
							
					$details =	array(
									'list_name' => $form_name,
									'approve_link' => "http://$server_name2/users/validate.php?id=$hash",
									'remove_database_link' => "http://$server_name2/users/unsubscribe.php?email=$email&del_user=1",
									'email_domain'=> $email_domain
								);
					notify_email($email, $mail_autoresponse, $details, true);

				}
			}					 
			
			if($membership && $member_fields) {
				$member_fields.=",form_id";
				$member_vals.=",'$form_id'";
				$q2=sqlquery("insert into user ($member_fields) values ($member_vals)");
				$uid=sqlinsid($q2);
				sqlquery("insert into user_group (user_id,group_id) values ('$uid',2)");
				sqlquery("update contacts_$form2 set user_id='$uid' where contact_id='$id'");
			}

			/* subscribe to auto-responders */
			sqlquery("
		insert into responder_subscribes (responder_id,form_id,contact_id,added)
		select responder_id,'$form_id','$id',now()
		from forms_responders
		where form_id='$form_id'");

			/* send welcome email */
			if($f_campaign) {
				list($email_field)=sqlget("
		    select name from form_fields
		    where form_id='$form_id' and type=24");
				if($email_field) {
					$email_field=castrate($email_field);
					list($email)=sqlget("select $email_field from contacts_$form2 where contact_id='$id'");
					for($i=0;$i<count($f_campaign);$i++)
					if($f_campaign[$i]) {

						thread_fork("send", null, $f_campaign[$i], 1, false, $id, $form_id, 1);
						#			   $out=file("http://$server_name2/admin/email_campaigns.php?op=send&id=$f_campaign[$i]&contact_id=$id&x_form_id=$form_id&$sid_name=$sid&nostats=1");
						#echo "<hr>".dirname($PHP_SELF);
						#echo "<hr>http://$server_name2".dirname($PHP_SELF)."/email_campaigns.php?op=send&id=$f_campaign&contact_id=$id&x_form_id=$form_id&$sid_name=$sid";
						echo "<p>Email sent to $email<br>";
					}
				}
			}
		}
		else {
			echo "<p><font color=red>You exceeded the maximum number of allowed contacts.</font><br>";
		}
	}
	else if($op=='edit' && ($form_id && in_array($form_id,$edit_access_arr))) {
		#echo "<hr>update contacts_$form2 set $u_fields where contact_id='$id'";

		$emails_not_match = '';
		list($curr_name) = sqlget("SELECT `name` FROM `user` WHERE user_id='$contact[user_id]'");
		if(($curr_name <> $entered_email) && $strict_require_user) {
			
			$emails_not_match = ", approved = '3'";
			
			$hash=md5(microtime());
			
			sqlquery("
			insert into validate_emails (form_id,contact_id,hash)
			values ('$form_id','$id','$hash')");

			
			if($entered_email) {
				list($form_name) = sqlget("SELECT `name` FROM `forms` WHERE `form_id`='$form_id'");
						
				$details =	array(
								'list_name' => $form_name,
								'approve_link' => "http://$server_name2/users/validate.php?id=$hash",
								'remove_database_link' => "http://$server_name2/users/unsubscribe.php?email=$entered_email&del_user=1",
								'email_domain'=> $email_domain
							);
				notify_email($entered_email, $mail_autoresponse, $details, true);

			}
		}
				
		if($u_fields) {
			sqlquery("
		update contacts_$form2 set $u_fields,
		    modified=now(),mod_user_id='$user_id'
		    $emails_not_match
		where contact_id='$id'");
		}
		sqlquery("delete from contacts_intgroups_$form2 where contact_id='$id'");
		if($membership && $member_u_fields) {
						
			list($user_exists)=sqlget("select user_id from contacts_$form2 where contact_id='$id'");
			if(!$user_exists) {
				$q2=sqlquery("
		    insert into user (form_id,$member_fields) values ('$form_id',$member_vals)");
				$uid=sqlinsid($q2);
				sqlquery("
		    insert into user_group (user_id,group_id)
		    values ('$uid',2)");
				sqlquery("
		    update contacts_$form2 set user_id='$uid'
		    where contact_id='$id'");
				$contact['user_id']=$uid;
			}
			
			sqlquery("update user set $member_u_fields where user_id='$contact[user_id]'");
			
		}

		/* send welcome email  ::NOTE:: copied from add */
		if($f_campaign) {
			list($email_field)=sqlget("
		    select name from form_fields
		    where form_id='$form_id' and type=24");
			if($email_field) {
				$email_field=castrate($email_field);
				list($email)=sqlget("select $email_field from contacts_$form2 where contact_id='$id'");
				for($i=0;$i<count($f_campaign);$i++)
				if($f_campaign[$i]) {
					thread_fork("send", null, $f_campaign[$i], 1, false, $id, $form_id, 1);
					##    			    $out=file("http://$server_name2/admin/email_campaigns.php?op=send&id=$f_campaign[$i]&contact_id=$id&x_form_id=$form_id&$sid_name=$sid&nostats=1");
					#echo "<hr>".dirname($PHP_SELF);
					#echo "<hr>http://$server_name2".dirname($PHP_SELF)."/email_campaigns.php?op=send&id=$f_campaign&contact_id=$id&x_form_id=$form_id&$sid_name=$sid";
					echo "<p>Email sent to $email<br>";
				}
			}
		}
	}
	/* add interest groups to the record */
	if(($op=='edit' && ($form_id && in_array($form_id,$edit_access_arr))) ||
	($op=='add' && $contacts_nr<$max_contacts &&
	in_array($form_id,$edit_access_arr))) {
		for($i=0;$i<count($f_intgrp);$i++) {
			@sqlquery("
		insert into contacts_intgroups_$form2 (contact_id,category_id)
		values ('$id','$f_intgrp[$i]')");
		}
	}
	echo "<p><b>Your information was successfully updated.</b><br>
	To add another contact to the $form list please click <a href=$PHP_SELF?op=add&form_id=$form_id><u>here</u></a><br><br>";
	$op='';
	unset($check);
	unset($_POST['check']);
	unset($HTTP_POST_VARS['check']);
	unset($check_x);
	unset($_POST['check_x']);
	unset($HTTP_POST_VARS['check_x']);
}

/* Reset bounces */
if($op=='reset_bounces') {
	sqlquery("update contacts_$form2 set bounces=0 where contact_id='$id'");
}

/*
* Change int.group
*/
if($op=='Change' && in_array($form_id,$edit_access_arr) && $form_id) {
	for($i=0;$i<count($id);$i++) {
		sqlquery("
	    delete from contacts_intgroups_$form2
	    where contact_id='$id[$i]'");
		sqlquery("
	    insert into contacts_intgroups_$form2 (contact_id,category_id)
	    values ('$id[$i]','$intgroup_id')");
	}
}

/*
* Delete the record from the database
*/
if(($op=='del' || $del_x) &&
($form_id && in_array($form_id,$del_access_arr))) {

	for($i=0;$i<count($id);$i++)
	if($id[$i]) {
		list($uid)=sqlget("select user_id from contacts_$form2 where contact_id='$id[$i]'");
		sqlquery("delete from user where user_id='$uid'");
		sqlquery("delete from user_group where user_id='$uid'");
		sqlquery("delete from contacts_$form2 where contact_id='$id[$i]'");
		sqlquery("delete from contacts_intgroups_$form2 where contact_id='$id[$i]'");
	}
}

/*
* List contacts
*/
if($op!='edit' && $op!='add') {
	BeginForm(2);

	/* these values may be not set when pressing "Enter" from keyboard,
	* so we set it to something random, to maintain magic number of 5
	* few lines below */
	if($check=='Search') {
		$_POST['check_x']='magic1-nothing';$_POST['check_y']='magic2-nothing';
	}
	if($check=='Search' &&
	((count(array_diff(
	array_unique(array_values($_POST)),
	array(''=>''))) == 5))) {
		$bad_form=1;
		FrmEcho("<tr bgcolor=white><td colspan=2><font color=red>
	    Please fill out at least one field for your search</font></td></tr>");
	}
	frmecho("<tr><td colspan=2 class=Arial11Grey><p>You may search the emails in
	your database by filling out the form below.
	If you are searching for emails from a certain domain then in
	the email column you can just enter domain.com and it will pull up
	all emails from that domain. If you want to search on other fields
	and you only know a few letters from the field you can enter what
	you know and the system will try to find the right information.<br><br>
	Also if you want to pull up all records, simple enter \"@\" in the email field.<br><br>
	</td></tr>");
	/*    InputField("Interest Groups:",'s_intgrp',array('type'=>'select',
	'combo'=>array(''=>'- All -'),'SQL'=>"
	select contact_categories.category_id as id,name
	from contact_categories,forms_intgroups
	where contact_categories.category_id=forms_intgroups.category_id and
	forms_intgroups.form_id='$form_id'"));
	*/ 
	FrmItemFormat("<tr bgcolor=#f4f4f4><td class=Arial11Grey>$(req) $(prompt) $(bad)</td><td class=Arial11Blue>$(input)</td></tr>\n");
	display_fields("form",'def_empty','',"form_id=$form_id and type not in (6,25,".join(',',array_merge($dead_fields,$secure_fields)).")",$form_id,
	    array('validator_param'=>array('exclude_all'=>'yes'),'combo'=>array(''=>''),
	    'search_date'=>1,'search_mode'=>1));
	FrmItemFormat("$(input)");
	FrmEcho("<tr bgcolor=#f4f4f4><td class=Arial11Grey>Added From:</td><td class=Arial11Blue>");
	InputField('','s_from_month',array('type'=>'month'));
	InputField('','s_from_day',array('type'=>'day'));
	InputField('','s_from_year',array('type'=>'year'));
	FrmEcho("&nbsp;(optional)</td></tr>");

	FrmItemFormat("$(input)");
	FrmEcho("<tr bgcolor=#f4f4f4><td class=Arial11Grey>Added To:</td><td class=Arial11Blue>");
	InputField('','s_to_month',array('type'=>'month'));
	InputField('','s_to_day',array('type'=>'day'));
	InputField('','s_to_year',array('type'=>'year'));
	FrmEcho("&nbsp;(optional)</td></tr>");

	FrmItemFormat("<tr bgcolor=#$(:)><td class=Arial11Grey>Subscription Type:</td><td class=Arial11Blue>$(input)</td></tr>");
	InputField('','s_subs',array('type'=>'select', 'combo'=>array('all'=>'show -All-','subs'=>'Subscribe Members','unsubs'=>'Un-Subscribed Members'), 'ddefault'=>0));

	FrmItemFormat("<tr bgcolor=#f4f4f4><td class=Arial11Grey>$(req) $(prompt) $(bad)</td><td class=Arial11Blue>$(input) records per page</td></tr>\n");
	InputField('Show','output_rows',array('default'=>25,'fparam'=>' size=2'));
	frmecho("<input type=hidden name=form_id value=$form_id>");
	EndForm('Search','../images/search.jpg','left');
	ShowForm();

	list($subscribe)=sqlget("select name from form_fields
    		    	     where form_id='$form_id' and type=6");
	$subscribe=castrate($subscribe);


	/* if the search fields are given then construct query */
	if(($check=='Search' && !$bad_form)) {
		echo "<p><b>You are currently looking at emails in the $form email list</b>.
	<br><br>
	Click <u><a href=$PHP_SELF?form_id=$form_id>here</a></u> if you would like to return to the main search page.

	<p>Un-subscribed links are in red. Click on field header to sort by column.<br>";

		$query=gen_query(array_merge($HTTP_POST_VARS,$HTTP_GET_VARS),1/*$f_date*/);

		if($s_intgrp) {
			if($query)
			$query.=" and ";
			$query.="contacts_intgroups_$form2.category_id='$s_intgrp' and
		contacts_intgroups_$form2.contact_id=contacts_$form2.contact_id";
			$tables=",contacts_intgroups_$form2";
			$group_by="group by contacts_$form2.contact_id";
		}
		//var_dump($subscribe);
		switch ($_POST['s_subs']){
			case 'all':
			//	    	$query .= "and0 ";
			break;
			case 'subs':
			$query = "approved not in (0,3)  and $subscribe=1";
			break;
			case 'unsubs':
			$query="approved not in (0,3) and $subscribe=0";
			break;
		}

		//	var_dump($query);

	}
	else if($search_unsubscribed==1)
	$query="approved not in (0,3) and $subscribe=0";
	else if($search_unconfirmed==1)
	$query="approved=3";
	else
	$query=stripslashes($query);
	if($query)
	$query2="where $query".($search_unconfirmed?"":" and approved not in (0,3)");
	else if($check=='Search' && !$bad_form) {
		$query2='where approved not in (0,3)';
		$query='approved not in (0,3)';
	}
	else
	$query2='where 1=0';
	$query=urlencode($query);

	echo "<form action=$PHP_SELF method=post name=results>
	<input type=hidden name=form_id value='$form_id'>";
	if(($check=='Search' && !$bad_form) || isset($start)
	|| isset($start0) || $search_unsubscribed || $search_unconfirmed) {
		echo "
	    <table border=1 cellpadding=0 cellspacing=0 width=100% bordercolor=#CCCCCC style='border-collapse:collapse;'>
	    <tr background=../images/title_bg.jpg>";

		/* choose the fields that are marked to be shown
		* in the contacts list as headers */
		$q=sqlquery("
	    select name,type from form_fields
	    where search=1 and form_id='$form_id' and
		type not in (".join(',',$dead_fields).")
	    order by sort asc
	    limit $cmgr_max_hdr_fields");
		$fields=array("contacts_$form2.contact_id",'cipher_init_vector');
		if($subscribe) {
			$fields[]=$subscribe;
		}
		$field_types=array();
		while(list($fld,$type)=sqlfetchrow($q)) {
			$fld2=castrate($fld);
			$fields[]=$fld2;
			$field_types[]=$type;
			echo "<td class=Arial12Blue>";
			if(!in_array($type,$multival_arr)) {
				echo "<u><a href=$PHP_SELF?form_id=$form_id&sort=$fld2&query=$query&group_by=".urlencode($group_by)."&tables=$tables&rows=$rows&check=$check&start=$start>";
			}
			echo "<b>$fld</b>";
			if(!in_array($type,$multival_arr)) {
				echo "</a></u>";
			}
			echo "</td>";
		}
		echo "<td class=Arial12Blue><b>Interest Group</b></td>";
		echo "</tr>";
		if($sort)
		$order="order by $sort";
		else
		$order='';
		if($output_rows)
		$rows=$output_rows;
		if(!$rows)
		$rows=10;
		if($start0)
		$start=($start0-1)*$rows;
		else if(!$start)
		$start=0;

		#echo "<hr>$query2";
		$q=sqlquery("
	    select ".join(',',$fields)." from contacts_$form2 $tables
	    $query2
	    $group_by
	    $order");
		if($subscribe) {
			$nfields=3;
		}
		else {
			$nfields=2;
		}
		$numrows=-1;

		if($form_id && (in_array($form_id,$viewedit_access_arr) ||
		in_array($form_id,$del_access_arr))) // -->
		while($vals=sqlfetchrow($q)) {
			$intgrp_id=$intgrp=array();
			$q1=sqlquery("
		select contact_categories.category_id,name
		from contact_categories,contacts_intgroups_$form2
		where contact_categories.category_id=contacts_intgroups_$form2.category_id and
		    contacts_intgroups_$form2.contact_id=$vals[0]");
			while(list($category_id,$tmpgrp)=sqlfetchrow($q1)) {
				$intgrp[]=$tmpgrp;
				$intgrp_id[]=$category_id;
			}
			$numrows++;
			if($numrows<$start || $numrows>=$start+$rows) {
				continue;
			}
			if($jkl++ % 2) {
				$trash='trash_small.gif';
				$bgcolor='f4f4f4';
			}
			else {
				$trash='trash_small.gif';
				$bgcolor='f4f4f4';
			}
			if($subscribe) {
				if($vals[$nfields-1]==1) {
					$font='blue';
				}
				else {
					$font='red';
				}
			}
			else {
				$font='blue';
			}
			echo "<tr bgcolor=#$bgcolor>";
			for($i=$nfields;$i<count($vals)/2;$i++) {
				echo "<td class=Arial11Grey>";
				if($i==$nfields) {
					echo "<input type=checkbox name=id[] value='$vals[0]'>&nbsp;&nbsp;&nbsp;&nbsp;
			<a href=".($contact_use_secure?$secure:"http://$server_name2")."/admin/contacts.php?op=edit&id=$vals[0]&form_id=$form_id&setsid=$sid&start=$start&sort=$sort&query=$query&group_by=".urlencode($group_by)."&tables=$tables><u>";
				}
				/* decrypt secure fields */
				if(in_array($field_types[$i-$nfields],$secure_fields)) {
					$vals[$i]=decrypt($vals[$i],$cipher_key,$vals[1]);
				}
				/* boolean fields */
				if(in_array($field_types[$i-$nfields],$checkbox_arr)) {
					if($vals[$i]) {
						$vals[$i]='Yes';
					}
					else {
						$vals[$i]='No';
					}
				}
				/* multi-value indexed fields */
				if(in_array($field_types[$i-$nfields],$multival_arr2)) {
					if ($vals[$i] <> '') {
						$contact_i = array();
						$contact_result=sqlquery("
			    select name from contacts_$form2"."_$fields[$i]"."_options
			    where contacts_$form2"."_$fields[$i]"."_option_id IN ($vals[$i])");
						while ($contact_row = sqlfetchrow($contact_result)) {
							array_push($contact_i, $contact_row['name']);
						}
						$vals[$i] = join(" ", $contact_i);
					}
				} elseif(in_array($field_types[$i-$nfields],$multival_arr)) {
					list($vals[$i])=sqlget("
			select name from contacts_$form2"."_$fields[$i]"."_options
			where contacts_$form2"."_$fields[$i]"."_option_id='$vals[$i]'");
				}
				/* convert dates */
				if($field_types[$i-$nfields]==11) {
					list($y,$m,$d)=explode('-',$vals[$i]);
					$vals[$i]="$m-$d-$y";
				}
				if($i==$nfields && !$vals[$i])
				$vals[$i]="&lt;empty&gt;";
				echo "<font color=$font>$vals[$i]</font>&nbsp;";
				if($i==$nfields) {
					echo "</u></a>";
				}
				echo "</td>";
			}
			echo "<td class=Arial11Grey>";
			/* there are no other fields except int group */
			if($i==$nfields) {
				echo "<a href=".($contact_use_secure?$secure:"http://$server_name2")."/admin/contacts.php?op=edit&id=$vals[0]&form_id=$form_id&setsid=$sid><u>";
			}
			echo "<font color=$font>".join('<br>',$intgrp)."</font>&nbsp;";
			if($i==$nfields) {
				echo "</u></a>";
			}
			echo "</td>";
			echo "</tr>";
		}
		echo "</table>";
	}

	if(has_right('Administration Management',$user_id)) {
		echo "<p>";
		list($numrows3)=sqlget("
	    select count(*) from contacts_$form2 where approved not in (0,3)");
		if($subscribe) {
			$total=count_subscribers($form2);
			$sub=count_subscribed($form2,$form_id,1);
			$unsub=$total-$sub;
			echo "<p>
		    <b>Un-Subscribed Users</b><br>
		    <a href=$PHP_SELF?search_unsubscribed=1&form_id=$form_id><u>Click here</u></a>
			to view all user(s) that are un-subscribed.</p>";
			echo "<b>There are $sub total contacts in this list that are subscribed.<br>
	        There are <a href=$PHP_SELF?search_unsubscribed=1&form_id=$form_id><u>$unsub contacts</u></a> in this list that are not subscribed.</b><br>";
		}
		echo "<b>There are a total of $numrows3 contact is this list.</b><br>";
		list($confirm_email)=sqlget("
	    select confirm_email from forms where form_id='$form_id'");
		if($confirm_email) {
			list($unconfirmed)=sqlget("select count(*) from contacts_$form2 where approved=3");
			echo "<p><b>Un-Confirmed Users</b><br>
		<b>You have a total of $unconfirmed un-confirmed users in your database.<br>
		<A href=$PHP_SELF?search_unconfirmed=1&form_id=$form_id><u>Click here</u></a>
		    to view all user(s) that have not confirmed via email.</b><br>";
		}
		if(($check=='Search' && !$bad_form) || isset($start) ||
		$search_unsubscribed || $search_unconfirmed) {
			$numrows2=((float)(++$numrows-1)/(float)$rows);
			if($numrows2>1) {
				echo "<br><b>You have ".round($numrows2+1)." pages of contacts.
		    You are now viewing page ".round($start/$rows+1).".
		    Please click on the numbers below</b>
	        <br>Pages";
			}
			/* if we have more than X pages, show links only to the first of them */
			$max_pages=5;
			if($start>=$rows)
			echo "&nbsp;<a href=$PHP_SELF?start=".($start-$rows)."&form_id=$form_id&sort=$sort&query=$query&group_by=".urlencode($group_by)."&tables=$tables&rows=$rows&search_unconfirmed=$search_unconfirmed><u>&lt;&lt; Back</u></a>&nbsp;";
			for($i=0;$numrows2>1 && $i<=$numrows2 && $i < $max_pages;$i++) {
				echo "&nbsp;";
				if($i*$rows != $start) {
					echo "<a href=$PHP_SELF?start=".($i*$rows)."&form_id=$form_id&sort=$sort&query=$query&group_by=".urlencode($group_by)."&tables=$tables&rows=$rows&search_unconfirmed=$search_unconfirmed><u>";
				}
				echo $i+1;
				if($i*$rows != $start) {
					echo "</u></a>";
				}
				if($i && !($i % 20)) {
					echo "<br>";
				}
			}
			if($start+$rows<$numrows2*$rows)
			echo "&nbsp;<a href=$PHP_SELF?start=".($start+$rows)."&form_id=$form_id&sort=$sort&query=$query&group_by=".urlencode($group_by)."&tables=$tables&rows=$rows&search_unconfirmed=$search_unconfirmed><u>Next &gt;&gt;</u></a>&nbsp;";
			if($numrows2>1)
			echo " of ".ceil($numrows2)."<br>";
			if($numrows2 > 1)
			echo "Jump to page number <input type=text name=start0 size=5>
		    <input type=hidden name=sort value=\"$sort\">
		    <input type=hidden name=query value=\"".urldecode($query)."\">
		    <input type=hidden name=group_by value=\"$group_by\">
		    <input type=hidden name=tables value=\"$tables\">
		    <input type=hidden name=rows value=\"$rows\">
		    <input type=hidden name=search_unconfirmed value=\"$search_unconfirmed\">
		    <input type=submit name=go value=Go>";

			echo "<br><script language=javascript>
var state=false;
function select_all() {
    var i;

    for(i=0;i<document.results.elements.length;i++) {
	// alert(document.results[i].type);
	if(document.results[i].type=='checkbox') {
	    if(state) {
		document.results[i].checked=false;
	    }
	    else {
		document.results[i].checked=true;
	    }
	}
	else if(document.results[i].type=='select-multiple') {
	    for(j=0;j<document.results[i].length;j++) {
		if(state) {
		    document.results[i][j].selected=false;
		}
		else {
		    document.results[i][j].selected=true;
		}	
	    }
	}
    }
    state=!state;
}
</script>
	<br><a href='javascript:select_all()'>
	    <img src=../images/selectallcontacts.gif border=0></a><br>
	<input type=image name=del onclick=\"javascript:return confirm('Are you sure you want to delete the selected records?')\" src=../images/deleteallcontacts.gif border=0><br>
	
	<br><b>Change Interest Group of all selected contacts to:</b><br>
	<select name=intgroup_id>
	<option value=''>- Please select -</option>
	".formatdbq("
	    select contact_categories.category_id as id,name
	    from contact_categories,forms_intgroups
	    where contact_categories.category_id=forms_intgroups.category_id and
		forms_intgroups.form_id='$form_id'
	    order by sort",
			"<option value=$(id)>$(name)</a>\n")."
	</select><input type=submit name=op value=Change><br>";
		}

		echo "<br>
	<table border=0 cellpadding=0 cellspacing=0 width=100%>
	<tr><td width=50% valign=top>
	<b>Download Management Area:</b><br>";
		list($has_contacts)=sqlget("select count(*) from contacts_$form2");
		$bad_ul_text="You cannot use this upload function because there are no\\n".
		"records in the system. In order to upload records you must\\n".
		"first download emails so you can get the layout of the file\\n".
		"used for uploading. You must first have at least one record\\n".
		"in the system before you can download the file to get the\\n".
		"record layout. Please visit our Upload / Download User Guide\\n".
		"which is a link on the bottom of this page.";
		$bad_dl_text="In order to download records, you must have\\n".
		"at least one record in the system.";
		if(($check=='Search' && !$bad_form) || isset($start) ||
		$search_unsubscribed || $search_unconfirmed) {
			if($has_contacts)
			echo "<input type=image name=dlselected src=../images/downloadselect.gif border=0><br>
		    <a href=$PHP_SELF?op=download&form_id=$form_id&query=$query&tables=$tables&group_by=$group_by>Download All Contacts from search</a><br>";
			else echo "<A href=\"javascript:alert('$bad_dl_text')\"><img src=../images/downloadselect.gif border=0></a><br>";
		}
		if($has_contacts)
		echo "<input type=image name=dlall src=../images/downloadall.gif border=0>";
		else echo "<A href=\"javascript:alert('$bad_dl_text')\"><img src=../images/downloadall.gif border=0></a>";
		/*
		$ff_dir = dirname(__FILE__)."/../ftp/";
		$ff = opendir($ff_dir);
		$file_list = "";
		while($file_name = readdir($ff)) {
		if ($file_name <> '.cvsignore' && is_file($ff_dir . $file_name) && is_readable($ff_dir . $file_name)) {
		$file_list .= "<option>$file_name</option>";
		}
		}
		closedir($ff);*/
		echo "<br>
	<font color=#000099>Use <input type=text name=delim value=',' size=1> as delimiter (You may use the word tab for tab files)</font><br>
	<font color=#000099>Secondary delimiter is <input type=text name=delim2 value=':' size=1>
	<A href=\"javascript:alert('The secondary delimiter is used inside the fields\\n".
		"that can hold multiple values, for example\\n".
		"interest groups field will look like &quot;group 1:group 2:group 3&quot;')\"><u>more info</u></a></font><br>
	</form>
	</td><td width=50% valign=top>
	<b>Upload Management Area:</b><br>
	<form action=$PHP_SELF method=POST enctype='multipart/form-data'>
	File to upload: <input type=file name=f_import><br>
	
	<input type=hidden name=form_id value='$form_id'>
	<font color=#000099>Use <input type=text name=delim value=',' size=1> as delimiter (You may use the word tab for tab files)</font><br>
	<font color=#000099>Secondary delimiter is <input type=text name=delim2 value=':' size=1>
	<A href=\"javascript:alert('The secondary delimiter is used inside the fields\\n".
		"that can hold multiple values, for example\\n".
		"interest groups field will look like &quot;group 1:group 2:group 3&quot;')\"><u>more info</u></a></font><br>";
		if($has_contacts)
		echo "<input type=image name=import src=../images/upload.gif value=Import border=0><br>";
		else echo "<A href=\"javascript:alert('$bad_ul_text')\"><img src=../images/upload.gif border=0></a><br>";
		echo "</form>
	</td></tr>";
		echo "</table>
	<p><b>To view our Uploading / Downloading User Guide please click
	<a href=download.php><u>here</u></a>.</b>";
	}
}

include "bottom.php";

/* construct the SELECT query by given variables that contains result
* of the form POST that was created with display_fields() */
function gen_query($vars,$search_by_dates) {
	while(list($field,$val)=each($vars)) {
		$tmp_arr=explode('_z_',$field);
		$tmp_arr2=explode('_',$field);
		if($tmp_arr[0]=='form') {
			array_shift($tmp_arr);
			$field=array_shift($tmp_arr);
			$subfield=array_shift($tmp_arr);

			/* handle the date fields */
			if($subfield=='day_from' || $subfield=='month_from' || $subfield=='year_from') {
				if($vars["form_z_$field"."_z_year_from"] &&
				$vars["form_z_$field"."_z_month_from"]) {
					$val=$vars["form_z_$field"."_z_year_from"].'-'.
					(strlen($vars["form_z_$field"."_z_month_from"])==1?'0':'').$vars["form_z_$field"."_z_month_from"];
					if($vars["form_z_$field"."_z_day_from"])
					$val.='-'.(strlen($vars["form_z_$field"."_z_day_from"])==1?'0':'').$vars["form_z_$field"."_z_day_from"];
					else
					$val.='-01';
					$vars["form_z_$field"."_z_year_from"]='';
					$vars["form_z_$field"."_z_month_from"]='';
					$vars["form_z_$field"."_z_day_from"]='';
					if(!$search_by_dates)
					$val='';
					else
					$fields[]="$field>='$val'";
					continue;
				}
			}
			if($subfield=='day_to' || $subfield=='month_to' || $subfield=='year_to') {
				if($vars["form_z_$field"."_z_year_to"] &&
				$vars["form_z_$field"."_z_month_to"]) {
					$val=$vars["form_z_$field"."_z_year_to"].'-'.
					(strlen($vars["form_z_$field"."_z_month_to"])==1?'0':'').$vars["form_z_$field"."_z_month_to"];
					if($vars["form_z_$field"."_z_day_to"])
					$val.='-'.(strlen($vars["form_z_$field"."_z_day_to"])==1?'0':'').$vars["form_z_$field"."_z_day_to"];
					else
					$val.='-01';
					$vars["form_z_$field"."_z_year_to"]='';
					$vars["form_z_$field"."_z_month_to"]='';
					$vars["form_z_$field"."_z_day_to"]='';
					if(!$search_by_dates)
					$val='';
					else
					$fields[]="$field<='$val'";
					continue;
				}
			}
			if($val) {
				if (is_array($val)) {
					$val1=array();
					foreach($val as $v) {
						array_push($val1, "FIND_IN_SET('$v', `$field`)");
					}
					$fields[]=join(" AND ", $val1);
				} else {
					$val=addslashes($val);
					$fields[]="$field like '%$val%'";
				}
			}
		}
		/* search by date added */
		else if(($tmp_arr2[1]=='from' || $tmp_arr2[1]=='to') &&
		$vars["s_".$tmp_arr2[1]."_year"] &&
		$vars["s_".$tmp_arr2[1]."_month"] &&
		$vars["s_".$tmp_arr2[1]."_day"]) {
			$val=$vars["s_".$tmp_arr2[1]."_year"].'-'.
			$vars["s_".$tmp_arr2[1]."_month"].'-'.
			$vars["s_".$tmp_arr2[1]."_day"];
			if($tmp_arr2[1]=='from')
			$fields[]="added>='$val'";
			else if($tmp_arr2[1]=='to')
			$fields[]="added<='$val'";
			$vars["s_".$tmp_arr2[1]."_year"]=
			$vars["s_".$tmp_arr2[1]."_month"]=
			$vars["s_".$tmp_arr2[1]."_day"]='';
		}
	}
	return join(' and ',$fields);
}

/* callback to obtain the field value for the contact record */
function def_contact_value($field) {
	global $field_type,$contact,$cipher_key,$iv,$secure_fields,$op;
	if(in_array($field_type[$field],$secure_fields)) {
		$contact[$field]=decrypt($contact[$field],$cipher_key,$iv);
	}
	else if($field_type[$field]==6 && $op=='add')
	$contact[$field]=1;
	return $contact[$field];
}

function def_empty($field) {
	return '';
}

?>
