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 $endline = fgets($imap_stream, 1024);
63 $read = strtolower($read);
65 if ($debug_mime) echo "<tt>$read</tt><br><br>";
66 // isolate the body structure and remove beginning and end parenthesis
67 $read = trim(substr ($read, strpos($read, "bodystructure") +
13));
68 $read = trim(substr ($read, 0, -1));
69 $end = mime_match_parenthesis(0, $read);
70 while ($end == strlen($read)-1) {
71 $read = trim(substr ($read, 0, -1));
72 $read = trim(substr ($read, 1));
73 $end = mime_match_parenthesis(0, $read);
76 if ($debug_mime) echo "<tt>$read</tt><br><br>";
78 $msg = mime_parse_structure ($read, 0);
79 $msg->header
= $header;
83 // this starts the parsing of a particular structure. It is called recursively,
84 // so it can be passed different structures. It returns an object of type
86 // First, it checks to see if it is a multipart message. If it is, then it
87 // handles that as it sees is necessary. If it is just a regular entity,
88 // then it parses it and adds the necessary header information (by calling out
89 // to mime_get_elements()
90 function mime_parse_structure ($structure, $ent_id) {
92 if ($debug_mime) echo "<font color=008800><tt>START: mime_parse_structure()</tt></font><br>";
94 if (substr($structure, 0, 1) == "(") {
95 $ent_id = mime_new_element_level($ent_id);
97 if ($debug_mime) echo "<br><font color=0000aa><tt>$structure</tt></font><br>";
99 if ($debug_mime) echo "<font color=008800><tt>Found entity...</tt></font><br>";
101 $end = mime_match_parenthesis ($start, $structure);
103 $element = substr($structure, $start+
1, ($end - $start)-1);
104 $ent_id = mime_increment_id ($ent_id);
105 $newmsg = mime_parse_structure ($element, $ent_id);
106 $msg->addEntity ($newmsg);
107 } while (substr($structure, $end+
1, 1) == "(");
109 // parse the elements
110 if ($debug_mime) echo "<br><font color=0000aa><tt>$structure</tt></font><br>";
111 $msg = mime_get_element (&$structure, $msg, $ent_id);
112 if ($debug_mime) echo "<br>";
115 if ($debug_mime) echo "<font color=008800><tt> END: mime_parse_structure()</tt></font><br>";
118 // Increments the element ID. An element id can look like any of
119 // the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
120 // the last number of the element id, changing 1.2 to 1.3.
121 function mime_increment_id ($id) {
123 if (strpos($id, ".")) {
124 $first = substr($id, 0, strrpos($id, "."));
125 $last = substr($id, strrpos($id, ".")+
1);
127 $new = $first . "." .$last;
131 if ($debug_mime) echo "<b>INCREMENT: $new</b><br>";
135 // See comment for mime_increment_id().
136 // This adds another level on to the entity_id changing 1.3 to 1.3.0
137 // NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
138 // before it can be used. I left it this way so as not to have
139 // to make a special case if it is the first entity_id. It
140 // always increments it, and that works fine.
141 function mime_new_element_level ($id) {
143 else $id = $id . ".0";
148 function mime_get_element (&$structure, $msg, $ent_id) {
151 $msg->header
= new msg_header();
152 $msg->header
->entity_id
= $ent_id;
154 while (strlen($structure) > 0) {
155 $structure = trim($structure);
156 $char = substr($structure, 0, 1);
158 if (substr($structure, 0, 3) == "nil") {
160 $structure = substr($structure, 3);
161 } else if ($char == "\"") {
162 // loop through until we find the matching quote, and return that as a string
164 $char = substr($structure, $pos, 1);
165 while ($char != "\"" && $pos < strlen($structure)) {
168 $char = substr($structure, $pos, 1);
170 $structure = substr($structure, strlen($text) +
2);
171 } else if ($char == "(") {
173 $end = mime_match_parenthesis (0, $structure);
174 $sub = substr($structure, 1, $end-1);
175 $properties = mime_get_props($properties, $sub);
176 $structure = substr($structure, strlen($sub) +
2);
178 // loop through until we find a space or an end parenthesis
180 $char = substr($structure, $pos, 1);
181 while ($char != " " && $char != ")" && $pos < strlen($structure)) {
184 $char = substr($structure, $pos, 1);
186 $structure = substr($structure, strlen($text));
188 if ($debug_mime) echo "<tt>$elem_num : $text</tt><br>";
190 // This is where all the text parts get put into the header
193 $msg->header
->type0
= $text;
194 if ($debug_mime) echo "<tt>type0 = $text</tt><br>";
197 $msg->header
->type1
= $text;
198 if ($debug_mime) echo "<tt>type1 = $text</tt><br>";
201 $msg->header
->description
= $text;
202 if ($debug_mime) echo "<tt>description = $text</tt><br>";
205 $msg->header
->encoding
= $text;
206 if ($debug_mime) echo "<tt>encoding = $text</tt><br>";
209 $msg->header
->size
= $text;
210 if ($debug_mime) echo "<tt>size = $text</tt><br>";
213 if ($msg->header
->type0
== "text" && $elem_num == 8) {
214 // This is a plain text message, so lets get the number of lines
216 $msg->header
->num_lines
= $text;
217 if ($debug_mime) echo "<tt>num_lines = $text</tt><br>";
219 } else if ($msg->header
->type0
== "message" && $msg->header
->type1
== "rfc822" && $elem_num == 8) {
220 // This is an encapsulated message, so lets start all over again and
221 // parse this message adding it on to the existing one.
222 $structure = trim($structure);
223 if (substr($structure, 0, 1) == "(") {
224 $e = mime_match_parenthesis (0, $structure);
225 $structure = substr($structure, 0, $e);
226 $structure = substr($structure, 1);
227 $m = mime_parse_structure($structure, $msg->header
->entity_id
);
229 // the following conditional is there to correct a bug that wasn't
230 // incrementing the entity IDs correctly because of the special case
231 // that message/rfc822 is. This fixes it fine.
232 if (substr($structure, 1, 1) != "(")
233 $m->header
->entity_id
= mime_increment_id(mime_new_element_level($ent_id));
235 // Now we'll go through and reformat the results.
237 for ($i=0; $i < count($m->entities
); $i++
) {
238 $msg->addEntity($m->entities
[$i]);
251 // loop through the additional properties and put those in the various headers
252 if ($msg->header
->type0
!= "message") {
253 for ($i=0; $i < count($properties); $i++
) {
254 $msg->header
->{$properties[$i]["name"]} = $properties[$i]["value"];
255 if ($debug_mime) echo "<tt>".$properties[$i]["name"]." = " . $properties[$i]["value"] . "</tt><br>";
262 // I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
263 // figure out how to do this part, so I decided to go to bed. I woke up
264 // in the morning and had a flash of insight. I went to the white-board
265 // and scribbled it out, then spent a bit programming it, and this is the
266 // result. Nothing complicated, but I think my brain was fried yesterday.
267 // Funny how that happens some times.
269 // This gets properties in a nested parenthesisized list. For example,
270 // this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
271 // This returns an array called $props with all paired up properties.
272 // It ignores the "attachment" for now, maybe that should change later
273 // down the road. In this case, what is returned is:
274 // $props[0]["name"] = "filename";
275 // $props[0]["value"] = "luke.tar.gz";
276 function mime_get_props ($props, $structure) {
278 while (strlen($structure) > 0) {
279 $structure = trim($structure);
280 $char = substr($structure, 0, 1);
284 $char = substr($structure, $pos, 1);
285 while ($char != "\"" && $pos < strlen($structure)) {
288 $char = substr($structure, $pos, 1);
290 $structure = trim(substr($structure, strlen($tmp) +
2));
291 $char = substr($structure, 0, 1);
295 $char = substr($structure, $pos, 1);
296 while ($char != "\"" && $pos < strlen($structure)) {
299 $char = substr($structure, $pos, 1);
301 $structure = trim(substr($structure, strlen($tmp) +
2));
304 $props[$k]["name"] = $tmp;
305 $props[$k]["value"] = $value;
306 } else if ($char == "(") {
307 $end = mime_match_parenthesis (0, $structure);
308 $sub = substr($structure, 1, $end-1);
309 $props = mime_get_props($props, $sub);
310 $structure = substr($structure, strlen($sub) +
2);
313 } else if ($char == "(") {
314 $end = mime_match_parenthesis (0, $structure);
315 $sub = substr($structure, 1, $end-1);
316 $props = mime_get_props($props, $sub);
317 $structure = substr($structure, strlen($sub) +
2);
325 // Matches parenthesis. It will return the position of the matching
326 // parenthesis in $structure. For instance, if $structure was:
327 // ("text" "plain" ("val1name", "1") nil ... )
329 // then this would return 42 to match up those two.
330 function mime_match_parenthesis ($pos, $structure) {
331 $char = substr($structure, $pos, 1);
333 // ignore all extra characters
334 while ($pos < strlen($structure)) {
336 $char = substr($structure, $pos, 1);
339 } else if ($char == "(") {
340 $pos = mime_match_parenthesis ($pos, $structure);
345 function mime_fetch_body ($imap_stream, $id, $ent_id) {
346 // do a bit of error correction. If we couldn't find the entity id, just guess
347 // that it is the first one. That is usually the case anyway.
348 if (!$ent_id) $ent_id = 1;
350 fputs ($imap_stream, "a001 FETCH $id BODY[$ent_id]\r\n");
351 $topline = fgets ($imap_stream, 1024);
352 $size = substr ($topline, strpos($topline, "{")+
1);
353 $size = substr ($size, 0, strpos($size, "}"));
354 $read = fread ($imap_stream, $size);
358 /* -[ END MIME DECODING ]----------------------------------------------------------- */
362 /** This is the first function called. It decides if this is a multipart
363 message or if it should be handled as a single entity
365 function decodeMime ($imap_stream, $body, $header) {
366 global $username, $key, $imapServerAddress, $imapPort;
367 return mime_structure ($imap_stream, $header);
370 // This is here for debugging purposese. It will print out a list
371 // of all the entity IDs that are in the $message object.
372 function listEntities ($message) {
374 if ($message->header
->entity_id
)
375 echo "<tt>" . $message->header
->entity_id
. " : " . $message->header
->type0
. "/" . $message->header
->type1
. "<br>";
376 for ($i = 0; $message->entities
[$i]; $i++
) {
377 $msg = listEntities($message->entities
[$i], $ent_id);
384 // returns a $message object for a particular entity id
385 function getEntity ($message, $ent_id) {
387 if ($message->header
->entity_id
== $ent_id && strlen($ent_id) == strlen($message->header
->entity_id
)) {
390 for ($i = 0; $message->entities
[$i]; $i++
) {
391 $msg = getEntity ($message->entities
[$i], $ent_id);
399 // figures out what entity to display and returns the $message object
401 function findDisplayEntity ($message) {
403 if ($message->header
->type0
== "text") {
404 if ($message->header
->type1
== "plain" ||
405 $message->header
->type1
== "html") {
406 return $message->header
->entity_id
;
409 for ($i=0; $message->entities
[$i]; $i++
) {
410 return findDisplayEntity($message->entities
[$i]);
416 /** This returns a parsed string called $body. That string can then
417 be displayed as the actual message in the HTML. It contains
418 everything needed, including HTML Tags, Attachments at the
421 function formatBody($imap_stream, $message, $color, $wrap_at) {
422 // this if statement checks for the entity to show as the
423 // primary message. To add more of them, just put them in the
424 // order that is their priority.
425 global $username, $key, $imapServerAddress, $imapPort;
427 $id = $message->header
->id
;
428 $urlmailbox = urlencode($message->header
->mailbox
);
430 // Get the right entity and redefine message to be this entity
431 $ent_num = findDisplayEntity ($message);
432 $body_message = getEntity($message, $ent_num);
434 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
435 $body = decodeBody($body, $body_message->header
->encoding
);
437 // If there are other types that shouldn't be formatted, add
439 if ($message->header
->type1
!= "html") {
440 $body = translateText($body, $wrap_at, $body_message->header
->charset
);
443 $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>";
445 /** Display the ATTACHMENTS: message if there's more than one part **/
446 if ($message->entities
) {
447 $body .= "<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=4 BORDER=0><TR><TD BGCOLOR=\"$color[0]\">";
448 $body .= "<TT><B>ATTACHMENTS:</B></TT>";
449 $body .= "</TD></TR><TR><TD BGCOLOR=\"$color[0]\">";
452 /** make this recurisve at some point **/
453 $body .= formatAttachments ($message, $ent_num, $message->header
->mailbox
, $id);
454 $body .= "</TD></TR></TABLE>";
459 // A recursive function that returns a list of attachments with links
460 // to where to download these attachments
461 function formatAttachments ($message, $ent_id, $mailbox, $id) {
463 if (!$message->entities
) {
464 $type0 = strtolower($message->header
->type0
);
465 $type1 = strtolower($message->header
->type1
);
467 if ($message->header
->entity_id
!= $ent_id) {
468 $filename = $message->header
->filename
;
469 if (trim($filename) == "") {
470 $display_filename = "untitled-".$message->header
->entity_id
;
472 $display_filename = $filename;
475 $urlMailbox = urlencode($mailbox);
476 $ent = urlencode($message->header
->entity_id
);
477 $body .= "<TT> <A HREF=\"../src/download.php?passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent\">" . $display_filename . "</A> (TYPE: $type0/$type1)";
478 if ($message->header
->description
)
479 $body .= " <b>" . htmlspecialchars($message->header
->description
)."</b>";
480 if ($message->header
->type0
== "image" &&
481 ($message->header
->type1
== "jpg" ||
482 $message->header
->type1
== "jpeg" ||
483 $message->header
->type1
== "gif" ||
484 $message->header
->type1
== "png"))
485 $body .= " (<a href=\"../src/download.php?passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent&view=true\">"._("view")."</a>)\n";
486 $body .= "</TT><BR>";
491 for ($i = 0; $i < count($message->entities
); $i++
) {
492 $body .= formatAttachments ($message->entities
[$i], $ent_id, $mailbox, $id);
500 /** this function decodes the body depending on the encoding type. **/
501 function decodeBody($body, $encoding) {
502 $encoding = strtolower($encoding);
504 if ($encoding == "quoted-printable") {
505 $body = quoted_printable_decode($body);
507 while (ereg("=\n", $body))
508 $body = ereg_replace ("=\n", "", $body);
509 } else if ($encoding == "base64") {
510 $body = base64_decode($body);
513 // All other encodings are returned raw.
518 // This functions decode strings that is encoded according to
519 // RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
520 function decodeHeader ($string) {
521 if (eregi('=\?([^?]+)\?(q|b)\?([^?]+)\?=',
523 if (ucfirst($res[2]) == "B") {
524 $replace = base64_decode($res[3]);
526 $replace = ereg_replace("_", " ", $res[3]);
527 $replace = quoted_printable_decode($replace);
530 $replace = charset_decode ($res[1], $replace);
532 $string = eregi_replace
533 ('=\?([^?]+)\?(q|b)\?([^?]+)\?=',
535 // In case there should be more encoding in the string: recurse
536 return (decodeHeader($string));
541 // Encode a string according to RFC 1522 for use in headers if it
542 // contains 8-bit characters or anything that looks like it should
544 function encodeHeader ($string) {
545 global $default_charset;
547 // Encode only if the string contains 8-bit characters or =?
548 if (ereg("([\200-\377])|=\\?", $string)) {
549 $newstring = "=?$default_charset?Q?";
551 // First the special characters
552 $string = str_replace("=", "=3D", $string);
553 $string = str_replace("?", "=3F", $string);
554 $string = str_replace("_", "=5F", $string);
555 $string = str_replace(" ", "_", $string);
558 while (ereg("([\200-\377])", $string, $regs)) {
560 $insert = "=" . strtoupper(bin2hex($replace));
561 $string = str_replace($replace, $insert, $string);
564 $newstring = "=?$default_charset?Q?".$string."?=";