<?php
/*
 * Edit the index.html and set the share-path to whereever you placed
 * this script.
 * 
 * ChangeLog: November 3, 2008 - Initial release.
 */

/* 
 * Settings for the script, change theise to fit your needs
 */
$subject = "[FROM_NAME] thought you should see this";

$body = "Check out Bozzuto's digital brochure here:

    [LINK]

    [MESSAGE]

[FROM_NAME]";

/* 
 * The url that will be sent out in the script, set this to the link you 
 * want the user to see.
 *
 * Example: http://www.example.com/path/to/publication/
 */
$publication_url = "http://www.bozzutoftp.com/bozzutoebrochure/";

/* Name used in emails from field */
$from_name = "The Bozzuto Group";

/* From email */
$from_email = "webmaster@bozzuto.com";

/* 
 * Set to true if you want to allow a custom from email, otherwise the 
 * variables set above will be used as from.
 */
$allow_custom_from = true;

/* END SETTINGS */

$status = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	$data = parse_input();

	if ($allow_custom_from) {
		$from = sprintf("%s <%s>", $data['name'], $data['youremail']);
	} else {
		$from = sprintf("%s <%s>", $from_name, $from_email);
	}

	$url = sprintf("%s#%d", $publication_url, $data['pagenumber']);

	$subject = str_replace("[FROM_NAME]", $data['name'], $subject);
	$body = str_replace(
		array("[FROM_NAME]", "[LINK]", "[MESSAGE]"), 
		array($data['name'], $url, $data['message']), 
		$body
	);

	$status = send_emails($data['emails'], $subject, $body, $from);
}

$rt_status = $status ? "true" : "false";
printf('<result value="%s" />', $rt_status);

function parse_input() { 
	$input = file_get_contents('php://input');
	
	$parser = xml_parser_create('UTF-8');
	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
	xml_parse_into_struct($parser, $input, $values);
	xml_parser_free($parser);
	
	$data = array(
		'emails' => array(),
		'name' => '',
		'youremail' => '',
		'message' => '',
		'pagenumber' => '1'
	);
	
	if ($values) {
		foreach ($values as $value) {
			if ($value['type'] == 'complete') {
				switch ($value['tag']) {
				case 'message':
				case 'name':
				case 'youremail':
				case 'pagenumber':
					$data[$value['tag']] = utf8_decode($value['value']);
					break;
				case 'email':
					$data['emails'][] = $value['value'];
					break;
				}
			}
		}
	}
	
	return $data;
}

function validate_email($email) {
	return strpos($email, "@") !== false && strpos($email, ".") !== false;
}

function send_emails($emails, $subject, $body, $from) {
	$rt_status = true;
	
	if ($emails) {
		foreach ($emails as $email) { 
			if (validate_email($email)) {
				$rt_status = mail($email, $subject, $body, "From: " . $from) && $rt_status;
			}
		}
	}
	
	return $rt_status;
}
?>
