4 ** This contains the functions necessary to detect and decode MIME
12 if (!isset($i18n_php))
13 include "../functions/i18n.php";
14 if (!isset($imap_php))
15 include "../functions/imap.php";
16 if (!isset($config_php))
17 include "../config/config.php";
20 /** Setting up the objects that have the structure for the message **/
23 /** msg_header contains generic variables for values that **/
24 /** could be in a header. **/
26 var $type0, $type1, $boundary, $charset, $encoding;
27 var $to, $from, $date, $cc, $bcc, $reply_to, $subject;
28 var $id, $mailbox, $description;
29 var $entity_id, $message_id, $charset;
33 /** message is the object that contains messages. It is a recursive
34 object in that through the $entities variable, it can contain
35 more objects of type message. See documentation in mime.txt for
36 a better description of how this works.
41 function addEntity ($msg) {
42 $this->entities
[count($this->entities
)] = $msg;
48 /* --------------------------------------------------------------------------------- */
50 /* --------------------------------------------------------------------------------- */
52 // This function gets the structure of a message and stores it in the "message" class.
53 // It will return this object for use with all relevant header information and
54 // fully parsed into the standard "message" object format.
55 function mime_structure ($imap_stream, $header) {
57 sqimap_messages_flag ($imap_stream, $header->id
, $header->id
, "Seen");
60 fputs ($imap_stream, "a001 FETCH $id BODYSTRUCTURE\r\n");
61 $read = fgets ($imap_stream, 10000);
62 $response = substr($read, 0, 4);
63 while ($response != "a001") {
64 $bodystructure = $read;
65 $read = fgets ($imap_stream, 10000);
66 $response = substr($read, 0, 4);
68 $read = strtolower($bodystructure);
70 if ($debug_mime) echo "<tt>$read</tt><br><br>";
71 // isolate the body structure and remove beginning and end parenthesis
72 $read = trim(substr ($read, strpos($read, "bodystructure") +
13));
73 $read = trim(substr ($read, 0, -1));
74 $end = mime_match_parenthesis(0, $read);
75 while ($end == strlen($read)-1) {
76 $read = trim(substr ($read, 0, -1));
77 $read = trim(substr ($read, 1));
78 $end = mime_match_parenthesis(0, $read);
81 if ($debug_mime) echo "<tt>$read</tt><br><br>";
83 $msg = mime_parse_structure ($read, 0);
84 $msg->header
= $header;
88 // this starts the parsing of a particular structure. It is called recursively,
89 // so it can be passed different structures. It returns an object of type
91 // First, it checks to see if it is a multipart message. If it is, then it
92 // handles that as it sees is necessary. If it is just a regular entity,
93 // then it parses it and adds the necessary header information (by calling out
94 // to mime_get_elements()
95 function mime_parse_structure ($structure, $ent_id) {
97 if ($debug_mime) echo "<font color=008800><tt>START: mime_parse_structure()</tt></font><br>";
99 if (substr($structure, 0, 1) == "(") {
100 $ent_id = mime_new_element_level($ent_id);
102 if ($debug_mime) echo "<br><font color=0000aa><tt>$structure</tt></font><br>";
104 if ($debug_mime) echo "<font color=008800><tt>Found entity...</tt></font><br>";
106 $end = mime_match_parenthesis ($start, $structure);
108 $element = substr($structure, $start+
1, ($end - $start)-1);
109 $ent_id = mime_increment_id ($ent_id);
110 $newmsg = mime_parse_structure ($element, $ent_id);
111 $msg->addEntity ($newmsg);
112 } while (substr($structure, $end+
1, 1) == "(");
114 // parse the elements
115 if ($debug_mime) echo "<br><font color=0000aa><tt>$structure</tt></font><br>";
116 $msg = mime_get_element (&$structure, $msg, $ent_id);
117 if ($debug_mime) echo "<br>";
120 if ($debug_mime) echo "<font color=008800><tt> END: mime_parse_structure()</tt></font><br>";
123 // Increments the element ID. An element id can look like any of
124 // the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
125 // the last number of the element id, changing 1.2 to 1.3.
126 function mime_increment_id ($id) {
128 if (strpos($id, ".")) {
129 $first = substr($id, 0, strrpos($id, "."));
130 $last = substr($id, strrpos($id, ".")+
1);
132 $new = $first . "." .$last;
136 if ($debug_mime) echo "<b>INCREMENT: $new</b><br>";
140 // See comment for mime_increment_id().
141 // This adds another level on to the entity_id changing 1.3 to 1.3.0
142 // NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
143 // before it can be used. I left it this way so as not to have
144 // to make a special case if it is the first entity_id. It
145 // always increments it, and that works fine.
146 function mime_new_element_level ($id) {
148 else $id = $id . ".0";
153 function mime_get_element (&$structure, $msg, $ent_id) {
156 $msg->header
= new msg_header();
157 $msg->header
->entity_id
= $ent_id;
159 while (strlen($structure) > 0) {
160 $structure = trim($structure);
161 $char = substr($structure, 0, 1);
163 if (substr($structure, 0, 3) == "nil") {
165 $structure = substr($structure, 3);
166 } else if ($char == "\"") {
167 // loop through until we find the matching quote, and return that as a string
169 $char = substr($structure, $pos, 1);
170 while ($char != "\"" && $pos < strlen($structure)) {
173 $char = substr($structure, $pos, 1);
175 $structure = substr($structure, strlen($text) +
2);
176 } else if ($char == "(") {
178 $end = mime_match_parenthesis (0, $structure);
179 $sub = substr($structure, 1, $end-1);
180 $properties = mime_get_props($properties, $sub);
181 $structure = substr($structure, strlen($sub) +
2);
183 // loop through until we find a space or an end parenthesis
185 $char = substr($structure, $pos, 1);
186 while ($char != " " && $char != ")" && $pos < strlen($structure)) {
189 $char = substr($structure, $pos, 1);
191 $structure = substr($structure, strlen($text));
193 if ($debug_mime) echo "<tt>$elem_num : $text</tt><br>";
195 // This is where all the text parts get put into the header
198 $msg->header
->type0
= $text;
199 if ($debug_mime) echo "<tt>type0 = $text</tt><br>";
202 $msg->header
->type1
= $text;
203 if ($debug_mime) echo "<tt>type1 = $text</tt><br>";
206 $msg->header
->description
= $text;
207 if ($debug_mime) echo "<tt>description = $text</tt><br>";
210 $msg->header
->encoding
= $text;
211 if ($debug_mime) echo "<tt>encoding = $text</tt><br>";
214 $msg->header
->size
= $text;
215 if ($debug_mime) echo "<tt>size = $text</tt><br>";
218 if ($msg->header
->type0
== "text" && $elem_num == 8) {
219 // This is a plain text message, so lets get the number of lines
221 $msg->header
->num_lines
= $text;
222 if ($debug_mime) echo "<tt>num_lines = $text</tt><br>";
224 } else if ($msg->header
->type0
== "message" && $msg->header
->type1
== "rfc822" && $elem_num == 8) {
225 // This is an encapsulated message, so lets start all over again and
226 // parse this message adding it on to the existing one.
227 $structure = trim($structure);
228 if (substr($structure, 0, 1) == "(") {
229 $e = mime_match_parenthesis (0, $structure);
230 $structure = substr($structure, 0, $e);
231 $structure = substr($structure, 1);
232 $m = mime_parse_structure($structure, $msg->header
->entity_id
);
234 // the following conditional is there to correct a bug that wasn't
235 // incrementing the entity IDs correctly because of the special case
236 // that message/rfc822 is. This fixes it fine.
237 if (substr($structure, 1, 1) != "(")
238 $m->header
->entity_id
= mime_increment_id(mime_new_element_level($ent_id));
240 // Now we'll go through and reformat the results.
242 for ($i=0; $i < count($m->entities
); $i++
) {
243 $msg->addEntity($m->entities
[$i]);
256 // loop through the additional properties and put those in the various headers
257 if ($msg->header
->type0
!= "message") {
258 for ($i=0; $i < count($properties); $i++
) {
259 $msg->header
->{$properties[$i]["name"]} = $properties[$i]["value"];
260 if ($debug_mime) echo "<tt>".$properties[$i]["name"]." = " . $properties[$i]["value"] . "</tt><br>";
267 // I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
268 // figure out how to do this part, so I decided to go to bed. I woke up
269 // in the morning and had a flash of insight. I went to the white-board
270 // and scribbled it out, then spent a bit programming it, and this is the
271 // result. Nothing complicated, but I think my brain was fried yesterday.
272 // Funny how that happens some times.
274 // This gets properties in a nested parenthesisized list. For example,
275 // this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
276 // This returns an array called $props with all paired up properties.
277 // It ignores the "attachment" for now, maybe that should change later
278 // down the road. In this case, what is returned is:
279 // $props[0]["name"] = "filename";
280 // $props[0]["value"] = "luke.tar.gz";
281 function mime_get_props ($props, $structure) {
283 while (strlen($structure) > 0) {
284 $structure = trim($structure);
285 $char = substr($structure, 0, 1);
289 $char = substr($structure, $pos, 1);
290 while ($char != "\"" && $pos < strlen($structure)) {
293 $char = substr($structure, $pos, 1);
295 $structure = trim(substr($structure, strlen($tmp) +
2));
296 $char = substr($structure, 0, 1);
300 $char = substr($structure, $pos, 1);
301 while ($char != "\"" && $pos < strlen($structure)) {
304 $char = substr($structure, $pos, 1);
306 $structure = trim(substr($structure, strlen($tmp) +
2));
309 $props[$k]["name"] = $tmp;
310 $props[$k]["value"] = $value;
311 } else if ($char == "(") {
312 $end = mime_match_parenthesis (0, $structure);
313 $sub = substr($structure, 1, $end-1);
314 $props = mime_get_props($props, $sub);
315 $structure = substr($structure, strlen($sub) +
2);
318 } else if ($char == "(") {
319 $end = mime_match_parenthesis (0, $structure);
320 $sub = substr($structure, 1, $end-1);
321 $props = mime_get_props($props, $sub);
322 $structure = substr($structure, strlen($sub) +
2);
330 // Matches parenthesis. It will return the position of the matching
331 // parenthesis in $structure. For instance, if $structure was:
332 // ("text" "plain" ("val1name", "1") nil ... )
334 // then this would return 42 to match up those two.
335 function mime_match_parenthesis ($pos, $structure) {
336 $char = substr($structure, $pos, 1);
338 // ignore all extra characters
339 while ($pos < strlen($structure)) {
341 $char = substr($structure, $pos, 1);
344 } else if ($char == "(") {
345 $pos = mime_match_parenthesis ($pos, $structure);
350 function mime_fetch_body ($imap_stream, $id, $ent_id) {
351 // do a bit of error correction. If we couldn't find the entity id, just guess
352 // that it is the first one. That is usually the case anyway.
353 if (!$ent_id) $ent_id = 1;
355 fputs ($imap_stream, "a001 FETCH $id BODY[$ent_id]\r\n");
356 $topline = fgets ($imap_stream, 1024);
357 $size = substr ($topline, strpos($topline, "{")+
1);
358 $size = substr ($size, 0, strpos($size, "}"));
359 $read = fread ($imap_stream, $size);
363 /* -[ END MIME DECODING ]----------------------------------------------------------- */
367 /** This is the first function called. It decides if this is a multipart
368 message or if it should be handled as a single entity
370 function decodeMime ($imap_stream, $body, $header) {
371 global $username, $key, $imapServerAddress, $imapPort;
372 return mime_structure ($imap_stream, $header);
375 // This is here for debugging purposese. It will print out a list
376 // of all the entity IDs that are in the $message object.
377 function listEntities ($message) {
379 if ($message->header
->entity_id
)
380 echo "<tt>" . $message->header
->entity_id
. " : " . $message->header
->type0
. "/" . $message->header
->type1
. "<br>";
381 for ($i = 0; $message->entities
[$i]; $i++
) {
382 $msg = listEntities($message->entities
[$i], $ent_id);
389 // returns a $message object for a particular entity id
390 function getEntity ($message, $ent_id) {
392 if ($message->header
->entity_id
== $ent_id && strlen($ent_id) == strlen($message->header
->entity_id
)) {
395 for ($i = 0; $message->entities
[$i]; $i++
) {
396 $msg = getEntity ($message->entities
[$i], $ent_id);
404 // figures out what entity to display and returns the $message object
406 function findDisplayEntity ($message) {
408 if ($message->header
->type0
== "text") {
409 if ($message->header
->type1
== "plain" ||
410 $message->header
->type1
== "html") {
411 return $message->header
->entity_id
;
414 for ($i=0; $message->entities
[$i]; $i++
) {
415 return findDisplayEntity($message->entities
[$i]);
421 /** This returns a parsed string called $body. That string can then
422 be displayed as the actual message in the HTML. It contains
423 everything needed, including HTML Tags, Attachments at the
426 function formatBody($imap_stream, $message, $color, $wrap_at) {
427 // this if statement checks for the entity to show as the
428 // primary message. To add more of them, just put them in the
429 // order that is their priority.
430 global $startMessage, $username, $key, $imapServerAddress, $imapPort;
432 $id = $message->header
->id
;
433 $urlmailbox = urlencode($message->header
->mailbox
);
435 // Get the right entity and redefine message to be this entity
436 $ent_num = findDisplayEntity ($message);
437 $body_message = getEntity($message, $ent_num);
439 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
440 $body = decodeBody($body, $body_message->header
->encoding
);
442 // If there are other types that shouldn't be formatted, add
444 if ($message->header
->type1
!= "html") {
445 $body = translateText($body, $wrap_at, $body_message->header
->charset
);
448 $body .= "<SMALL><CENTER><A HREF=\"../src/download.php?absolute_dl=true&passed_id=$id&passed_ent_id=$ent_num&mailbox=$urlmailbox\">". _("Download this as a file") ."</A></CENTER><BR></SMALL>";
450 /** Display the ATTACHMENTS: message if there's more than one part **/
451 if ($message->entities
) {
452 $body .= "</TD></TR></TABLE>";
453 $body .= "<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=4 BORDER=0><TR><TD BGCOLOR=\"$color[0]\">";
454 $body .= "<TT><B>ATTACHMENTS:</B></TT>";
455 $body .= "</TD></TR><TR><TD BGCOLOR=\"$color[0]\">";
458 $body .= formatAttachments ($message, $ent_num, $message->header
->mailbox
, $id);
459 $body .= "</TD></TR></TABLE>";
461 $body .= "</TD></TR></TABLE>";
466 // A recursive function that returns a list of attachments with links
467 // to where to download these attachments
468 function formatAttachments ($message, $ent_id, $mailbox, $id) {
469 global $where, $what;
470 global $startMessage;
472 if (!$message->entities
) {
473 $type0 = strtolower($message->header
->type0
);
474 $type1 = strtolower($message->header
->type1
);
476 if ($message->header
->entity_id
!= $ent_id) {
477 $filename = decodeHeader($message->header
->filename
);
478 if (trim($filename) == "") {
479 $display_filename = "untitled-".$message->header
->entity_id
;
481 $display_filename = $filename;
484 $urlMailbox = urlencode($mailbox);
485 $ent = urlencode($message->header
->entity_id
);
486 if ($where && $what) {
488 $body .= "<TT> <A HREF=\"../src/download.php?startMessage=$startMessage&where=".urlencode($where)."&what=".urlencode($what)."&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent\">" . $display_filename . "</A> (TYPE: $type0/$type1)";
490 $body .= "<TT> <A HREF=\"../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent\">" . $display_filename . "</A> (TYPE: $type0/$type1)";
492 if ($message->header
->description
)
493 $body .= " <b>" . htmlspecialchars($message->header
->description
)."</b>";
494 $body .= " (<a href=\"../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent\">"._("download")."</a>)\n";
495 $body .= "</TT><BR>";
500 for ($i = 0; $i < count($message->entities
); $i++
) {
501 $body .= formatAttachments ($message->entities
[$i], $ent_id, $mailbox, $id);
509 /** this function decodes the body depending on the encoding type. **/
510 function decodeBody($body, $encoding) {
511 $body = str_replace("\r\n", "\n", $body);
512 $encoding = strtolower($encoding);
514 if ($encoding == "quoted-printable") {
515 $body = quoted_printable_decode($body);
517 while (ereg("=\n", $body))
518 $body = ereg_replace ("=\n", "", $body);
519 } else if ($encoding == "base64") {
520 $body = base64_decode($body);
523 // All other encodings are returned raw.
528 // This functions decode strings that is encoded according to
529 // RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
530 function decodeHeader ($string) {
531 if (eregi('=\?([^?]+)\?(q|b)\?([^?]+)\?=',
533 if (ucfirst($res[2]) == "B") {
534 $replace = base64_decode($res[3]);
536 $replace = ereg_replace("_", " ", $res[3]);
537 // Convert lowercase Quoted Printable to uppercase for
538 // quoted_printable_decode to understand it.
539 while (ereg("(=([0-9][a-f])|([a-f][0-9]))", $replace, $res)) {
540 $replace = str_replace($res[1], strtoupper($res[1]), $replace);
542 $replace = quoted_printable_decode($replace);
545 $replace = charset_decode ($res[1], $replace);
547 $string = eregi_replace
548 ('=\?([^?]+)\?(q|b)\?([^?]+)\?=',
550 // In case there should be more encoding in the string: recurse
551 return (decodeHeader($string));
556 // Encode a string according to RFC 1522 for use in headers if it
557 // contains 8-bit characters or anything that looks like it should
559 function encodeHeader ($string) {
560 global $default_charset;
562 // Encode only if the string contains 8-bit characters or =?
563 if (ereg("([\200-\377])|=\\?", $string)) {
564 $newstring = "=?$default_charset?Q?";
566 // First the special characters
567 $string = str_replace("=", "=3D", $string);
568 $string = str_replace("?", "=3F", $string);
569 $string = str_replace("_", "=5F", $string);
570 $string = str_replace(" ", "_", $string);
573 while (ereg("([\200-\377])", $string, $regs)) {
575 $insert = "=" . strtoupper(bin2hex($replace));
576 $string = str_replace($replace, $insert, $string);
579 $newstring = "=?$default_charset?Q?".$string."?=";