Example #1
0
	/**
	 * insert new entry to db
	 *
	 * @access	public
	 * @return	null
	 */

    function insert_new_entry()
    {

    
        $default	= array('name', 'email');
        
        $all_fields	= '';
        
        $fields		= array();
        
        $entry_id	= '';

		$msg		= array();
        
        foreach ($default as $val)
        {
			if ( ! isset($_POST[$val]))
			{
				$_POST[$val] = '';
			}
        }        
               
        //	----------------------------------------
        //	Fetch the freeform language pack
        //	----------------------------------------
        
        ee()->lang->loadfile('freeform');        
                
        //	----------------------------------------
        //	Is the user banned?
        //	----------------------------------------
        
        if (ee()->session->userdata['is_banned'] == TRUE)
        {
        	return ee()->output->show_user_error('general', array(ee()->lang->line('not_authorized')));
        }
                
        //	----------------------------------------
        //	Is the IP address and User Agent required?
        //	----------------------------------------
                
        if ( $this->check_yes($this->_param('require_ip')) )
        {
        	if (ee()->session->userdata['group_id'] != 1 AND ee()->input->ip_address() == '0.0.0.0')
        	{            
            	return ee()->output->show_user_error('general', array(ee()->lang->line('not_authorized')));
        	}        	
        }
        
        //	----------------------------------------
		//	Is the nation of the user banned?
        //	----------------------------------------
        
		ee()->session->nation_ban_check();
        
        //	----------------------------------------
        //	Blacklist/Whitelist Check
        //	----------------------------------------
        
        if ($this->check_yes(ee()->blacklist->blacklisted) && $this->check_no(ee()->blacklist->whitelisted))
        {
        	return ee()->output->show_user_error('general', array(ee()->lang->line('not_authorized')));
        }
        
        //	----------------------------------------
        //	Check duplicates
        //	----------------------------------------
        
        if ( $this->_param('prevent_duplicate_on') 			AND 
			 $this->_param('prevent_duplicate_on') != '' 	AND 
				( 	ee()->session->userdata['group_id'] != 1 	OR 	
					ee()->input->get_post('email') != '' ) 
		   )
        {
        	$sql	= "	SELECT 	COUNT(*) 
						AS 		count 
						FROM 	exp_freeform_entries 
						WHERE 	status != 'closed'";

			if ( $this->_param('form_name') )
			{
				$sql	.= " AND form_name = '".ee()->db->escape_str($this->_param('form_name'))."'";
			}

			if ( $this->_param('prevent_duplicate_on') == 'member_id' AND ee()->session->userdata['member_id'] != '0' )
			{
				$sql	.= " AND author_id = '".ee()->db->escape_str(ee()->session->userdata['member_id'])."'";
			}
			elseif ( $this->_param('prevent_duplicate_on') == 'ip_address' 	AND 
					  ee()->input->ip_address() != '0.0.0.0' 				AND 
					  ee()->session->userdata['group_id'] != 1)
			{
				$sql	.= " AND ip_address = '".ee()->db->escape_str(ee()->input->ip_address())."'";
			}
			else
			{
				$sql	.= " AND email = '".ee()->db->escape_str(ee()->input->get_post('email'))."'";
			}
        	
        	$dup	= ee()->db->query( $sql );
        	
        	if ( $dup->row('count') > 0 )
        	{
				return ee()->output->show_user_error('general', array(ee()->lang->line('no_duplicates')));
        	}
        }        
        
        //	----------------------------------------
        //	Start error trapping on required fields
        //	----------------------------------------
        
        $errors	= array();
        
        // Are there any required fields?
        
        if ( $this->_param('ee_required') != '' )
        {
        	$required_fields	= preg_split("/,|\|/" ,$this->_param('ee_required'));
        	
			//	----------------------------------------
			//	Let's get labels from the DB
			//	----------------------------------------
			
        	$query	= ee()->db->query(
				"SELECT * 
				 FROM 	exp_freeform_fields"
			);
        	
        	$labels	= array();
        	
        	if ( $query->num_rows() > 0 )
        	{        	
				foreach ($query->result_array() as $row)
				{
					$labels[$row['name']]	= $row['label'];
				}        	
        	
				// Check for empty fields
				
				foreach ( $required_fields as $val )
				{
					if ( ! ee()->input->post($val) OR ee()->input->post($val) == '' )
					{
						if (array_key_exists($val, $labels))
						{
							$errors[] = ee()->lang->line('field_required') . ' ' . $labels[$val];
						}
						else
						{
							$errors[] = ee()->lang->line('not_in_field_list') . ' ' . $val;
						}  
					}
				}
				
				//	End empty check 
			}
			
        	//	End labels from DB 
        
			//	----------------------------------------
			//	Do we require an email address?
			//	----------------------------------------
			
			if ( isset( $labels['email'] ) AND ee()->input->get_post('email') )
			{
				//	----------------------------------------
				//	Valid email address?
				//	----------------------------------------
				
				//1.x
				if (APP_VER < 2.0)
				{
					if ( ! class_exists('Validate'))
					{
						require PATH_CORE.'core.validate'.EXT;
					}
					
					$VAL = new Validate( array( 'email' => ee()->input->get_post('email') ) );
				}
				//2.x
				else
				{
					if ( ! class_exists('EE_Validate'))
					{
						require APPPATH . 'libraries/Validate'.EXT;
					}
					
					$VAL = new EE_Validate( array( 'email' => ee()->input->get_post('email') ) );
				}
					
				$VAL->validate_email();
		
				//	----------------------------------------
				//	Display errors if there are any
				//	----------------------------------------
		
				if (count($VAL->errors) > 0)
				{
					return ee()->output->show_user_error('general', $VAL->errors );
				}
			}
        }
        
		//	----------------------------------------
		//	Are we trying to accept file uploads?
		//	----------------------------------------
        
        if ( $this->_param('file_upload') != '' AND $this->upload_limit = $this->_param('upload_limit') )
        {
        	$this->_upload_files( TRUE );
        }
		
		//	----------------------------------------
		//	'freeform_module_validate_end' hook.
		//	 - This allows developers to do more form validation.
		//	----------------------------------------
		
		if (ee()->extensions->active_hook('freeform_module_validate_end') === TRUE)
		{
			$errors = ee()->extensions->universal_call('freeform_module_validate_end', $errors);
			if (ee()->extensions->end_script === TRUE) return;
		}
        //	----------------------------------------
        
        //	----------------------------------------
        //	Do we have errors to display?
        //	----------------------------------------
        
        if (count($errors) > 0)
        {
           return ee()->output->show_user_error('submission', $errors);
        }
        
        //	----------------------------------------
        //	Do we require captcha?
        //	----------------------------------------
		
		if ( $this->_param('require_captcha') AND $this->check_yes($this->_param('require_captcha')) )
		{
			if ( $this->check_yes(ee()->config->item('captcha_require_members'))  OR  
					( $this->check_no(ee()->config->item('captcha_require_members')) AND 
					  ee()->session->userdata('member_id') == 0)
			   )
			{
				if ( ! ee()->input->post('captcha') OR ee()->input->post('captcha') == '')
				{
					return ee()->output->show_user_error('submission', ee()->lang->line('captcha_required'));
				}
				else
				{
					$res = ee()->db->query(
						"SELECT COUNT(*) 
						 AS 	count 
						 FROM 	exp_captcha 
						 WHERE 	word='" . ee()->db->escape_str(ee()->input->post('captcha')) . "' 
						 AND 	ip_address = '" . ee()->db->escape_str(ee()->input->ip_address()) . "' 
						 AND 	date > UNIX_TIMESTAMP()-7200"
					);
				
					if ($res->row('count') == 0)
					{
						return ee()->output->show_user_error('submission', ee()->lang->line('captcha_incorrect'));
					}
				
					// Moved because of file uploading errors
					/*
					  ee()->db->query("DELETE FROM exp_captcha 
											WHERE (word='".ee()->db->escape_str($_POST['captcha'])."' 
											AND ip_address = '".ee()->db->escape_str(ee()->input->ip_address())."') 
											OR date < UNIX_TIMESTAMP()-7200");
					*/
				}
			}
		}        
        
        //	----------------------------------------
        //	Check Form Hash
        //	----------------------------------------
        
        if ( $this->check_yes(ee()->config->item('secure_forms')) )
        {        	
            $query = ee()->db->query(
				"SELECT 	COUNT(*) 
				 AS 		count 
				 FROM 		exp_security_hashes 
				 WHERE 		hash='" . ee()->db->escape_str(ee()->input->post('XID')) . "' 
				 AND 		ip_address = '" . ee()->db->escape_str(ee()->input->ip_address())."' 
				 AND	 	date > UNIX_TIMESTAMP()-7200"
			);
        
			//email_change
            if ($query->row('count') == 0)
            {
				return ee()->output->show_user_error('general', array(ee()->lang->line('not_authorized')));
            }
            
            // Moved because of file uploading errors                    
			/* ee()->db->query("DELETE FROM exp_security_hashes 
									 WHERE (hash='".ee()->db->escape_str($_POST['XID'])."' 
									 AND ip_address = '".ee()->db->escape_str(ee()->input->ip_address())."') 
									 OR date < UNIX_TIMESTAMP()-7200");
			*/
        }
                        
        //	----------------------------------------
        //	Let's get all of the fields from the
        //	database for testing purposes
        //	----------------------------------------
        
        $fields['form_name']	= "Collection Name";
        
        $query		= ee()->db->query(
			"SELECT 	name, label 
			 FROM 		exp_freeform_fields 
			 ORDER BY 	field_order 
			 ASC"
		);
        
        if ($query->num_rows() > 0)
        {
        	foreach($query->result_array() as $row)
        	{
        		$fields[$row['name']]	= $row['label'];
        	}
        }
        else
        {
        	return false;
        }        
        
        //	----------------------------------------
        //	Build the data array
        //	----------------------------------------
        
        $exclude	= array('ACT', 'RET', 'URI', 'PRV', 'XID', 'return', 'ee_notify', 'ee_required', 'submit');
							
		$include	= array('status');
        
        $data		= array(
            'author_id'		=> ee()->session->userdata['member_id'],
            'group_id'		=> ee()->session->userdata['group_id'],
            'ip_address'	=> ee()->input->ip_address(),
            'entry_date'	=> ee()->localize->now,
            'edit_date'		=> ee()->localize->now
		);
        			
        foreach ( $_POST as $key => $val )
        {
			//	----------------------------------------
        	//	If the given field is not a FreeForm
        	//	field or not in our include list, then
        	//	skip it.
			//	----------------------------------------
        	
        	if ( ! array_key_exists( $key, $fields ) AND ! in_array( $key, $include ) ) continue;
        	
			//	----------------------------------------
        	//	If the given field is in our exclude
        	//	list, then skip it.
			//	----------------------------------------
			
        	if ( in_array( $key, $exclude ) ) continue;
        	
        	if ( $key == 'website' )
        	{
        		ee()->security->xss_clean( prep_url( ee()->input->post('website') ) );
        		
        		$data[$key]	= ee()->input->post($key);
        	}
        	
			// If the field is a multi-select field, then handle it as such.
			if ( is_array( $val ) )
			{
				$val = implode( "\n", $val );
				
				$data[$key] = ee()->security->xss_clean($val);
			}
			else
			{
				$data[$key] = ee()->security->xss_clean($val);
			}
        }
		
		//backup for form name in case it isnt in the post data
		if ( ! isset($data['form_name']) AND $this->_param('form_name') !== FALSE)
		{
			$data['form_name'] = $this->_param('form_name');
		}
		
		//check to see if there is any missing data that we have in the params:
		/*foreach($fields as $f_key => $f_value)
		{
			if ( ! isset($data[$f_key]) AND $this->_param($f_key) !== FALSE)
			{
				$data[$f_key] = $this->_param($f_key);
			}
		}*/
		
		//i dont want to remove this because we might need it for some god awful reason, but it screws with stuff.
		$fields['subject']		= "Subject";
		
		//	----------------------------------------
		//	'freeform_module_insert_begin' hook.
		//	 - This allows developers to do one last thing before Freeform submit is ended.
		//	----------------------------------------
		
		if (ee()->extensions->active_hook('freeform_module_insert_begin') === TRUE)
		{
			$data = ee()->extensions->universal_call('freeform_module_insert_begin', $data);
			if (ee()->extensions->end_script === TRUE) return;
		}
        
		//	------------------------------------------------------------------------------------
      	//  Discarded data email_change
		//  ------------------------------------------------------------------------------------
              
        //	----------------------------------------
        //	Are we discarding some field values and preventing data save on them?
        //	----------------------------------------
        
        if ( $this->_param('discard_field') != '' )
        {        
        	foreach ( explode( "|", $this->_param('discard_field') ) as $val )
        	{
        		if ( ! empty( $data[ $val ] ) )
        		{
        			$data[ $val ]	= ee()->lang->line('discarded_field_data');
        		}
        	}       
        }

		//	------------------------------------------------------------------------------------
      	//  end Discarded data email_change
		//  ------------------------------------------------------------------------------------


        //	----------------------------------------
        //	Submit data into DB
        //	----------------------------------------

		$sql			= ee()->db->insert_string( 'exp_freeform_entries', $data ); //email_change
		
		$query			= ee()->db->query( $sql );
		
		$this->entry_id	= ee()->db->insert_id();
        
        //	----------------------------------------
        //	Process file uploads
        //	----------------------------------------
        
        if ( count( $this->upload ) > 0 )
        {
        	$this->_upload_files();
        }	
        
		//----------------------------------------
		//	 Delete CAPTCHA and Form Hash - Moved here because of File Upload Error possibilities
		//	----------------------------------------
		
		if ( $this->check_yes($this->_param('require_captcha')) && isset($_POST['captcha']))
		{
			ee()->db->query(
				"DELETE FROM 	exp_captcha 
				 WHERE	 		(word='" . ee()->db->escape_str(ee()->input->post('captcha')) . "' 
				 AND 			ip_address = '" . ee()->db->escape_str(ee()->input->ip_address()) . "') 
				 OR 			date < UNIX_TIMESTAMP()-7200"
			);
		}
        
        if ( $this->check_yes(ee()->config->item('secure_forms')) && ee()->input->post('XID') )
        {        	
            ee()->db->query(
				"DELETE FROM 	exp_security_hashes 
				 WHERE 			(hash='" . ee()->db->escape_str(ee()->input->post('XID')) . "' 
				 AND 			ip_address = '" . ee()->db->escape_str(ee()->input->ip_address()) . "') 
				 OR 			date < UNIX_TIMESTAMP()-7200"
			);
        }
		
        //	----------------------------------------
        //	Send notifications
        //	----------------------------------------
        
        if ( $this->_param('ee_notify') != '' )
        {
        	$recipients	= preg_split("/,|\|/" , $this->_param('ee_notify') );
        	
        	$template	= ( $this->_param('template') AND $this->_param('template') != '' ) ? 
							$this->_param('template'): 'default_template';
		
			//	----------------------------------------
			//	Generate message
			//	----------------------------------------
			
			$msg		= array();
			
			$query		= ee()->db->query(
				"SELECT * 
				 FROM 	exp_freeform_templates 
				 WHERE 	template_name = '" . ee()->db->escape_str($template) . "' 
				 AND 	enable_template = 'y' 
				 LIMIT 	1"
			);

			if ( $query->num_rows() == 0 )
			{
				return ee()->output->show_user_error('general', array(ee()->lang->line('template_not_available')));
			}
			
			$msg['from_name']	= ( $query->row('data_from_name') != '' ) ?
			 							$query->row('data_from_name'): ee()->config->item('webmaster_name');

			$msg['from_email']	= ( $query->row('data_from_email') != '' ) ?
			 							$query->row('data_from_email'): ee()->config->item('webmaster_email');

			$msg['subject']		= $query->row('data_title');

			$msg['msg']			= $query->row('template_data');

			$wordwrap			= $this->check_yes($query->row('wordwrap'));
			
			$msg['subject']		= str_replace( 	LD.'entry_date'.RD, 
											   	ee()->localize->set_human_time(ee()->localize->now), 
												$msg['subject'] );
			
			$msg['msg']			= str_replace( 	LD.'entry_date'.RD, 
												ee()->localize->set_human_time(ee()->localize->now), 
												$msg['msg'] );
			
			$msg['subject']		= str_replace( 	LD.'freeform_entry_id'.RD, $this->entry_id, $msg['subject'] );
			$msg['msg']			= str_replace( 	LD.'freeform_entry_id'.RD, $this->entry_id, $msg['msg'] );
			
			if (preg_match_all("/".LD."(entry_date)\s+format=([\"'])(.*?)\\2".RD."/is", 
							   $msg['subject'].$msg['msg'], $matches)
			   )
			{
				for ($j = 0; $j < count($matches[0]); $j++)
				{	
					$val = $matches[3][$j];
					
					foreach (ee()->localize->fetch_date_params($matches[3][$j]) AS $dvar)
					{
						$val = str_replace($dvar, ee()->localize->convert_timestamp($dvar, ee()->localize->now, TRUE), $val);					
					}
					
					$msg['subject']		= str_replace( $matches[0][$j], $val, $msg['subject'] );
			
					$msg['msg']			= str_replace( $matches[0][$j], $val, $msg['msg'] );
				}
			}
			
			//	----------------------------------------
			//	Parse conditionals
			//	----------------------------------------
			
			//template isn't defined yet, so we have to fetch it
			//1.x
			if(APP_VER < 2.0)
			{
				if ( ! class_exists('Template'))
				{
					require PATH_CORE.'core.template'.EXT;
				}
			
				$local_TMPL	= new Template();
			}
			//2.x
			else
			{
				ee()->load->library('template');
				$local_TMPL =& ee()->template;
			}
			
			$data['attachment_count']		= count( $this->attachments );
			
			//i have no idea why this is being done instead of just using $data...			
			$cond		= $data;
			
			foreach( $msg as $key => $val )
			{
				$msg[$key]	= $local_TMPL->advanced_conditionals( 
					ee()->functions->prep_conditionals( $msg[$key], $cond ) 
				);
			}

			unset( $cond );

			//	----------------------------------------
			//	Parse individual fields
			//	----------------------------------------
			
			$exclude	= array('submit');
			
			foreach ( $msg as $key => $val )
			{
				//	----------------------------------------
				//	Handle attachments
				//	----------------------------------------
				
				$msg[$key]	= str_replace( LD."attachment_count".RD, $data['attachment_count'], $msg[$key] );
						
				if ( $key == 'msg' )
				{
					$all_fields	.= "Attachments: ".$data['attachment_count']."\n";
					
					$n		= 0;
					
					foreach ( $this->attachments as $file )
					{
						$n++;						
						$all_fields	.= "Attachment $n: ".$file['filename']." ".$this->upload['url'].$file['filename']."\n";
					}
				}
				
				if ( preg_match( "/".LD."attachments".RD."(.*?)".LD."\/attachments".RD."/s", $msg[$key], $match ) )
				{
					if ( count( $this->attachments ) > 0 )
					{
						$str	= '';
						
						foreach ( $this->attachments as $file )
						{
							$tagdata	= $match['1'];
							$tagdata	= str_replace( LD."fileurl".RD, $this->upload['url'].$file['filename'], $tagdata );
							$tagdata	= str_replace( LD."filename".RD, $file['filename'], $tagdata );
							$str		.= $tagdata;
						}
						
						$msg[$key]	= str_replace( $match['0'], $str, $msg[$key] );
					}
					else
					{
						$msg[$key]	= str_replace( $match['0'], "", $msg[$key] );
					}
				}
				
				//	----------------------------------------
				//	Loop
				//	----------------------------------------
				
				foreach ( $fields as $name => $label )
				{
					if ( isset( $data[$name] ) AND ! in_array( $name, $exclude ) )
					{
						$msg[$key]	= str_replace( LD.$name.RD, $data[$name], $msg[$key] );
						
						//	----------------------------------------
						//	We don't want to concatenate for every
						//	time through the main loop.
						//	----------------------------------------
						
						if ( $key == 'msg' )
						{
							$all_fields	.= $label.": ".$data[$name]."\n";
						}
					}
					else
					{
						$msg[$key]	= str_replace( LD.$name.RD, '', $msg[$key] );
					}
				}
			}
			
			
			//	----------------------------------------
			//	Parse all fields variable
			//	----------------------------------------
			
			if ( stristr( $msg['msg'], LD.'all_custom_fields'.RD ) )
			{
				$msg['msg']	= str_replace( LD.'all_custom_fields'.RD, $all_fields, $msg['msg'] );
			}
			
			
			//	----------------------------------------
			//	'freeform_module_admin_notification' hook.
			//	 - This allows developers to alter the 
			//	   $msg array before admin notification is sent.
			//	----------------------------------------
			
			if (ee()->extensions->active_hook('freeform_module_admin_notification') === TRUE)
			{
				$msg = ee()->extensions->universal_call('freeform_module_admin_notification', $fields, $this->entry_id, $msg);
				if (ee()->extensions->end_script === TRUE) return;
			}
			//	----------------------------------------
			
			//	----------------------------------------
			//	Send email
			//	----------------------------------------
			
			ee()->email->wordwrap	= $wordwrap;
			ee()->email->mailtype	= ( $this->check_yes($query->row('html')) ) ? 'html': 'text';
			
			if ( count( $this->attachments ) > 0 AND $this->check_yes($this->_param('send_attachment')) )
			{
				foreach ( $this->attachments as $file_name )
				{
					ee()->email->attach( $file_name['filepath'] );
				}
				
				ee()->db->query( 
					ee()->db->update_string( 
						'exp_freeform_attachments', 
						array( 'emailed' 	=> 'y' ), 
						array( 'entry_id' 	=> $this->entry_id ) 
					) 
				);
			}
			
			foreach ($recipients as $val)
			{								
				ee()->email->initialize();
				ee()->email->from($msg['from_email'], $msg['from_name']);	
				ee()->email->to($val); 
				ee()->email->subject($msg['subject']);	
				ee()->email->message(entities_to_ascii($msg['msg']));						
				ee()->email->send();
				
			}
			ee()->email->clear(TRUE);

			$msg = array();
		
			//	----------------------------------------
			//	Register the template used
			//	----------------------------------------
			
			ee()->db->query( 
				ee()->db->update_string( 
					'exp_freeform_entries', 
					array( 'template' 	=> $template), 
					array( 'entry_id' 	=> $this->entry_id ) 
				) 
			);
		}
		
        //	----------------------------------------
        //	Send user email email_change
        //	----------------------------------------
        
        if ($this->check_yes($this->_param('recipients')) AND 
			( ee()->session->userdata['group_id'] == 1 OR ee()->input->ip_address() != '0.0.0.0' ) AND 
			ee()->input->post('recipient_email') !== FALSE)
        {	
			$all_fields	= '';
			
			
			
			//don't we already do this...?
        	$template	= ( $this->_param('recipient_template') AND $this->_param('recipient_template') != '' ) ? 
							$this->_param('recipient_template') : 'default_template';
	
			//	----------------------------------------
			//	Array of recipients?
			//	----------------------------------------

			if ( is_array( ee()->input->post('recipient_email') ) === TRUE AND 
				count( ee()->input->post('recipient_email') ) > 0 )
			{
				$recipient_email	= ee()->input->post('recipient_email');
			}
			else
			{
				$recipient_email	= array( ee()->input->post('recipient_email') );
			}

			

			// if we are using 'static recipients'. e.g., recipient1='bob|bob@email.com'
			// parse out the uniqids and replace them with the real stored emails
			if ( $this->_param('static_recipients') == TRUE )
			{
				//prevents injection and only uses hashed emails from the form
				$temp_email			= $recipient_email;
				$recipient_email 	= array();	
				
				//parse email
				$stored_recipients = $this->_param('static_recipients_list');
								
				//have to check each email against the entire list.
				foreach ( $temp_email as $key => $value )
				{
					foreach ( $stored_recipients as $recipient_data )
					{
						if ( $value == $recipient_data['key'] )
						{
							$recipient_email[] = $recipient_data['email'];
						}
					}
				}
			}

			//	----------------------------------------
			//	Validate recipients?
			//	----------------------------------------

			$array			= $this->_validate_recipients( implode( ",", $recipient_email ) );

			$error			= $array['error'];

			$approved_tos	= $array['approved'];
			
			//	----------------------------------------
			//	Over our spam limit?
			//	----------------------------------------

			if ( $this->_param('static_recipients') != TRUE AND 
				 count( $approved_tos ) > $this->_param( 'recipient_limit' ) )
			{
				$error[]	= ee()->lang->line( 'recipient_limit_exceeded' );
			}

			//	----------------------------------------
			//	Errors?
			//	----------------------------------------

			if ( count( $error ) > 0 )
			{
				return ee()->output->show_user_error( 'general', $error );
			}

			//	----------------------------------------
			//	Check for spamming or hacking
			//	----------------------------------------

			$query	= ee()->db->query( 
				"SELECT 	SUM(exp_freeform_user_email.email_count) AS count 
				 FROM 		exp_freeform_entries, exp_freeform_user_email 
				 WHERE		exp_freeform_entries.entry_id   = exp_freeform_user_email.entry_id
				 AND 		exp_freeform_entries.ip_address = '" . ee()->db->escape_str( ee()->input->ip_address() )."' 
				 AND 		exp_freeform_entries.entry_date > '" . ee()->db->escape_str( 
					ee()->localize->now - ( 60 * ( (int) $this->prefs['spam_interval'] ) ) 
				) . "'" 
			);

			if ( $query->row('count') > $this->prefs['spam_count'] )
			{
				return ee()->email->output->show_user_error(
					'general', array(ee()->lang->line('em_limit_exceeded')));
			}

			//	----------------------------------------
			//	Log the number of emails sent
			//	----------------------------------------

			ee()->db->query( 
				ee()->db->insert_string( 
					"exp_freeform_user_email", 
					array( 
						'email_count' 	=> count( $approved_tos ) ,
						'entry_id' 		=> $this->entry_id 
					) 
				)
			);

			//	----------------------------------------
			//	Generate message
			//	----------------------------------------
			
			$msg		= array();
			
			$query		= ee()->db->query(
				"SELECT * 
				 FROM 	exp_freeform_templates 
				 WHERE 	template_name = '" . ee()->db->escape_str($template) . "' 
				 AND 	enable_template = 'y' 
				 LIMIT 	1"
			);

			if ( $query->num_rows() == 0 )
			{
				return ee()->output->show_user_error('general', array(ee()->lang->line('template_not_available')));
			}
			
			$msg['from_name']	= ( $query->row('data_from_name') != '' ) ?
			 							$query->row('data_from_name'): ee()->config->item('webmaster_name');

			$msg['from_email']	= ( $query->row('data_from_email') != '' ) ?
			 							$query->row('data_from_email'): ee()->config->item('webmaster_email');

			$msg['subject']		= $query->row('data_title');

			$msg['msg']			= $query->row('template_data');

			$wordwrap			= $this->check_yes($query->row('wordwrap'));
			
			$msg['subject']		= str_replace( 	LD.'entry_date'.RD, 
											   	ee()->localize->set_human_time(ee()->localize->now), 
												$msg['subject'] );
			
			$msg['msg']			= str_replace( 	LD.'entry_date'.RD, 
												ee()->localize->set_human_time(ee()->localize->now), 
												$msg['msg'] );
			
			$msg['subject']		= str_replace( 	LD.'freeform_entry_id'.RD, $this->entry_id, $msg['subject'] );
			$msg['msg']			= str_replace( 	LD.'freeform_entry_id'.RD, $this->entry_id, $msg['msg'] );
			
			if (preg_match_all("/".LD."(entry_date)\s+format=([\"'])(.*?)\\2".RD."/is", 
							   $msg['subject'].$msg['msg'], $matches)
			   )
			{
				for ($j = 0; $j < count($matches[0]); $j++)
				{	
					$val = $matches[3][$j];
					
					foreach (ee()->localize->fetch_date_params($matches[3][$j]) AS $dvar)
					{
						$val = str_replace($dvar, ee()->localize->convert_timestamp($dvar, ee()->localize->now, TRUE), $val);					
					}
					
					$msg['subject']		= str_replace( $matches[0][$j], $val, $msg['subject'] );
			
					$msg['msg']			= str_replace( $matches[0][$j], $val, $msg['msg'] );
				}
			}
			
			//	----------------------------------------
			//	Parse conditionals
			//	----------------------------------------
			
			//template isn't defined yet, so we have to fetch it
			//1.x
			if(APP_VER < 2.0)
			{
				if ( ! class_exists('Template'))
				{
					require PATH_CORE.'core.template'.EXT;
				}
			
				$local_TMPL	= new Template();
			}
			//2.x
			else
			{
				ee()->load->library('template');
				$local_TMPL =& ee()->template;
			}
			
			$data['attachment_count']		= count( $this->attachments );
						
			$cond		= $data;
			
			foreach( $msg as $key => $val )
			{
				$msg[$key]	= $local_TMPL->advanced_conditionals( 
					ee()->functions->prep_conditionals( $msg[$key], $cond ) 
				);
			}

			unset( $cond );

			//	----------------------------------------
			//	Parse individual fields
			//	----------------------------------------
			
			$exclude	= array('submit');
			
			foreach ( $msg as $key => $val )
			{
				//	----------------------------------------
				//	Handle attachments
				//	----------------------------------------
				
				$msg[$key]	= str_replace( LD."attachment_count".RD, $data['attachment_count'], $msg[$key] );
						
				if ( $key == 'msg' )
				{
					$all_fields	.= "Attachments: ".$data['attachment_count']."\n";
					
					$n		= 0;
					
					foreach ( $this->attachments as $file )
					{
						$n++;						
						$all_fields	.= "Attachment $n: ".$file['filename']." ".$this->upload['url'].$file['filename']."\n";
					}
				}
				
				if ( preg_match( "/".LD."attachments".RD."(.*?)".LD."\/attachments".RD."/s", $msg[$key], $match ) )
				{
					if ( count( $this->attachments ) > 0 )
					{
						$str	= '';
						
						foreach ( $this->attachments as $file )
						{
							$tagdata	= $match['1'];
							$tagdata	= str_replace( LD."fileurl".RD, $this->upload['url'].$file['filename'], $tagdata );
							$tagdata	= str_replace( LD."filename".RD, $file['filename'], $tagdata );
							$str		.= $tagdata;
						}
						
						$msg[$key]	= str_replace( $match['0'], $str, $msg[$key] );
					}
					else
					{
						$msg[$key]	= str_replace( $match['0'], "", $msg[$key] );
					}
				}
				
				//	----------------------------------------
				//	Loop
				//	----------------------------------------
				
				foreach ( $fields as $name => $label )
				{
					if ( isset( $data[$name] ) AND ! in_array( $name, $exclude ) )
					{
						$msg[$key]	= str_replace( LD.$name.RD, $data[$name], $msg[$key] );
						
						//	----------------------------------------
						//	We don't want to concatenate for every
						//	time through the main loop.
						//	----------------------------------------
						
						if ( $key == 'msg' )
						{
							$all_fields	.= $label.": ".$data[$name]."\n";
						}
					}
					else
					{
						$msg[$key]	= str_replace( LD.$name.RD, '', $msg[$key] );
					}
				}
			}
			
			
			//	----------------------------------------
			//	Parse all fields variable
			//	----------------------------------------
			
			if ( stristr( $msg['msg'], LD.'all_custom_fields'.RD ) )
			{
				$msg['msg']	= str_replace( LD.'all_custom_fields'.RD, $all_fields, $msg['msg'] );
			}
			
			
			//	----------------------------------------
			//	'freeform_recipient_email' hook.
			//	 - This allows developers to alter the 
			//	   $msg array before admin notification is sent.
			//	----------------------------------------
			
			if (ee()->extensions->active_hook('freeform_recipient_email') === TRUE)
			{
				$msg = ee()->extensions->universal_call('freeform_recipient_email', $fields, $this->entry_id, $msg);
				if (ee()->extensions->end_script === TRUE) return;
			}
			//	----------------------------------------
			
			//	----------------------------------------
			//	Send email
			//	----------------------------------------
			
			ee()->email->wordwrap	= $wordwrap;
			ee()->email->mailtype	= ( $this->check_yes($query->row('html')) ) ? 'html': 'text';
			
			if ( count( $this->attachments ) > 0 AND $this->check_yes($this->_param('send_attachment')) )
			{
				foreach ( $this->attachments as $file_name )
				{
					ee()->email->attach( $file_name['filepath'] );
				}
				
				ee()->db->query( 
					ee()->db->update_string( 
						'exp_freeform_attachments', 
						array( 'emailed' 	=> 'y' ), 
						array( 'entry_id' 	=> $this->entry_id ) 
					) 
				);
			}
			
			foreach ($approved_tos as $val)
			{								
				ee()->email->initialize();
				ee()->email->from($msg['from_email'], $msg['from_name']);	
				ee()->email->to($val); 
				ee()->email->subject($msg['subject']);	
				ee()->email->message(entities_to_ascii($msg['msg']));						
				ee()->email->send();
				
			}
			ee()->email->clear(TRUE);

			$msg = array();
		
			//	----------------------------------------
			//	Register the template used
			//	----------------------------------------
			
			ee()->db->query( 
				ee()->db->update_string( 
					'exp_freeform_entries', 
					array( 'template' 	=> $template), 
					array( 'entry_id' 	=> $this->entry_id ) 
				) 
			);
		}
		
		//	End send user recipients
				
		
        //	----------------------------------------
        //	Send user email
        //	----------------------------------------
        
        //$msg = array(); email_change
        
        if ( $this->check_yes($this->_param('send_user_email')) AND ee()->input->get_post('email') )
        {
        	$all_fields		= '';
        	
        	$recipients		= array();
        	
        	$recipients[]	= ee()->input->get_post('email');
        	
        	$template	= ( $this->_param('user_email_template') AND $this->_param('user_email_template') != '' ) ?
 								$this->_param('user_email_template'): 'default_template';
		
			//	----------------------------------------
			//	Generate message
			//	----------------------------------------
			
			$msg = array();
			
			$query		= ee()->db->query(
				"SELECT * 
				 FROM 	exp_freeform_templates 
				 WHERE 	template_name = '" . ee()->db->escape_str($template) . "' 
				 AND 	enable_template = 'y' 
				 LIMIT 	1"
			);

			if ( $query->num_rows() == 0 )
			{
				return ee()->output->show_user_error('general', array(ee()->lang->line('template_not_available')));
			}
			
			$msg['from_name']	= ( $query->row('data_from_name') != '' ) ?
			 							$query->row('data_from_name') : ee()->config->item('webmaster_name');

			$msg['from_email']	= ( $query->row('data_from_email') != '' ) ?
			 							$query->row('data_from_email') : ee()->config->item('webmaster_email');

			$msg['subject']		= $query->row('data_title');

			$msg['msg']			= $query->row('template_data');

			$wordwrap			= ( $this->check_yes($query->row('wordwrap')) ) ? TRUE: FALSE;
			
			$msg['subject']		= str_replace( 	LD.'entry_date'.RD, 	
											   	ee()->localize->set_human_time(ee()->localize->now), 
												$msg['subject'] );
			
			$msg['msg']			= str_replace( 	LD.'entry_date'.RD, 
												ee()->localize->set_human_time(ee()->localize->now), 
												$msg['msg'] );
			
			$msg['subject']		= str_replace( LD.'freeform_entry_id'.RD, $this->entry_id, $msg['subject'] );
			$msg['msg']			= str_replace( LD.'freeform_entry_id'.RD, $this->entry_id, $msg['msg'] );
		
			/* email_change*/
			if (preg_match_all("/".LD."(entry_date)\s+format=([\"'])(.*?)\\2".RD."/is", $msg['subject'].$msg['msg'], $matches))
			{
				for ($j = 0; $j < count($matches[0]); $j++)
				{	
					$val = $matches[3][$j];
					
					foreach (ee()->localize->fetch_date_params($matches[3][$j]) AS $dvar)
					{
						$val = str_replace(	$dvar, 
											ee()->localize->convert_timestamp($dvar, ee()->localize->now, TRUE), 
											$val);					
					}
					
					$msg['subject']		= str_replace( $matches[0][$j], $val, $msg['subject'] );
			
					$msg['msg']			= str_replace( $matches[0][$j], $val, $msg['msg'] );
				}
			}
			
			//	----------------------------------------
			//	Parse conditionals
			//	----------------------------------------
		
			//template isn't defined yet, so we have to fetch it
			//1.x
			if(APP_VER < 2.0)
			{
				if ( ! class_exists('Template'))
				{
					require PATH_CORE.'core.template'.EXT;
				}
			
				$local_TMPL	= new Template();
			}
			//2.x
			else
			{
				ee()->load->library('template');
				$local_TMPL =& ee()->template;
			}
			
			$data['attachment_count']		= count( $this->attachments );
			
			$cond							= $data;
			
			foreach( $msg as $key => $val )
			{
				$msg[$key]	= $local_TMPL->advanced_conditionals( 
					ee()->functions->prep_conditionals( $msg[$key], $cond ) 
				);
			}

			unset( $cond );

			//	----------------------------------------
			//	Parse individual fields
			//	----------------------------------------
			
			$exclude	= array('submit');
			
			foreach ( $msg as $key => $val )
			{
				//	----------------------------------------
				//	Handle attachments
				//	----------------------------------------
				
				$msg[$key]	= str_replace( LD."attachment_count".RD, $data['attachment_count'], $msg[$key] );
						
				if ( $key == 'msg' )
				{
					$all_fields	.= "Attachments: ".$data['attachment_count']."\n";
					
					$n		= 0;
					
					foreach ( $this->attachments as $file )
					{
						$n++;						
						$all_fields	.= "Attachment $n: ".$file['filename']." ".$this->upload['url'].$file['filename']."\n";
					}
				}
				
				if ( preg_match( "/".LD."attachments".RD."(.*?)".LD."\/attachments".RD."/s", $msg[$key], $match ) )
				{
					if ( count( $this->attachments ) > 0 )
					{
						$str	= '';
						
						foreach ( $this->attachments as $file )
						{
							$tagdata	= $match['1'];
							$tagdata	= str_replace( LD."fileurl".RD, $this->upload['url'].$file['filename'], $tagdata );
							$tagdata	= str_replace( LD."filename".RD, $file['filename'], $tagdata );
							$str		.= $tagdata;
						}
						
						$msg[$key]	= str_replace( $match['0'], $str, $msg[$key] );
					}
					else
					{
						$msg[$key]	= str_replace( $match['0'], "", $msg[$key] );
					}
				}
				
				//	----------------------------------------
				//	Loop
				//	----------------------------------------
				
				foreach ( $fields as $name => $label )
				{
					if ( isset( $data[$name] ) AND ! in_array( $name, $exclude ) )
					{
						$msg[$key]	= str_replace( LD.$name.RD, $data[$name], $msg[$key] );
						
						//	----------------------------------------
						//	We don't want to concatenate for every
						//	time through the main loop.
						//	----------------------------------------
						
						if ( $key == 'msg' )
						{
							$all_fields	.= $label.": ".$data[$name]."\n";
						}
					}
					else
					{
						$msg[$key]	= str_replace( LD.$name.RD, '', $msg[$key] );
					}
				}
			}
			
			
			//	----------------------------------------
			//	Parse all fields variable
			//	----------------------------------------
			
			if ( stristr( $msg['msg'], LD.'all_custom_fields'.RD ) )
			{
				$msg['msg']	= str_replace( LD.'all_custom_fields'.RD, $all_fields, $msg['msg'] );
			}
			
			//	----------------------------------------
			//	'freeform_module_user_notification' hook.
			//	 - This allows developers to alter the $msg array before user notification is sent.
			//	----------------------------------------
			
			if (ee()->extensions->active_hook('freeform_module_user_notification') === TRUE)
			{
				$msg = ee()->extensions->universal_call('freeform_module_user_notification', $fields, $this->entry_id, $msg);
				if (ee()->extensions->end_script === TRUE) return;
			}
			//	----------------------------------------
		
			//	----------------------------------------
			//	Send email
			//	----------------------------------------
			
			//ee()->load->library('email');
			ee()->email->wordwrap	= $wordwrap;
			ee()->email->mailtype	= ( $this->check_yes($query->row('html')) ) ? 'html': 'text';
			
			if ( count( $this->attachments ) > 0 AND $this->check_yes($this->_param('send_user_attachment')) )
			{
				foreach ( $this->attachments as $file_name )
				{
					ee()->email->attach( $file_name['filepath'] );
				}
				
				ee()->db->query( 
					ee()->db->update_string( 
						'exp_freeform_attachments', 
						array( 'emailed' => 'y' ), 
						array( 'entry_id' => $this->entry_id ) 
					) 
				);
			}
			
			foreach ($recipients as $val)
			{								
				ee()->email->initialize();
				ee()->email->from($msg['from_email'], $msg['from_name']);	
				ee()->email->to($val); 
				ee()->email->subject($msg['subject']);	
				ee()->email->message(entities_to_ascii($msg['msg']));		
				ee()->email->send();
			}
			
			$msg = array();
			ee()->email->clear(TRUE);
		}
		
		//	End send user email 
		
		
		//	----------------------------------------
		//	Subscribe to mailing lists
		//	----------------------------------------
		
		if ( ee()->input->get_post('mailinglist') )
		{			
			if ( ee()->db->table_exists('exp_mailing_lists') )
			{
				//	----------------------------------------
				//	Do we have an email?
				//	----------------------------------------
				
				if ( $email = ee()->input->get_post('email') )
				{
					//	----------------------------------------
					//	Explode mailinglist parameter
					//	----------------------------------------
					
					if ( is_array( ee()->input->post('mailinglist') ) )
					{
						$lists	= implode( "','", ee()->db->escape_str(ee()->input->post('mailinglist')));
					}
					else
					{
						$lists	= ee()->db->escape_str(ee()->input->post('mailinglist'));
					}
					
					//	----------------------------------------
					//	Get lists
					//	----------------------------------------
					
					$subscribed	= '';
					
					$sub	= ee()->db->query( 
						"SELECT list_id 
						 FROM exp_mailing_list 
						 WHERE email = '" . ee()->db->escape_str($email) . "' 
						 GROUP BY list_id"
					);

					if ( $sub->num_rows() > 0 )
					{
						foreach( $sub->result_array() as $row )
						{
							$subscribed[] = $row['list_id'];
						}
						
						$subscribed	= " AND list_id NOT IN (".implode(',', $subscribed).") ";
					}
					
					$query	= ee()->db->query( 
						"SELECT DISTINCT 	list_id, list_title 
						 FROM 				exp_mailing_lists 
						 WHERE 				( list_id IN ('" . $lists . "') OR 
						 					  list_name IN ('" . $lists . "') ) " . $subscribed
					);
					
					if ( $query->num_rows() > 0 AND $query->num_rows() < 50 )
					{				
						// Kill duplicate emails from authorization queue.  This prevents an error if a user
						// signs up but never activates their email, then signs up again.
						
						ee()->db->query(
							"DELETE FROM 	exp_mailing_list_queue 
							 WHERE 			email = '" . ee()->db->escape_str($email) . "'"
						);
					
						foreach ( $query->result_array() as $row )
						{
							//	----------------------------------------
							//	Insert email
							//	----------------------------------------
									
							$code	= ee()->functions->random('alpha', 10);
							
							if (  $this->check_no(ee()->input->get_post('mailinglist_opt_in')) )
							{
								ee()->db->query(
									ee()->db->insert_string(	
										'exp_mailing_list',
										array(	
											'user_id'		=> '',
											'list_id'		=> $row['list_id'],
											'authcode'		=> $code,
											'email'			=> $email,
											'ip_address'	=> ee()->input->ip_address()
										)
									)
								);
														
								// ----------------------------------------
								//  Is there an admin notification to send?
								// ----------------------------------------
						
								if ($this->check_yes(ee()->config->item('mailinglist_notify'))  AND
								    ee()->config->item('mailinglist_notify_emails') != '')
								{
									$query = ee()->db->query(
										"SELECT list_title 
										 FROM 	exp_mailing_lists 
										 WHERE 	list_id = '" . ee()->db->escape_str($row['list_id']) . "'"
									);
								
									$swap = array(
										'email'			=> $email,
										'mailing_list'	=> $query->row('list_title')
									 );
									
									$template = ee()->functions->fetch_email_template('admin_notify_mailinglist');
									$email_tit = ee()->functions->var_swap($template['title'], $swap);
									$email_msg = ee()->functions->var_swap($template['data'], $swap);
																		
									// ----------------------------
									//  Send email
									// ----------------------------
						
									$notify_address = $this->remove_extra_commas(
										ee()->config->item('mailinglist_notify_emails')
									);
									
									if ($notify_address != '')
									{				
										// ----------------------------
										//  Send email
										// ----------------------------
										
										//ee()->load->library('email');
										
										foreach (explode(',', $notify_address) as $addy)
										{
											ee()->email->initialize();
											ee()->email->wordwrap = true;
											ee()->email->from(
												ee()->config->item('webmaster_email'), 
												ee()->config->item('webmaster_name')
											);	
											ee()->email->to($addy); 
											ee()->email->reply_to(ee()->config->item('webmaster_email'));
											ee()->email->subject($email_tit);	
											ee()->email->message(entities_to_ascii($email_msg));		
											ee()->email->Send();
										}
										ee()->email->clear(TRUE);
									}
								}
							}        
							else
							{        	
								ee()->db->query(
									"INSERT INTO exp_mailing_list_queue (email, list_id, authcode, date) 
									 VALUES ('" . ee()->db->escape_str($email) . "', '" . 
									 			  ee()->db->escape_str($row['list_id']) ."', '" . 
												  ee()->db->escape_str($code) . "', '" . time() . "')"
									);
								
								$this->send_email_confirmation($email, $row, $code);
							}
						}
					}
				}
			}
		}
		
		//	End subscribe to mailinglists 
		
		//	----------------------------------------
		//	'freeform_module_insert_end' hook.
		//	 - This allows developers to do one last thing before Freeform submit is ended.
		//	----------------------------------------
		
		if (ee()->extensions->active_hook('freeform_module_insert_end') === TRUE)
		{
			$edata = ee()->extensions->universal_call('freeform_module_insert_end', $fields, $this->entry_id, $msg);
			if (ee()->extensions->end_script === TRUE) return;
		}
        //	----------------------------------------
		
		//	----------------------------------------
		//	Set return
		//	----------------------------------------
        
        if ( ! $return = ee()->input->get_post('return') )
        {
        	$return	= ee()->input->get_post('RET');
        }
		
		if ( preg_match( "/".LD."\s*path=(.*?)".RD."/", $return, $match ) > 0 )
		{
			$return	= ee()->functions->create_url( $match['1'] );
		}
		elseif ( stristr( $return, "http://" ) === FALSE && stristr( $return, "https://" ) === FALSE )
		{
			$return	= ee()->functions->create_url( $return );
		}
		
		$return	= str_replace( "%%entry_id%%", $this->entry_id, $return );
		
		$return	= $this->_chars_decode( $return );
				
        //	----------------------------------------
        //	Return the user
        //	----------------------------------------

        if ( $return != '' )
        {
			ee()->functions->redirect( $return );
        }
        else
        {
        	ee()->functions->redirect( ee()->functions->fetch_site_index() );
        }
		
		exit;
    }