<?php
// +---------------------------------------------------------------------------------------+
// | TenderSystem                                                                          |
// +---------------------------------------------------------------------------------------+
// | The contents of this file are subject to the TenderSystem Public License Version 1.1  |
// | ("License"); you may not use this file except in compliance with the License. You may |
// | obtain a copy of the License at http://www.tendersystem.com/tpl/                      |
// |                                                                                       |
// | Software distributed under the License is distributed on an "AS IS" basis, WITHOUT    |
// | WARRANTY OF ANY KIND, either express or implied. See the License for the specific     |
// | language governing rights and limitations under the License.                          |
// |                                                                                       |
// | All copies of the Covered Code must include the "Powered by TenderSystem" logo and    |
// | ValueCard copyright notice on every user interface screen and in every outgoing       |
// | email in the same form as they appear in the distribution.                            |
// |                                                                                       |
// | The Original Code is: TenderSystem                                                    |
// | The Initial Developer of the Original Code is ValueCard (Pty) Limited.                |
// | Portions created by ValueCard are Copyright (C) 2002 ValueCard (Pty) Limited.         |
// | All Rights Reserved.                                                                  |
// | Contributor(s): __________________.                                                   |
// +---------------------------------------------------------------------------------------+

/**
* MIME class
* @package TenderSystem
* @subpackage generic
* @copyright Copyright &copy; 2002, ValueCard (Pty) Ltd
* @license http://www.tendersystem.com/tpl/ TenderSystem Public License
* @version 
*/

// Security - ensure that file never called directly
// not required if global variables are off or API is hosted on a non-public server
if (eregi(basename(__FILE__),$_SERVER['PHP_SELF'])) {
    die ("You can't access this file directly...");
}

class mime {
	// set paramaters
	var $recipients = Array();
	var $attachments = Array();
	var $headers = Array();
	var $mime_parts = Array();

	function decode($msg_text) {
		$this->encoded_text = str_replace("\r", "", $msg_text);
		$this->parse_msg_headers();
		// if no boundary presume text
		if (!$this->mime_boundary) {
			// assume plain text and adapt later
			$this->mime_parts[0] = Array(
				"headers"	=> 	Array(
									"content-type" 				=> "text/plain",
									"content-transfer-encoding"	=> "7bit"
								),
				"body"		=> substr($this->encoded_text,strpos($this->encoded_text,"\n\n") + 2)
			);
		} else {
			$this->decode_body(substr($this->encoded_text,strpos($this->encoded_text,"--".$this->mime_boundary)),$this->mime_boundary);
		}
		$this->encoded_text = "";
	}
	
	function parse_msg_headers() {
		// parse email headers
		$headers = "\n".substr($this->encoded_text,0,strpos($this->encoded_text, "\n\n"))."\n";
		$match_ptrn = Array(
			"To"			=> "to", 
			"cc"			=> "cc", 
			"From"			=> "from", 
			"Date"			=> "date",
			"Subject"		=> "subject", 
			"Return-path"	=> "return_path",
			"Reply-to"		=> "reply_to", 
			"MIME-Version"	=> "mime_version"
		);
		// if present set
		foreach($match_ptrn AS $match => $varname) {
			preg_match("/\n$match: ([^\n]*)\n/i",$headers,$matches);
			$this->$varname = $matches[1];
		}
		// get the mime boundary
		if(preg_match("/\n?\t?boundary=\"?(.*?)\"?\s*\n/i", $headers, $matches)){
			$this->mime_boundary = $matches[1];
			$pos = @strpos($this->mime_boundary,"\"");
			if(FALSE <> $pos) {
				$length = strlen($this->mime_boundary);
				$pos = $pos - $length;
				$this->mime_boundary = @substr($this->mime_boundary,0,$pos);
			}
		}
	}
	
	function decode_body($body, $boundary) {
		// recursively parse email body
		$body_pieces = explode("--".$boundary, $body);
		for ($i = 1; $i < sizeof($body_pieces) - 1; $i++) {
			$headers = $this->get_part_headers($body_pieces[$i]);
			$part_body = substr($body_pieces[$i],strpos($body_pieces[$i], "\n\n") + 2);
			if ($headers["content-type"] == "multipart/alternative") {
				$this->decode_body(substr($part_body,strpos($part_body, "--".$headers["boundary"])),$headers["boundary"]);
			} else {
				$this->mime_parts[] = Array(
					"headers" 	=> $headers,
					"body"		=> $part_body
				);
			}
		}
	}
	
	function get_part_headers($text) {
		// get the message part headers and return in array
		$headers = substr($text, 0, strpos($text, "\n\n"));
		$head_pieces = split("\n", $headers);
		foreach($head_pieces AS $header_line) {
			preg_match_all("/(\s|\t){0,}([a-z0-9-]*)(=|:)\s?\"?([^(;|\"|$|\n)]*)(;|$|\"|\n)/i",$header_line,$matches);
			for($i = 0; $i < sizeof($matches[2]); $i++) {
				if ($matches[2][$i] && $matches[4][$i]) {
					$ret_headers[strtolower($matches[2][$i])] = $matches[4][$i];
				}
			}
		}
		return $ret_headers;
	}
	
	function get_msg_array() {
		// place message in an array
		$mime_parts_tmp = $this->mime_parts;
		$headers_inc = Array("to","cc","from","date","subject","return_path","reply_to");
		// Put headers in array first
		foreach($headers_inc AS $var) {
			$ret_msg_array[$var] = $this->$var;
		}
		// process mime type
		foreach($mime_parts_tmp AS $key => $part_array) {
			if ($part_array["headers"]["content-type"] == "text/plain" && $ret_msg_array["text"] == "") {
				$ret_msg_array["text"] = $this->decode_part($part_array["body"], $part_array["headers"]["content-transfer-encoding"]);
				unset($mime_parts_tmp[$key]);
			}
		}
		foreach($mime_parts_tmp AS $key => $part_array) {
			if ($part_array["headers"]["content-type"] == "text/html" && $ret_msg_array["html"] == "") {
				$ret_msg_array["html"] = $this->decode_part($part_array["body"],
				$part_array["headers"]["content-transfer-encoding"]);
				unset($mime_parts_tmp[$key]);
			}
		}
		$attachmentid = 0;
		foreach($mime_parts_tmp AS $key => $part_array) {
			$ret_msg_array["attachment".++$attachmentid] = $part_array;
			$ret_msg_array["attachment".$attachmentid]["body"] = $this->decode_part($ret_msg_array["attachment".$attachmentid]["body"],$ret_msg_array["attachment".$attachmentid]["headers"]["content-transfer-encoding"]);
		}
		$ret_msg_array["attachments"] = $attachmentid;
		return $ret_msg_array;
	}
	
	function decode_part($contents,$encoding) {
		// decode
		$encoding = strtolower($encoding);
		switch($encoding) {
			case "base64":
				return base64_decode(trim($contents));
				break;
			case "quoted-printable":
				return quoted_printable_decode($contents);
				break;
			default:
				return $contents;
				break;
		}
	}
}
?>