<?php

function quotedprintable_encode($input, $line_max = 76)
{ 
    $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'); 
    $lines = preg_split("/(?:\r\n|\r|\n)/", $input); 
    $eol = "\r\n"; 
    $escape = "="; 
    $output = ""; 

    while( list(, $line) = each($lines) )
	{ 
        //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary 
        $linlen = strlen($line); 
        $newline = ""; 
        for($i = 0; $i < $linlen; $i++)
		{ 
            $c = substr($line, $i, 1); 
            $dec = ord($c); 
            if ( ($dec == 32) && ($i == ($linlen - 1)) )
			{ // convert space at eol only 
                $c = "=20"; 
            }
			elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) )
			{ // always encode "\t", which is *not* required 
                $h2 = floor($dec/16); $h1 = floor($dec%16); 
                $c = $escape.$hex["$h2"].$hex["$h1"]; 
            }
            if ( (strlen($newline) + strlen($c)) >= $line_max )
			{ // CRLF is not counted 
                $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay 
                $newline = ""; 
            } 
            $newline .= $c; 
        } // end of for 
        $output .= $newline.$eol; 
    }

    return trim($output);
} 

//////////////////////////////////////////
//
//////////////////////////////////////////
function my_split($pattern, $text)
{
}

//////////////////////////////////////////
//
//////////////////////////////////////////
function mk_header_array($headers_text, &$err)
{
    $headers = array();
    $lines = split("\n", $headers_text);
	foreach($lines as $line)
	{
	    if ( strlen($line) > 0 )
		{
		    if ( ctype_space($line[0]) )
			{
			    if ( isset($parts) && is_array($parts) && ( 3 == count($parts) ) )
				{
				    $headers[strtolower(trim($parts[1]))] .= $line;
				}
				else
				{
				    $err = "header continuation line in invalid position - \"". trim($line) . "\"";
					unset($headers);
					break;
				}
			}
			else
			{
	    	    if ( preg_match("/(.+)\s*:\s*(.+)/", $line, $parts) )
				{
			        if ( isset($parts) && is_array($parts) && ( 3 == count($parts) ) )
				    {
			            $headers[strtolower(trim($parts[1]))] = trim($parts[2]);
				    }
				    else
				    {
				        $err = "unable to parse header line - \"". trim($line) . "\"";
						echo "\$parts is " . gettype($parts) . " : size " . count($parts) . "\n";
						echo $parts[0] . " / " . $parts[1] . " / " . $parts[2] . "\n";
					    unset($headers);
					    break;
				    }
				}
				else
				{
				        $err = "unable to parse header line - \"". trim($line) . "\"";
						echo "no preg_match\n";
					    unset($headers);
					    break;
				}
			}
		}
	}
	
	return $headers;
}

//////////////////////////////////////////
//
//////////////////////////////////////////
function header_line_length_limit($header, $max_length = 74, $seperators = ", ")
{
    $new_header="";
	$current_col = 0;
	$line_start = 0;
    for ($i = 0; $i < strlen($header); $i++)
	{
	    if ( strstr($seperators, substr($header, $i, 1)) )
		{
		   // potential seperator here
		   $last_break = $i;
		}
		if ( $current_col >= $max_length )
		{
		    // if we have a break, put everything from the start of the current line up
			// to the last break into a line in the new header
			if (isset($last_break))
			{
			    if ( strlen($new_header) > 0 ) $new_header .= "\n ";  // space is important here
				$new_header .= substr($header, $line_start, ($last_break-$line_start)+1);
				$line_start = $last_break+1;
				$current_col = 0;
				unset($last_break);
			}
		}
		$current_col++;
	}
	// add reminder of header
    if ( strlen($new_header) > 0 ) $new_header .= "\n ";  // space is important here
	$new_header .= substr($header, $line_start, strlen($header)-$line_start);
	
	return $new_header;
}

//////////////////////////////////////////
//
//////////////////////////////////////////
function mk_header_text($headers_array)
{
    $headers = "";
	foreach($headers_array as $key => $val)
	{
	    $headers .= header_line_length_limit($key . ": " . $val) . "\n";
	}
	
	return $headers;
}

class mimeobject
{
    var $type;
	var $encoding;
	var $description;
	var $id;
	var $contents;
	
	function __construct($type = "text/plain", $encoding = "7bit")
	{
	    $this->type = $type;
	    $this->encoding = $encoding;
		$id = "OID-" . uniqid(rand(), 1);
    }
	
	function getMOType()
	{
	    return $this->type;
	}

	function getMOEncoding()
	{
	    return $this->encoding;
	}
	
	function setDescription($text)
	{
	    $this->description = $text;
	}
	
	function getDescription()
	{
	    return $this->description;
	}
	
	function render()
	{
	    $rendered = $this->renderHeaders() . "\n" . $this->renderBody();
		
		return $rendered;
	}

    function renderHeaders()
	{
	    $headers =  "Content-Type: " . $this->type . "\n";
	    $headers .=  "Content-Transfer-Encoding: " . $this->encoding . "\n";
		if ( isset($this->description) )
		{
	        $headers .=  "Content-Description: \"" . $this->description . "\"\n";
		}
        return $headers;
	}
	
	function renderBody()
	{
		switch ($this->encoding)
		{
		case "7bit":
		case "8bit":
		    $encoded = wordwrap($this->contents);
			break;
		case "binary":
		    $encoded = $this->contents;
			break;
		case "base64":
		    $encoded = chunk_split(base64_encode($this->contents));
			break;
		case "quoted-printable":
		    $encoded = quotedprintable_encode($this->contents);
			break;
		}
		
		return $encoded;
	}
}

class mimeTextObject extends mimeObject
{
	var $charset;

    function __construct($type = "text/plain", $charset = "us_ascii", $encoding = "7bit")
	{
	    parent::__construct($type, $encoding);
		$this->charset = $charset;
	    $this->contents = "";
	}

	function getCharset()
	{
	    return $this->charset;
	}

	function getText()
	{
	    return $this->contents;
	}

	function &getTextRef()
	{
	    return $this->contents;
	}

	function setText($newtext)
	{
	    $this->contents = $newtext;
	}

    function renderHeaders()
	{
	    $headers = parent::renderHeaders();
		$header_array = mk_header_array($headers, $err);
		$header_array['Content-Type'] .= "; charset=" . $this->charset;
		$headers = mk_header_text($header_array);
		return $headers;
	}

	function renderBody()
	{
	    $body = parent::renderBody();
		return $body;
	}

	function render()
	{
	    $rendered = $this->renderHeaders() . "\n" . $this->renderBody();
		
		return $rendered;
	}
}

class mimeHtmlObject extends mimeTextObject
{
    function __construct($charset = "us_ascii", $encoding = "7bit")
	{
	    parent::__construct("text/html", $charset, $encoding);
	}

	function render()
	{
	    $rendered = $this->renderHeaders() . "\n" . $this->renderBody();
		
		return $rendered;
	}

    function renderHeaders()
	{
	    $headers = parent::renderHeaders();
		return $headers;
	}


	function renderBody()
	{
	    $body = parent::renderBody();
		return $body;
	}
}

class mimeMultipartObject extends mimeObject
{
    var $partSeperator;
	var $nonMIMEContents;
	
	function __construct($type, $encoding = "7bit")
	{
	    parent::__construct($type, $encoding);
	    $this->partSeperator = "MMO" . chr(rand(65, 91)) . '----' . md5(uniqid(rand(), 1));
		$this->contents = array();
	}

	function addPart($mimeObj)
	{
	    $this->contents[] = &$mimeObj;
	}
	
	function setNonMIMEContents($text)
	{
	    $this->nonMIMEContents = $text;
	}

	function render()
	{
	    $rendered = $this->renderHeaders() . "\n" . $this->renderBody();
		
		return $rendered;
	}

    function renderHeaders()
	{
	    $headers = parent::renderHeaders();
		$header_array = mk_header_array($headers, $err);
		$header_array['Content-Type'] .= "; boundary=\"" . $this->partSeperator . "\"";
		$headers = mk_header_text($header_array);
		return $headers;
	}

	function renderBody()
	{
	    $rendered = $this->nonMIMEContents . "\n";
	    foreach($this->contents as $part)
		{
		    $rendered .= "--" . $this->partSeperator . "\n";
			$rendered .= $part->render() . "\n";
		}
		$rendered .= "--" . $this->partSeperator . "--\n";
		
		return $rendered;
	}
}

class mimeMultipartAlternative extends mimeMultipartObject
{
	function __construct($encoding = "7bit")
	{
	    parent::__construct("multipart/alternative", $encoding);
	}

	function render()
	{
	    $rendered = $this->renderHeaders() . "\n" . $this->renderBody();
		
		return $rendered;
	}

    function renderHeaders()
	{
	    $headers = parent::renderHeaders();
		return $headers;
	}

	function renderBody()
	{
	    $body = parent::renderBody();
		return $body;
	}
}

class mimeMultipartMixed extends mimeMultipartObject
{
	function __construct($encoding = "7bit")
	{
	    parent::__construct("multipart/mixed", $encoding);
	}

	function render()
	{
	    $rendered = $this->renderHeaders() . "\n" . $this->renderBody();
		
		return $rendered;
	}

    function renderHeaders()
	{
	    $headers = parent::renderHeaders();
		return $headers;
	}

	function renderBody()
	{
	    $body = parent::renderBody();
		return $body;
	}
}

 ?>
