<?php if(!defined('master_script')) die();

/**
 * Default settings
 *
 * @category   Module (form)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2009-04-05
 */
	
	global $user_data, $system_data, $page_info, $modules, $id, $form, $message, $action, $message_sent;
	
	if(!isset($module_settings['form']['template'])) $module_settings['form']['template'] = '';
	if(!isset($module_settings['form']['send to'])) $module_settings['form']['send to'] = 'email';
	if(!isset($module_settings['form']['email address'])) $module_settings['form']['email address'] = $user_data['email'];
	if(!isset($module_settings['form']['url address'])) $module_settings['form']['url address'] = '';
	if(!isset($module_settings['form']['message sent'])) $module_settings['form']['message sent'] = txt('form', 'Danke, wir haben Ihre Nachricht erhalten.');
	
	$module_settings['form']['message sent'] = stripslashes($module_settings['form']['message sent']);
	
/**
 * Languages
 *
 * @category   Module (form)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2010-07-28
 */

	$modules['form']['key'] = 'form';
	include_txt($modules['form']['key'], $system_data['folder']['modules'] . $modules['form']['key'] . '/languages/');
	include_txt($modules['form']['key'], $system_data['folder']['settings'] . 'modules/' . $modules['form']['key'] . '/languages/');

/**
 * Default values
 *
 * @category   Module (form)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2009-09-10
 */

	// Module ID
	$id = rand(1,100);
	
	// Default values
	$form = '';
	$message = '';
	$message_sent = '';

/**
 * Handle submit type
 *
 * @category   Module (form)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2009-09-10
 */
	
	switch($module_settings['form']['send to']) {
		case 'email' : $action = $page_info->href; break;
		case 'url' : $action = $module_settings['form']['url address'] != '' ? $module_settings['form']['url address'] : $page_info->href; break;
		default : $action = $user_data['url rewrite'] == false ? 'index.php?page=' : '' . $module_settings['form']['send to'];
	}

/**
 * Load form template and parse template tags
 *
 * @category   Module (form)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2009-12-01
 */
	
	if(file_exists($module_settings['form']['template'])) {
		$form_template_content = file_get_contents($module_settings['form']['template']);
		
		// Parse label values
		$form = preg_replace_callback(
			'/\{(.+)\}/u',
			create_function(
		      	'$code',
      			'	$code_0 = trim($code[0], "{}");
      				return txt("form", $code_0);
      			'
    		),
    		$form_template_content
    	);
		
		// Parse input field values
		$form = preg_replace_callback(
			'/\$(.+)\$/u',
			create_function(
		      	'$code',
      			'	$code_0 = trim($code[0], "$");
      				return isset($_POST[$code_0]) ? clean_output($_POST[$code_0]) : "";
      			'
    		),
    		$form
    	);
		
		// Parse checkbox and radio input fields
		$form = preg_replace_callback(
			"/<input(.*?)name=\"(.+?)\"(.*?)>/u",
			create_function(
		      	'$parts', '
		      		preg_match("/name=\"(.+?)\"/", $parts[0], $ids);
		      		$id = isset($ids[1]) ? $ids[1] : "";

		      		preg_match("/value=\"(.+?)\"/", $parts[0], $values);
		      		$value = isset($values[1]) ? $values[1] : "";
		      		
		      		return isset($_POST[$id]) && ($_POST[$id] == "on" || $_POST[$id] == $value) ? "<input" . $parts[1] . "name=\"$parts[2]\" checked=\"checked\"" . $parts[3] . ">" : $parts[0];
		      	'
    		),
    		$form
    	);

		// Parse select fields
		$form = preg_replace_callback(
			"/<select(.*?)name=\"(.+?)\"(.*?)>(.*?)<\/select>/us",
			create_function(
		      	'$parts', '
		      		if(isset($_POST[$parts[2]]) && $_POST[$parts[2]] != "") {
		      			$options = explode("<", $parts[4]);
		      			$new_options = "";
		      			
		      			foreach($options as $option) if(trim($option) != "") {
		      				preg_match("/value=\"(.+?)\"/", $option, $values);
    	      				$new_options .= "<" . (isset($values[1]) && $values[1] == $_POST[$parts[2]] ? str_replace($values[1] . "\"", $values[1] . "\" selected=\"selected\"", $option) : $option);
		      			}
		      			
		      			return str_replace($parts[4], $new_options, $parts[0]);
		      		} else
			      		return $parts[0];
		      	'
    		),
    		$form
    	);
	}

/**
 * On submitted form
 *
 * @category   Module (form)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   2010-05-19
 */

	if(isset($_POST['required']) && time() - intval($_POST['required']) > 5) {
		// Get field names
    	$submit_fields = explode(',', $_POST['submit-fields']);
    	$required_fields = explode(',', $_POST['required-fields']);
    	
    	// Default value
    	$passed = true;
    	
    	// Walk trough posted vars
    	foreach($submit_fields as $field) {
    		$field = trim($field);
    		$_POST[$field] = isset($_POST[$field]) ? clean_string($_POST[$field], true) : '';
    		
    		// Parse checkboxes
    		if($_POST[$field] == 'on') $_POST[$field] = txt('form', 'on');
    		
    		// Check required fields
    		if(in_array($field, $required_fields)) {
    			if($field == 'email' && !is_email($_POST[$field])) $message = txt('form', 'Bitte geben Sie eine gültige E-Mail-Adresse an.');
    			if($_POST[$field] == '') $message = txt('form', 'Bitte füllen Sie alle markierten Felder aus.');
    		}
    	}
    	
    	// Send email
    	if($module_settings['form']['send to'] == 'email' && $message == '') {
    		if($module_settings['form']['email address'] == '')
    			$module_settings['form']['email address'] = $user_data['email'];

    		$fromEmail = isset($_POST['email']) ? $_POST['email'] : $module_settings['form']['email address'];
    		$fromName = isset($_POST['name']) ? $_POST['name'] : $fromEmail;
    		
    		$mail_header[] = 'From: Pagemap Mailer <' . $user_data['email'] . '>';
    		$mail_header[] = 'Reply-To: ' . $fromEmail;
    		$mail_header[] = 'Return-Path: ' . $user_data['email'];
    		$mail_header[] = 'X-Mailer: PHP/' . phpversion();
    		$mail_header[] = 'X-Sender-IP: ' . $_SERVER['REMOTE_ADDR'];
    		$mail_header[] = 'Content-type: text/plain; charset="UTF-8"';

    		$timestamp = time(); $date = date("d.m.Y", $timestamp); $time = date("H:i", $timestamp);
    		$content[] = txt('form', 'Über Ihre Website wurde eine Nachricht gesendet.') . "\n";
    		$content[] = txt('form', 'Gesendet am') . ' ' . $date . ' (' . $time . '):' . "\n";
    		
    		foreach($submit_fields as $field) if($_POST[$field] != '') {
    			if(isset($modules['form'][$field])) {
    				$content[] = txt('form', $modules['form'][$field]) . ': ' . html_entity_decode($_POST[$field]);
    			} else {
    				// Search in form template for the label of field by Name
    				$field_label = preg_match("/<label.+for=\"$field\".*>(.+)<\/label>/u", $form, $matches);
    				$field_label_value = isset($matches[1]) ? $matches[1] : $field;
    				$content[] = txt('form', $field_label_value) . ': ' . html_entity_decode($_POST[$field]);
    			}
    		}
    		
    		connector('form send mail');
    		
    		if($module_settings['form']['email address'] != '')
    			mail($module_settings['form']['email address'], txt('form', 'Kontakt über Ihre Website'), implode("\r\n", $content), implode("\r\n", $mail_header), "-f " . $user_data['email']);
    		
    		$message_sent = $module_settings['form']['message sent'];
    	}
	} else if(isset($_POST['required']))
		$message = txt('form', 'Bitte warten Sie mindestens 5 Sekunden, bevor Sie das Formular abschicken.');
	
/**
 * Include module frontend template
 *
 * @category   Module (form)
 * @author     Nico Wenig <nico.wenig@yellowgreen.de>
 * @version	   1.0
 */

	include_template('form');

?>