Source for file mime_parser.php
Documentation is available at mime_parser.php
* @(#) $Id: mime_parser.php,v 1.1 2008/12/31 16:04:04 tblue246 Exp $
define('MIME_PARSER_START', 1);
define('MIME_PARSER_HEADER', 2);
define('MIME_PARSER_HEADER_VALUE', 3);
define('MIME_PARSER_BODY', 4);
define('MIME_PARSER_BODY_START', 5);
define('MIME_PARSER_BODY_DATA', 6);
define('MIME_PARSER_BODY_DONE', 7);
define('MIME_MESSAGE_START', 1);
define('MIME_MESSAGE_GET_HEADER_NAME', 2);
define('MIME_MESSAGE_GET_HEADER_VALUE', 3);
define('MIME_MESSAGE_GET_BODY', 4);
define('MIME_MESSAGE_GET_BODY_PART', 5);
define('MIME_ADDRESS_START', 1);
define('MIME_ADDRESS_FIRST', 2);
{metadocument}<?xml version="1.0" encoding="ISO-8859-1" ?>
<package>net.manuellemos.mimeparser</package>
<version>@(#) $Id: mime_parser.php,v 1.1 2008/12/31 16:04:04 tblue246 Exp $</version>
<copyright>Copyright © (C) Manuel Lemos 2006</copyright>
<title>MIME parser</title>
<author>Manuel Lemos</author>
<authoraddress>mlemos-at-acm.org</authoraddress>
<purpose>Parse MIME encapsulated e-mail message data compliant with
the RFC 2822 or aggregated in mbox format.</purpose>
<usage>Use the function <functionlink>Decode</functionlink> function
to retrieve the structure of the messages to be parsed. Adjust its
parameters to tell how to return the decoded body data.
Use the <tt>SaveBody</tt> parameter to make the body parts be saved
to files when the message is larger than the available memory. Use
the <tt>SkipBody</tt> parameter to just retrieve the message
structure without returning the body data.<paragraphbreak />
If the message data is an archive that may contain multiple messages
aggregated in the mbox format, set the variable
<variablelink>mbox</variablelink> to <booleanvalue>1</booleanvalue>.</usage>
<purpose>Store the message that is returned when an error
<usage>Check this variable to understand what happened when a call to
any of the class functions has failed.<paragraphbreak />
This class uses cumulative error handling. This means that if one
class functions that may fail is called and this variable was
already set to an error message due to a failure in a previous call
to the same or other function, the function will also fail and does
not do anything.<paragraphbreak />
This allows programs using this class to safely call several
functions that may fail and only check the failure condition after
the last function call.<paragraphbreak />
Just set this variable to an empty string to clear the error
<name>error_position</name>
<purpose>Point to the position of the message data or file that
refers to the last error that occurred.</purpose>
<usage>Check this variable to determine the relevant position of the
message when a parsing error occurs.</usage>
<purpose>Specify whether the message data to parse is a single RFC
2822 message or it is an archive that contain multiple messages in
the mbox format.</purpose>
<usage>Set this variable to <booleanvalue>1</booleanvalue> if it is
it is intended to parse an mbox message archive.<br />
mbox archives may contain multiple messages. Each message starts
with the header <tt>From</tt>. Since all valid RFC 2822 headers
must with a colon, the class will fail to parse a mbox archive if
this variable is set to <booleanvalue>0</booleanvalue>.</usage>
<name>decode_headers</name>
<purpose>Specify whether the message headers should be decoded.</purpose>
<usage>Set this variable to <booleanvalue>1</booleanvalue> if it is
necessary to decode message headers that may have non-ASCII
characters and use other character set encodings.</usage>
<name>decode_bodies</name>
<purpose>Specify whether the message body parts should be decoded.</purpose>
<usage>Set this variable to <booleanvalue>1</booleanvalue> if it is
necessary to parse the message bodies and extract its part
<name>extract_addresses</name>
<purpose>Specify whether the message headers that usually contain
e-mail addresses should be parsed and the addresses should be
extracted by the <functionlink>Decode</functionlink> function.</purpose>
<usage>Set this variable to <booleanvalue>1</booleanvalue> if it is
necessary to extract the e-mail addresses contained in certain
message headers.<paragraphbreak />
The headers to be parsed are defined by the
<variablelink>address_headers</variablelink> variable.<paragraphbreak />
The parsed addresses are returned by the
<tt>ExtractedAddresses</tt> entry of the <argumentlink>
<function>Decode</function>
<argument>decoded</argument>
</argumentlink> argument of the
<functionlink>Decode</functionlink> function.</usage>
<name>address_headers</name>
<purpose>Specify which headers contain addresses that should be
parsed and extracted.</purpose>
<usage>Change this variable if you need to extract e-mail addresses
from a different list of message headers.<paragraphbreak />
It must be set to an associative array with keys set to the names
of the headers to be parsed including the colon. The array values
must be set to a boolean flag to tell whether the headers with the
respective name should be parsed. The header names must be in lower
By default the class addresses from the headers:
<stringvalue>from:</stringvalue>, <stringvalue>to:</stringvalue>,
<stringvalue>cc:</stringvalue>, <stringvalue>bcc:</stringvalue>,
<stringvalue>return-path:</stringvalue>,
<stringvalue>reply-to:</stringvalue> and
<stringvalue>disposition-notification-to:</stringvalue>.</usage>
'disposition-notification-to:'=>
1
<name>ignore_syntax_errors</name>
<purpose>Specify whether the class should ignore syntax errors in
malformed messages.</purpose>
<usage>Set this variable to <booleanvalue>0</booleanvalue> if it is
necessary to verify whether message data may be corrupted due to
to eventual bugs in the program that generated the
message.<paragraphbreak />
Currently the class only ignores some types of syntax errors.
Other syntax errors may still cause the
<functionlink>Decode</functionlink> to fail.</usage>
<purpose>Return a list of positions of the original message that
contain syntax errors.</purpose>
<usage>Check this variable to retrieve eventual message syntax
errors that were ignored when the
<variablelink>ignore_syntax_errors</variablelink> is set to
<booleanvalue>1</booleanvalue>.<paragraphbreak />
The indexes of this array are the positions of the errors. The
array values are the corresponding syntax error messages.</usage>
var $state =
MIME_PARSER_START;
return($this->SetError($error.
'. Please contact the author Manuel Lemos <mlemos@acm.org> and send a copy of this message to let him add support for this kind of messages'));
if(IsSet
($php_error_message)
&&
strlen($php_error_message))
$error .=
': '.
$php_error_message;
Function Tokenize($string,$separator=
"")
for($character=
0;$character<
strlen($separator);$character++
)
if(GetType($position=
strpos($string,$separator[$character]))==
'integer')
$found=
(IsSet
($found) ?
min($found,$position) :
$position);
return(substr($string,0,$found));
$parameters =
$character_sets =
$languages =
array();
&&
!strcmp($parameter[$l -
1],'*'))
$parameter=
$this->Tokenize($parameter, '*');
if(IsSet
($parameters[$parameter])
&& IsSet
($character_sets[$parameter]))
$value =
$parameters[$parameter] .
UrlDecode($value);
$languages[$parameter] =
$this->Tokenize('\'');
$value =
UrlDecode($this->Tokenize(''));
$parameters[$parameter] =
$value;
if(GetType($line_break=
strpos($string, $break=
"\n", $position))==
'integer')
&&
$string[$line_break-
1]==
"\r")
return(GetType($line_break=
strpos($string, $break=
"\r", $position))==
'integer');
if(GetType($line_break=
strpos($this->buffer, $break=
"\r", $position))==
'integer')
return(GetType($line_break=
strpos($this->buffer, $break=
"\n", $position))==
'integer');
if(GetType($line_break=
strpos($this->body_buffer, $break=
"\r", $position))==
'integer')
return(GetType($line_break=
strpos($this->body_buffer, $break=
"\n", $position))==
'integer');
$line =
substr($body, $position, $line_break -
$position);
$position =
$line_break +
strlen($break);
$line =
substr($body, $position);
Function ParsePart($end, &$part, &$need_more_data)
$next =
$line_break +
strlen($break);
$next =
$line_break +
strlen($break);
$line =
substr($this->buffer, $position, $line_break -
$position);
$character =
$this->buffer[$next];
$next =
$line_break +
strlen($break);
$following =
$next +
strlen($break);
||
GetType($line=
strpos($this->buffer, $break, $following))!=
'integer')
if(!strcmp($break.
'from ', $start))
if(GetType($line_break=
strrpos($data, "\n"))==
'integer'
||
GetType($line_break=
strrpos($data, "\r"))==
'integer')
$data =
substr($data, 0, $line_break);
if(!IsSet
($part['Part']))
$part['Part']=
$this->headers['Boundary'];
$parameters[$parameter] =
$value;
if(!strcmp($parameter, $return))
for($decoded_header =
array(), $position =
0; $position<
strlen($value); )
if(GetType($encoded=
strpos($value,'=?', $position))!=
'integer')
if(count($decoded_header))
$decoded_header[count($decoded_header)-
1]['Value'].=
substr($value, $position);
'Value'=>
substr($value, $position),
if(GetType($method=
strpos($value,'?', $set))!=
'integer')
$error =
'invalid header encoding syntax '.
$part['Value'];
$error_position =
$part['Position'] +
$set;
if(GetType($data=
strpos($value,'?', $method))!=
'integer')
$error =
'invalid header encoding syntax '.
$part['Value'];
$error_position =
$part['Position'] +
$set;
if(GetType($end=
strpos($value,'?=', $start))!=
'integer')
$error =
'invalid header encoding syntax '.
$part['Value'];
$error_position =
$part['Position'] +
$start;
if(count($decoded_header))
$decoded_header[count($decoded_header)-
1]['Value'].=
substr($value, $position, $encoded -
$position);
'Value'=>
substr($value, $position, $encoded -
$position),
for($decoded =
'', $position =
$start; $position <
$end ; )
switch($value[$position])
$warning =
'the header specified an invalid encoded character';
$warning_position =
$part['Position'] +
$position +
1;
$error_position =
$warning_position;
$decoded .=
$value[$position];
if(count($decoded_header)
&&
(!strcmp($decoded_header[$last =
count($decoded_header)-
1]['Encoding'], 'ASCII'))
||
!strcmp($decoded_header[$last]['Encoding'], $encoding))
$decoded_header[$last]['Value'].=
$decoded;
$decoded_header[$last]['Encoding']=
$encoding;
||
GetType($decoded) !=
'string'
$warning =
'the header specified an invalid base64 encoded text';
$warning_position =
$part['Position'] +
$start;
$error_position =
$warning_position;
if(count($decoded_header)
&&
(!strcmp($decoded_header[$last =
count($decoded_header)-
1]['Encoding'], 'ASCII'))
||
!strcmp($decoded_header[$last]['Encoding'], $encoding))
$decoded_header[$last]['Value'].=
$decoded;
$decoded_header[$last]['Encoding']=
$encoding;
$error =
'the header specified an unsupported encoding method';
$error_position =
$part['Position'] +
$method;
&&
count($decoded_header))
$part['Decoded']=
$decoded_header;
$boundary =
$this->ParseParameters($part['Value'], $type, $parameters, 'boundary');
$part['MainValue'] =
$type;
$part['Parameters'] =
$parameters;
$this->headers['Boundary'] =
$boundary;
return($this->SetPositionedError('multipart content-type header does not specify the boundary parameter', $part['Position']));
case 'content-transfer-encoding:':
$this->headers['QuotedPrintable'] =
1;
&& IsSet
($this->headers['Multipart']))
&& IsSet
($this->headers['Multipart'])
if(IsSet
($this->headers['Multipart']))
$boundary =
'--'.
$this->headers['Boundary'];
$next =
$line_break +
strlen($break);
'Part'=>
$this->headers['Boundary'],
$next =
$line_break +
strlen($break);
'Part'=>
$this->headers['Boundary'],
'Part'=>
$this->headers['Boundary'],
elseif(!strcmp($line, $boundary.
'--'))
'Part'=>
$this->headers['Boundary'],
elseif(IsSet
($this->headers['QuotedPrintable']))
$position =
$next +
strlen($break);
$part['Data'] =
$decoded;
elseif(IsSet
($this->headers['Base64']))
Function DecodeStream($parameters, &$end_of_message, &$decoded)
if(IsSet
($parameters['File']))
if(GetType($data)!=
'string')
return($this->SetPHPError('could not read the message file', $php_errormsg));
if(!$this->Parse($data, $end_of_data))
$value =
trim($part['Value']);
if(!IsSet
($decoded['Headers'][$header]))
$decoded['Headers'][$header]=
$value;
$decoded['HeaderPositions'][$header] =
$part['Position'];
elseif(GetType($decoded['Headers'][$header])==
'string')
$decoded['Headers'][$header]=
array($decoded['Headers'][$header], $value);
$h =
count($decoded['Headers'][$header]);
$decoded['Headers'][$header][]=
$value;
if(IsSet
($part['Decoded'])
&&
(count($part['Decoded'])>
1
||
strcmp($part['Decoded'][0]['Encoding'],'ASCII')
||
strcmp($value, trim($part['Decoded'][0]['Value']))))
$p[0]['Value']=
ltrim($p[0]['Value']);
$p[$last]['Value']=
rtrim($p[$last]['Value']);
$decoded['DecodedHeaders'][$header][$h]=
$p;
case 'content-disposition:':
if(!IsSet
($decoded['FileName']))
if(IsSet
($header_parameters[$filename]))
$decoded['FileName']=
$header_parameters[$filename];
if(IsSet
($character_sets[$filename])
&&
strlen($character_sets[$filename]))
$decoded['FileNameCharacterSet']=
$character_sets[$filename];
if(IsSet
($character_sets['language'])
&&
strlen($character_sets['language']))
$decoded['FileNameCharacterSet']=
$character_sets[$filename];
if(!strcmp($header, 'content-disposition:'))
$decoded['FileDisposition']=
$type;
if(IsSet
($parameters['SaveBody']))
if(!IsSet
($decoded['BodyFile']))
$directory_separator=
(defined('DIRECTORY_SEPARATOR') ?
DIRECTORY_SEPARATOR :
'/');
$path =
(strlen($parameters['SaveBody']) ?
($parameters['SaveBody'].
(strcmp($parameters['SaveBody'][strlen($parameters['SaveBody'])-
1], $directory_separator) ?
$directory_separator :
'')) :
'').
strval($this->body_part_number);
return($this->SetPHPError('could not create file '.
$path.
' to save the message body part', $php_errormsg));
$decoded['BodyFile'] =
$path;
$decoded['BodyLength'] =
0;
$this->SetPHPError('could not save the message body part to file '.
$decoded['BodyFile'], $php_errormsg);
@unlink($decoded['BodyFile']);
elseif(IsSet
($parameters['SkipBody']))
if(!IsSet
($decoded['BodyPart']))
$decoded['BodyLength'] =
0;
if(IsSet
($decoded['Body']))
$decoded['Body'].=
$part['Data'];
$decoded['Body']=
$part['Data'];
$decoded['BodyLength'] =
0;
$decoded['BodyLength'] +=
strlen($part['Data']);
if(!$this->DecodeStream($parameters, $end_of_part, $decoded_part))
$decoded['Parts'][$part_number]=
$decoded_part;
if(IsSet
($decoded['BodyFile']))
return($this->SetError('unexpected decoded message part type '.
$type.
' in state '.
$state));
Function Parse($data, $end)
return($this->SetError('the parser already reached the end'));
if(!$this->ParsePart($end, $part, $need_more_data))
return($this->SetError('reached a premature end of data'));
if(!($stream =
@fopen($file, 'r')))
return($this->SetPHPError('Could not open the file '.
$file, $php_errormsg));
if(!($data =
@fread($stream, 8000)))
$this->SetPHPError('Could not open the file '.
$file, $php_errormsg);
if(!$this->Parse($data, $end))
<purpose>Parse and decode message data and retrieve its structure.</purpose>
<usage>Pass an array to the <argumentlink>
<function>Decode</function>
<argument>parameters</argument>
parameter to define whether the message data should be read and
parsed from a file or a data string, as well additional parsing
options. The <argumentlink>
<function>Decode</function>
<argument>decoded</argument>
</argumentlink> returns the
data structure of the parsed messages.</usage>
<returnvalue>This function returns <booleanvalue>1</booleanvalue> if
the specified message data is parsed successfully. Otherwise,
check the variables <variablelink>error</variablelink> and
<variablelink>error_position</variablelink> to determine what
error occurred and the relevant message position.</returnvalue>
<purpose>Associative array to specify parameters for the message
data parsing and decoding operation. Here follows the list of
supported parameters that should be used as indexes of the
<tt>File</tt><paragraphbreak />
Name of the file from which the message data will be read. It
may be the name of a file stream or a remote URL, as long as
your PHP installation is configured to allow accessing remote
files with the <tt>fopen()</tt> function.<paragraphbreak />
<tt>Data</tt><paragraphbreak />
String that specifies the message data. This should be used
as alternative data source for passing data available in memory,
like for instance messages stored in a database that was queried
dynamically and the message data was fetched into a string
variable.<paragraphbreak />
<tt>SaveBody</tt><paragraphbreak />
If this parameter is specified, the message body parts are saved
to files. The path of the directory where the files are saved is
defined by this parameter value. The information about the
message body part structure is returned by the <argumentlink>
<function>Decode</function>
<argument>decoded</argument>
</argumentlink> argument, but it just returns the body data part
file name instead of the actual body data. It is recommended for
retrieving messages larger than the available memory. The names
of the body part files are numbers starting from
<stringvalue>1</stringvalue>.<paragraphbreak />
<tt>SkipBody</tt><paragraphbreak />
If this parameter is specified, the message body parts are
skipped. This means the information about the message body part
structure is returned by the <argumentlink>
<function>Decode</function>
<argument>decoded</argument>
</argumentlink> but it does not return any body data. It is
recommended just for parsing messages without the need to
retrieve the message body part data.</purpose>
<purpose>Retrieve the structure of the parsed message headers and
body data.<paragraphbreak />
The argument is used to return by reference an array of message
structure definitions. Each array entry refers to the structure
of each message that is found and parsed successfully.<paragraphbreak />
Each message entry consists of an associative array with several
entries that describe the message structure. Here follows the
list of message structure entries names and the meaning of the
respective values:<paragraphbreak />
<tt>Headers</tt><paragraphbreak />
Associative array that returns the list of all the message
headers. The array entries are the header names mapped to
lower case, including the end colon. The array values are the
respective header raw values without any start or trailing white
spaces. Long header values split between multiple message lines
are gathered in single string without line breaks. If an header
with the same name appears more than once in the message, the
respective value is an array with the values of all of the
header occurrences.<paragraphbreak />
<tt>DecodedHeaders</tt><paragraphbreak />
Associative array that returns the list of all the encoded
<variablelink>decode_headers</variablelink> variable is set. The
array entries are the header names mapped to lower case,
including the end colon. The array values are also arrays that
list only the occurrences of the header that originally were
encoded. Each entry of the decoded header array contains more
associative arrays that describe each part of the decoded
header. Each of those associative arrays have an entry named
<tt>Value</tt> that contains the decoded header part value, and
another entry named <tt>Encoding</tt> that specifies the
character set encoding of the value in upper case.<paragraphbreak />
<tt>ExtractedAddresses</tt><paragraphbreak />
If the <variablelink>extract_addresses</variablelink> variable
is set to <booleanvalue>1</booleanvalue>, this entry is set to an
associative array with the addresses found in the headers
specified by the <variablelink>address_headers</variablelink>
variable.<paragraphbreak />
The parsed addresses found on each header are returned as an
array with the format of the <link>
<url>rfc822_addresses_class.html#argument_ParseAddressList_addresses</url>
</link> argument of the <link>
<data>ParseAddressList</data>
<url>rfc822_addresses_class.html#function_ParseAddressList</url>
</link> function of the <link>
<data>RFC 822 addresses</data>
<url>rfc822_addresses_class.html</url>
</link> class.<paragraphbreak />
<tt>Parts</tt><paragraphbreak />
If this message content type is multipart, this entry is an
array that describes each of the parts contained in the message
body. Each message part is described by an associative array
with the same structure of a complete message
definition.<paragraphbreak />
<tt>Body</tt><paragraphbreak />
String with the decoded data contained in the message body. If
the <tt>SaveBody</tt> or <tt>SkipBody</tt> parameters are
defined, the <tt>Body</tt> entry is not set.<paragraphbreak />
<tt>BodyFile</tt><paragraphbreak />
Name of the file to which the message body data was saved when
the <tt>SaveBody</tt> parameter is defined.<paragraphbreak />
<tt>BodyLength</tt><paragraphbreak />
Length of the current decoded body part.<paragraphbreak />
<tt>BodyPart</tt><paragraphbreak />
Number of the current message body part.<paragraphbreak />
<tt>FileName</tt><paragraphbreak />
Name of the file for body parts composed from
<tt>FileNameCharacterSet</tt><paragraphbreak />
Character set encoding for file parts with names that may
include non-ASCII characters.<paragraphbreak />
<tt>FileNameLanguage</tt><paragraphbreak />
Language of file parts with names that may include non-ASCII
characters.<paragraphbreak />
<tt>FileDisposition</tt><paragraphbreak />
Disposition of parts that files. It may be either
<tt><stringvalue>inline</stringvalue></tt> for file parts to be
displayed with the message, or
<tt><stringvalue>attachment</stringvalue></tt> otherwise.</purpose>
Function Decode($parameters, &$decoded)
if(IsSet
($parameters['File']))
if(!($this->file =
@fopen($parameters['File'], 'r')))
return($this->SetPHPError('could not open the message file to decode '.
$parameters['File'], $php_errormsg));
elseif(IsSet
($parameters['Data']))
return($this->SetError('it was not specified a valid message to decode'));
for($message =
0; ($success =
$this->DecodeStream($parameters, $end_of_message, $decoded_message)) &&
!$end_of_message; $message++
)
$headers =
$decoded_message['Headers'];
$positions =
$decoded_message['HeaderPositions'];
for(Reset($headers), $h =
0; $h<
$th; Next($headers), ++
$h)
$values =
(GetType($headers[$header]) ==
'array' ?
$headers[$header] :
array($headers[$header]));
$p =
(GetType($positions[$header]) ==
'array' ?
$positions[$header] :
array($positions[$header]));
for($v =
0; $v<
$tv; ++
$v)
if($addresses->ParseAddressList($values[$v], $a))
$decoded_message['ExtractedAddresses'][$header] =
$a;
for($l =
0; $l<
$tl; ++
$l)
$decoded_message['ExtractedAddresses'][$header][] =
$a[$l];
$tw =
count($addresses->warnings);
for($w =
0, Reset($addresses->warnings); $w <
$tw; Next($addresses->warnings), $w++
)
$warning =
Key($addresses->warnings);
if(!$this->SetPositionedWarning('Address extraction warning from header '.
$header.
' '.
$addresses->warnings[$warning], $warning +
$p[$v]))
elseif(!$this->SetPositionedWarning('Address extraction error from header '.
$header.
' '.
$addresses->error, $addresses->error_position +
$p[$v]))
UnSet
($decoded_message['HeaderPositions']);
$decoded[$message]=
$decoded_message;
if(IsSet
($parameters['File']))
if(!IsSet
($message['Headers'][$header]))
if(!IsSet
($message['ExtractedAddresses'][$header]))
$values =
(GetType($message['Headers'][$header]) ==
'array' ?
$message['Headers'][$header] :
array($message['Headers'][$header]));
for($v =
0; $v<
$tv; ++
$v)
if($parser->ParseAddressList($values[$v], $a))
for($l =
0; $l<
$tl; ++
$l)
$addresses =
$message['ExtractedAddresses'][$header];
if(IsSet
($message[$prefix]))
$body =
$message[$prefix];
elseif(IsSet
($message[$prefix.
'File']))
$path =
$message[$prefix.
'File'];
if(!($file =
@fopen($path, 'rb')))
return($this->SetPHPError('could not open the message body file '.
$path, $php_errormsg));
for($body =
'', $end =
0;!$end;)
if(!($data =
@fread($file, 8000)))
$this->SetPHPError('Could not open the message body file '.
$path, $php_errormsg);
<purpose>Analyze a parsed message to describe its contents.</purpose>
<usage>Pass an array to the <argumentlink>
<function>Analyze</function>
<argument>message</argument>
parameter with the decoded message array structure returned by the
<functionlink>Decode</functionlink> function. The <argumentlink>
<function>Analyze</function>
<argument>results</argument>
</argumentlink> returns details about the type of message that was
analyzed and its contents.</usage>
<returnvalue>This function returns <booleanvalue>1</booleanvalue> if
the specified message is analyzed successfully. Otherwise,
check the variables <variablelink>error</variablelink> and
<variablelink>error_position</variablelink> to determine what
error occurred.</returnvalue>
<purpose>Pass an associative array with the definition of an
individual message returned by the <argumentlink>
<function>Decode</function>
<argument>decoded</argument>
</argumentlink> argument of the
<functionlink>Decode</functionlink> function..</purpose>
<purpose>Returns an associative array with the results of the
analysis. Some types of entries are returned for all types of
analyzed messages. Other entries are specific to each type of
message.<paragraphbreak />
<tt>Type</tt><paragraphbreak />
Type of message that was analyzed. Currently it supports the
types: <tt>binary</tt>, <tt>text</tt>, <tt>html</tt>,
<tt>video</tt>, <tt>image</tt>, <tt>audio</tt>, <tt>zip</tt>,
<tt>pdf</tt>, <tt>postscript</tt>, <tt>ms-word</tt>,
<tt>ms-excel</tt>, <tt>ms-powerpoint</tt>, <tt>ms-tnef</tt>,
<tt>odf-writer</tt>, <tt>signature</tt>, <tt>report-type</tt>,
<tt>delivery-status</tt> and <tt>message</tt>.<paragraphbreak />
<tt>SubType</tt><paragraphbreak />
Name of the variant of the message type format.<paragraphbreak />
<tt>Description</tt><paragraphbreak />
Human readable description in English of the message type.<paragraphbreak />
<b>From message headers:</b><paragraphbreak />
<tt>Encoding</tt><paragraphbreak />
Character set encoding of the message part.<paragraphbreak />
<tt>Subject</tt><paragraphbreak />
The message subject.<paragraphbreak />
<tt>SubjectEncoding</tt><paragraphbreak />
Character set encoding of the message subject.<paragraphbreak />
<tt>Date</tt><paragraphbreak />
The message date.<paragraphbreak />
<tt>From</tt><paragraphbreak />
<tt>To</tt><paragraphbreak />
<tt>Cc</tt><paragraphbreak />
<tt>Bcc</tt><paragraphbreak />
Array of e-mail addresses found in the <tt>From</tt>,
<tt>To</tt>, <tt>Cc</tt>, <tt>Bcc</tt>.<paragraphbreak />
Each of the entries consists of an associative array with an
entry named <tt>address</tt> with the e-mail address and
optionally another named <tt>name</tt> with the associated
<b>For content message parts:</b><paragraphbreak />
<tt>Data</tt><paragraphbreak />
String of data of the message part.<paragraphbreak />
<tt>DataFile</tt><paragraphbreak />
File with data of the message part.<paragraphbreak />
<tt>DataLength</tt><paragraphbreak />
Length of the data of the message part.<paragraphbreak />
<b>For message with embedded files:</b><paragraphbreak />
<tt>FileName</tt><paragraphbreak />
Original name of the file.<paragraphbreak />
<tt>ContentID</tt><paragraphbreak />
Content identifier of the file to be used in references from
other message parts.<paragraphbreak />
For instance, an HTML message may reference images embedded in
the message using URLs that start with the
<stringvalue>cid:</stringvalue> followed by the content
identifier of the embedded image file part.<paragraphbreak />
<tt>Disposition</tt><paragraphbreak />
Information of whether the embedded file should be displayed
inline when the message is presented, or it is an attachment
<b>For composite message:</b><paragraphbreak />
<tt>Attachments</tt><paragraphbreak />
List of files attached to the message.<paragraphbreak />
<tt>Alternative</tt><paragraphbreak />
List of alternative message parts that can be displayed if the
main message type is not supported by the program displaying
the message.<paragraphbreak />
<tt>Related</tt><paragraphbreak />
List of message parts related with the main message type.<paragraphbreak />
It may list for instance embedded images or CSS files related
with an HTML message type.<paragraphbreak />
<b>For bounced messages or other types of delivery status report
messages:</b><paragraphbreak />
<tt>Recipients</tt><paragraphbreak />
List of recipients of the original message.<paragraphbreak />
Each entry contains an associative array that may have the
entries: <tt>Recipient</tt> with the original recipient address,
<tt>Action</tt> with the name action that triggered the delivery
status report, <tt>Status</tt> with the code of the status of
the message delivery.<paragraphbreak />
<tt>Response</tt><paragraphbreak />
Human readable response sent by the server the originated the
report.<paragraphbreak />
Function Analyze($message, &$results)
$content_type =
(IsSet
($message['Headers']['content-type:']) ?
$message['Headers']['content-type:'] :
'text/plain');
$disposition =
$this->ParseParameters($content_type, $content_type, $parameters, 'disposition');
$type =
$this->Tokenize($content_type, '/');
$tolerate_unrecognized =
1;
$tolerate_unrecognized =
0;
$lp =
count($message['Parts']);
return($this->SetError($this->decode_bodies ?
'No parts were found in the '.
$content_type.
' part message' :
'It is not possible to analyze multipart messages without parsing the contained message parts. Please set the decode_bodies variable to 1 before parsing the message'));
for($p =
0; $p <
$lp; ++
$p)
if(!$this->Analyze($message['Parts'][$p], $parts[$p]))
for(--
$p ; $p >=
0 ; --
$p)
$results['Alternative'][] =
$parts[$p];
for($p =
1; $p <
$lp; ++
$p)
$results['Related'][] =
$parts[$p];
for($p =
1; $p <
$lp; ++
$p)
$results['Attachments'][] =
$parts[$p];
if(IsSet
($parameters['report-type']))
switch($parameters['report-type'])
for($p =
1; $p <
$lp; ++
$p)
if(!strcmp($parts[$p]['Type'], $parameters['report-type']))
$results['Response'] =
$body;
$results['Type'] =
$parameters['report-type'];
return($this->SetError('this '.
$content_type.
' message does not have just 2 parts'));
if(strcmp($parts[1]['Type'], 'signature'))
$results['Signature'] =
$parts[1];
$results['Type'] =
'text';
$results['Description'] =
'Text message';
$results['Type'] =
'html';
$results['Description'] =
'HTML message';
$results['Type'] =
$type;
$results['SubType'] =
$sub_type;
$results['Description'] =
'Text file in the '.
strtoupper($sub_type).
' format';
$results['Type'] =
$type;
$results['SubType'] =
$sub_type;
$results['Description'] =
'Video file in the '.
strtoupper($sub_type).
' format';
$results['Type'] =
$type;
$results['SubType'] =
$sub_type;
$results['Description'] =
'Image file in the '.
strtoupper($sub_type).
' format';
$results['Type'] =
$type;
$results['SubType'] =
$sub_type;
$results['Description'] =
'Audio file in the '.
strtoupper($sub_type).
' format';
$results['Type'] =
'binary';
$results['Description'] =
'Binary file';
$results['Type'] =
$sub_type;
$results['Description'] =
'Document in PDF format';
$results['Type'] =
$sub_type;
$results['Description'] =
'Document in Postscript format';
$results['Type'] =
'ms-word';
$results['Description'] =
'Word processing document in Microsoft Word format';
case 'vnd.ms-powerpoint':
$results['Type'] =
'ms-powerpoint';
$results['Description'] =
'Presentation in Microsoft PowerPoint format';
$results['Type'] =
'ms-excel';
$results['Description'] =
'Spreadsheet in Microsoft Excel format';
$results['Type'] =
'zip';
$results['Description'] =
'ZIP archive with compressed files';
$results['Type'] =
$sub_type;
$results['Description'] =
'Microsoft Exchange data usually sent by Microsoft Outlook';
$results['Type'] =
'signature';
$results['SubType'] =
$sub_type;
$results['Description'] =
'Message signature for PGP';
case 'x-pkcs7-signature':
$results['Type'] =
'signature';
$results['SubType'] =
$sub_type;
$results['Description'] =
'PKCS message signature';
case 'vnd.oasis.opendocument.text':
$results['Type'] =
'odf-writer';
$results['Description'] =
'Word processing document in ODF text format used by OpenOffice Writer';
$tolerate_unrecognized =
0;
$results['Type'] =
$sub_type;
$results['Description'] =
'Notification of the status of delivery of a message';
if(IsSet
($headers['action']))
$recipients[$r]['Action'] =
$headers['action'];
if(IsSet
($headers['status']))
$recipients[$r]['Status'] =
$headers['status'];
if(IsSet
($headers['original-recipient']))
strtok($headers['original-recipient'], ';');
elseif(IsSet
($headers['final-recipient']))
strtok($headers['final-recipient'], ';');
$results['Recipients'] =
$recipients;
$results['Type'] =
'message';
$results['Description'] =
'E-mail message';
$tolerate_unrecognized =
0;
if(!IsSet
($results['Type']))
$results['Type'] =
$this->error;
if(IsSet
($parameters['charset']))
$results['Encoding'] =
strtolower($parameters['charset']);
if(IsSet
($message['Headers']['subject:']))
if(IsSet
($message['DecodedHeaders']['subject:'])
&&
count($message['DecodedHeaders']['subject:']) ==
1
&&
count($message['DecodedHeaders']['subject:'][0]) ==
1)
$results['Subject'] =
$message['DecodedHeaders']['subject:'][0][0]['Value'];
$results['SubjectEncoding'] =
strtolower($message['DecodedHeaders']['subject:'][0][0]['Encoding']);
$results['Subject'] =
$message['Headers']['subject:'];
if(IsSet
($message['Headers']['date:']))
if(IsSet
($message['DecodedHeaders']['date:'])
&&
count($message['DecodedHeaders']['date:']) ==
1
&&
count($message['DecodedHeaders']['date:'][0]) ==
1)
$results['Date'] =
$message['DecodedHeaders']['date:'][0][0]['Value'];
$results['Date'] =
$message['Headers']['date:'];
if(IsSet
($message['Body']))
$results['Data'] =
$message['Body'];
elseif(IsSet
($message['BodyFile']))
$results['DataFile'] =
$message['BodyFile'];
elseif(IsSet
($message['BodyLength']))
$results['DataLength'] =
$message['BodyLength'];
if(IsSet
($message['FileName']))
$results['FileName'] =
$message['FileName'];
if(IsSet
($message['FileDisposition']))
$results['FileDisposition'] =
$message['FileDisposition'];
if(IsSet
($message['Headers']['content-id:']))
$content_id =
trim($message['Headers']['content-id:']);
if(!strcmp($content_id[0], '<')
&&
!strcmp($content_id[$l -
1], '>'))
$results['ContentID'] =
substr($content_id, 1, $l -
2);