* Noticed that mime_match_parentheses() didn't work when a string had
[squirrelmail.git] / functions / mime.php
1 <?php
2 /** mime.php
3 **
4 ** This contains the functions necessary to detect and decode MIME
5 ** messages.
6 **
7 ** $Id$
8 **/
9
10 $debug_mime = false;
11 $mime_php = true;
12
13 if (!isset($i18n_php))
14 include "../functions/i18n.php";
15 if (!isset($imap_php))
16 include "../functions/imap.php";
17 if (!isset($config_php))
18 include "../config/config.php";
19
20
21 /** Setting up the objects that have the structure for the message **/
22
23 class msg_header {
24 /** msg_header contains generic variables for values that **/
25 /** could be in a header. **/
26
27 var $type0 = '', $type1 = '', $boundary = '', $charset = '';
28 var $encoding = '', $size = 0, $to = array(), $from = '', $date = '';
29 var $cc = array(), $bcc = array(), $reply_to = '', $subject = '';
30 var $id = 0, $mailbox = '', $description = '', $filename = '';
31 var $entity_id = 0, $message_id = 0;
32 }
33
34 class message {
35 /** message is the object that contains messages. It is a recursive
36 object in that through the $entities variable, it can contain
37 more objects of type message. See documentation in mime.txt for
38 a better description of how this works.
39 **/
40 var $header = '';
41 var $entities = array();
42
43 function addEntity ($msg) {
44 $this->entities[] = $msg;
45 }
46 }
47
48
49
50 /* --------------------------------------------------------------------------------- */
51 /* MIME DECODING */
52 /* --------------------------------------------------------------------------------- */
53
54 // This function gets the structure of a message and stores it in the "message" class.
55 // It will return this object for use with all relevant header information and
56 // fully parsed into the standard "message" object format.
57 function mime_structure ($imap_stream, $header) {
58 global $debug_mime;
59 sqimap_messages_flag ($imap_stream, $header->id, $header->id, "Seen");
60
61 $id = $header->id;
62 fputs ($imap_stream, "a001 FETCH $id BODYSTRUCTURE\r\n");
63 //
64 // This should use sqimap_read_data instead of reading it itself
65 //
66 $read = fgets ($imap_stream, 10000);
67 $response = substr($read, 0, 4);
68 $bodystructure = "";
69 while ($response != "a001") {
70 $bodystructure .= $read;
71 $read = fgets ($imap_stream, 10000);
72 $response = substr($read, 0, 4);
73 }
74 $read = $bodystructure;
75
76 if ($debug_mime) echo "<tt>$read</tt><br><br>\n";
77 // isolate the body structure and remove beginning and end parenthesis
78 $read = trim(substr ($read, strpos(strtolower($read), "bodystructure") + 13));
79 $read = trim(substr ($read, 0, -1));
80 $end = mime_match_parenthesis(0, $read);
81 while ($end == strlen($read)-1) {
82 $read = trim(substr ($read, 0, -1));
83 $read = trim(substr ($read, 1));
84 $end = mime_match_parenthesis(0, $read);
85 }
86
87 if ($debug_mime) echo "<tt>$read</tt><br><br>\n";
88
89 $msg = mime_parse_structure ($read, 0);
90 $msg->header = $header;
91 return $msg;
92 }
93
94 // this starts the parsing of a particular structure. It is called recursively,
95 // so it can be passed different structures. It returns an object of type
96 // $message.
97 // First, it checks to see if it is a multipart message. If it is, then it
98 // handles that as it sees is necessary. If it is just a regular entity,
99 // then it parses it and adds the necessary header information (by calling out
100 // to mime_get_elements()
101 function mime_parse_structure ($structure, $ent_id) {
102 global $debug_mime;
103 if ($debug_mime) echo "<font color=008800><tt>START: mime_parse_structure()</tt></font><br>\n";
104 $msg = new message();
105 if (substr($structure, 0, 1) == "(") {
106 $ent_id = mime_new_element_level($ent_id);
107 $start = $end = -1;
108 if ($debug_mime) echo "<br><font color=0000aa><tt>$structure</tt></font><br>";
109 do {
110 if ($debug_mime) echo "<font color=008800><tt>Found entity...</tt></font><br>";
111 $start = $end+1;
112 $end = mime_match_parenthesis ($start, $structure);
113
114 $element = substr($structure, $start+1, ($end - $start)-1);
115 $ent_id = mime_increment_id ($ent_id);
116 $newmsg = mime_parse_structure ($element, $ent_id);
117 $msg->addEntity ($newmsg);
118 } while (substr($structure, $end+1, 1) == "(");
119 } else {
120 // parse the elements
121 if ($debug_mime) echo "<br><font color=0000aa><tt>$structure</tt></font><br>";
122 $msg = mime_get_element ($structure, $msg, $ent_id);
123 if ($debug_mime) echo "<br>";
124 }
125 return $msg;
126 if ($debug_mime) echo "<font color=008800><tt>&nbsp;&nbsp;END: mime_parse_structure()</tt></font><br>";
127 }
128
129 // Increments the element ID. An element id can look like any of
130 // the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
131 // the last number of the element id, changing 1.2 to 1.3.
132 function mime_increment_id ($id) {
133 global $debug_mime;
134 if (strpos($id, ".")) {
135 $first = substr($id, 0, strrpos($id, "."));
136 $last = substr($id, strrpos($id, ".")+1);
137 $last++;
138 $new = $first . "." .$last;
139 } else {
140 $new = $id + 1;
141 }
142 if ($debug_mime) echo "<b>INCREMENT: $new</b><br>";
143 return $new;
144 }
145
146 // See comment for mime_increment_id().
147 // This adds another level on to the entity_id changing 1.3 to 1.3.0
148 // NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
149 // before it can be used. I left it this way so as not to have
150 // to make a special case if it is the first entity_id. It
151 // always increments it, and that works fine.
152 function mime_new_element_level ($id) {
153 if (!$id) $id = 0;
154 else $id = $id . ".0";
155
156 return $id;
157 }
158
159 function mime_get_element (&$structure, $msg, $ent_id) {
160 global $debug_mime;
161 $elem_num = 1;
162 $msg->header = new msg_header();
163 $msg->header->entity_id = $ent_id;
164
165 while (strlen($structure) > 0) {
166 $structure = trim($structure);
167 $char = substr($structure, 0, 1);
168
169 if (strtolower(substr($structure, 0, 3)) == "nil") {
170 $text = "";
171 $structure = substr($structure, 3);
172 } else if ($char == "\"") {
173 // loop through until we find the matching quote, and return that as a string
174 $pos = 1;
175 $char = substr($structure, $pos, 1);
176 $text = "";
177 while ($char != "\"" && $pos < strlen($structure)) {
178 $text .= $char;
179 $pos++;
180 $char = substr($structure, $pos, 1);
181 }
182 $structure = substr($structure, strlen($text) + 2);
183 } else if ($char == "(") {
184 // comment me
185 $end = mime_match_parenthesis (0, $structure);
186 $sub = substr($structure, 1, $end-1);
187 if (! isset($properties))
188 $properties = array();
189 $properties = mime_get_props($properties, $sub);
190 $structure = substr($structure, strlen($sub) + 2);
191 } else {
192 // loop through until we find a space or an end parenthesis
193 $pos = 0;
194 $char = substr($structure, $pos, 1);
195 $text = "";
196 while ($char != " " && $char != ")" && $pos < strlen($structure)) {
197 $text .= $char;
198 $pos++;
199 $char = substr($structure, $pos, 1);
200 }
201 $structure = substr($structure, strlen($text));
202 }
203 if ($debug_mime) echo "<tt>$elem_num : $text</tt><br>";
204
205 // This is where all the text parts get put into the header
206 switch ($elem_num) {
207 case 1:
208 $msg->header->type0 = strtolower($text);
209 if ($debug_mime) echo "<tt>type0 = ".strtolower($text)."</tt><br>";
210 break;
211 case 2:
212 $msg->header->type1 = strtolower($text);
213 if ($debug_mime) echo "<tt>type1 = ".strtolower($text)."</tt><br>";
214 break;
215 case 5:
216 $msg->header->description = $text;
217 if ($debug_mime) echo "<tt>description = $text</tt><br>";
218 break;
219 case 6:
220 $msg->header->encoding = strtolower($text);
221 if ($debug_mime) echo "<tt>encoding = ".strtolower($text)."</tt><br>";
222 break;
223 case 7:
224 $msg->header->size = $text;
225 if ($debug_mime) echo "<tt>size = $text</tt><br>";
226 break;
227 default:
228 if ($msg->header->type0 == "text" && $elem_num == 8) {
229 // This is a plain text message, so lets get the number of lines
230 // that it contains.
231 $msg->header->num_lines = $text;
232 if ($debug_mime) echo "<tt>num_lines = $text</tt><br>";
233
234 } else if ($msg->header->type0 == "message" && $msg->header->type1 == "rfc822" && $elem_num == 8) {
235 // This is an encapsulated message, so lets start all over again and
236 // parse this message adding it on to the existing one.
237 $structure = trim($structure);
238 if (substr($structure, 0, 1) == "(") {
239 $e = mime_match_parenthesis (0, $structure);
240 $structure = substr($structure, 0, $e);
241 $structure = substr($structure, 1);
242 $m = mime_parse_structure($structure, $msg->header->entity_id);
243
244 // the following conditional is there to correct a bug that wasn't
245 // incrementing the entity IDs correctly because of the special case
246 // that message/rfc822 is. This fixes it fine.
247 if (substr($structure, 1, 1) != "(")
248 $m->header->entity_id = mime_increment_id(mime_new_element_level($ent_id));
249
250 // Now we'll go through and reformat the results.
251 if ($m->entities) {
252 for ($i=0; $i < count($m->entities); $i++) {
253 $msg->addEntity($m->entities[$i]);
254 }
255 } else {
256 $msg->addEntity($m);
257 }
258 $structure = "";
259 }
260 }
261 break;
262 }
263 $elem_num++;
264 $text = "";
265 }
266 // loop through the additional properties and put those in the various headers
267 if ($msg->header->type0 != "message") {
268 for ($i=0; $i < count($properties); $i++) {
269 $msg->header->{$properties[$i]["name"]} = $properties[$i]["value"];
270 if ($debug_mime) echo "<tt>".$properties[$i]["name"]." = " . $properties[$i]["value"] . "</tt><br>";
271 }
272 }
273
274 return $msg;
275 }
276
277 // I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
278 // figure out how to do this part, so I decided to go to bed. I woke up
279 // in the morning and had a flash of insight. I went to the white-board
280 // and scribbled it out, then spent a bit programming it, and this is the
281 // result. Nothing complicated, but I think my brain was fried yesterday.
282 // Funny how that happens some times.
283 //
284 // This gets properties in a nested parenthesisized list. For example,
285 // this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
286 // This returns an array called $props with all paired up properties.
287 // It ignores the "attachment" for now, maybe that should change later
288 // down the road. In this case, what is returned is:
289 // $props[0]["name"] = "filename";
290 // $props[0]["value"] = "luke.tar.gz";
291 function mime_get_props ($props, $structure) {
292 global $debug_mime;
293 while (strlen($structure) > 0) {
294 $structure = trim($structure);
295 $char = substr($structure, 0, 1);
296
297 if ($char == "\"") {
298 $pos = 1;
299 $char = substr($structure, $pos, 1);
300 $tmp = "";
301 while ($char != "\"" && $pos < strlen($structure)) {
302 $tmp .= $char;
303 $pos++;
304 $char = substr($structure, $pos, 1);
305 }
306 $structure = trim(substr($structure, strlen($tmp) + 2));
307 $char = substr($structure, 0, 1);
308
309 if ($char == "\"") {
310 $pos = 1;
311 $char = substr($structure, $pos, 1);
312 $value = "";
313 while ($char != "\"" && $pos < strlen($structure)) {
314 $value .= $char;
315 $pos++;
316 $char = substr($structure, $pos, 1);
317 }
318 $structure = trim(substr($structure, strlen($tmp) + 2));
319
320 $k = count($props);
321 $props[$k]["name"] = strtolower($tmp);
322 $props[$k]["value"] = $value;
323 } else if ($char == "(") {
324 $end = mime_match_parenthesis (0, $structure);
325 $sub = substr($structure, 1, $end-1);
326 if (! isset($props))
327 $props = array();
328 $props = mime_get_props($props, $sub);
329 $structure = substr($structure, strlen($sub) + 2);
330 }
331 return $props;
332 } else if ($char == "(") {
333 $end = mime_match_parenthesis (0, $structure);
334 $sub = substr($structure, 1, $end-1);
335 $props = mime_get_props($props, $sub);
336 $structure = substr($structure, strlen($sub) + 2);
337 return $props;
338 } else {
339 return $props;
340 }
341 }
342 }
343
344 // Matches parenthesis. It will return the position of the matching
345 // parenthesis in $structure. For instance, if $structure was:
346 // ("text" "plain" ("val1name", "1") nil ... )
347 // x x
348 // then this would return 42 to match up those two.
349 function mime_match_parenthesis ($pos, $structure) {
350 $char = substr($structure, $pos, 1);
351
352 // ignore all extra characters
353 // If inside of a string, skip string -- Boundary IDs and other
354 // things can have ) in them.
355 while ($pos < strlen($structure)) {
356 $pos++;
357 $char = substr($structure, $pos, 1);
358 if ($char == ")") {
359 return $pos;
360 } else if ($char == '"') {
361 $pos ++;
362 while (substr($structure, $pos, 1) != '"' &&
363 $pos < strlen($structure)) {
364 if (substr($structure, $pos, 2) == '\\"')
365 $pos ++;
366 elseif (substr($structure, $pos, 2) == '\\\\')
367 $pos ++;
368 $pos ++;
369 }
370 } else if ($char == "(") {
371 $pos = mime_match_parenthesis ($pos, $structure);
372 }
373 }
374 echo "Error decoding mime structure. Report this as a bug!<br>\n";
375 return $pos;
376 }
377
378 function mime_fetch_body ($imap_stream, $id, $ent_id) {
379 // do a bit of error correction. If we couldn't find the entity id, just guess
380 // that it is the first one. That is usually the case anyway.
381 if (!$ent_id) $ent_id = 1;
382
383 fputs ($imap_stream, "a010 FETCH $id BODY[$ent_id]\r\n");
384 $data = sqimap_read_data ($imap_stream, 'a010', true, $response, $message);
385 $topline = array_shift($data);
386 while (! ereg('\\* [0-9]+ FETCH ', $topline) && data)
387 $topline = array_shift($data);
388 $wholemessage = implode('', $data);
389
390 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
391 return substr($wholemessage, 0, $regs[1]);
392 }
393 else if (ereg('"([^"]*)"', $topline, $regs)) {
394 return $regs[1];
395 }
396
397 $str = "Body retrival error. Please report this bug!\n";
398 $str .= "Response: $response\n";
399 $str .= "Message: $message\n";
400 $str .= "FETCH line: $topline";
401 $str .= "---------------\n$wholemessage";
402 foreach ($data as $d)
403 {
404 $str .= htmlspecialchars($d) . "\n";
405 }
406 return $str;
407
408 return "Body retrival error, please report this bug!\n\nTop line is \"$topline\"\n";
409 }
410
411 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
412 // do a bit of error correction. If we couldn't find the entity id, just guess
413 // that it is the first one. That is usually the case anyway.
414 if (!$ent_id) $ent_id = 1;
415
416 fputs ($imap_stream, "a001 FETCH $id BODY[$ent_id]\r\n");
417 $cnt = 0;
418 $continue = true;
419 $read = fgets ($imap_stream,4096);
420 while (!ereg("^a001 (OK|BAD|NO)(.*)$", $read, $regs)) {
421 if (trim($read) == ")==") {
422 $read1 = $read;
423 $read = fgets ($imap_stream,4096);
424 if (ereg("^a001 (OK|BAD|NO)(.*)$", $read, $regs)) {
425 return;
426 } else {
427 echo decodeBody($read1, $encoding);
428 echo decodeBody($read, $encoding);
429 }
430 } else if ($cnt) {
431 echo decodeBody($read, $encoding);
432 }
433 $read = fgets ($imap_stream,4096);
434 $cnt++;
435 }
436 }
437
438 /* -[ END MIME DECODING ]----------------------------------------------------------- */
439
440
441
442 /** This is the first function called. It decides if this is a multipart
443 message or if it should be handled as a single entity
444 **/
445 function decodeMime ($imap_stream, &$header) {
446 global $username, $key, $imapServerAddress, $imapPort;
447 return mime_structure ($imap_stream, $header);
448 }
449
450 // This is here for debugging purposese. It will print out a list
451 // of all the entity IDs that are in the $message object.
452 function listEntities ($message) {
453 if ($message) {
454 if ($message->header->entity_id)
455 echo "<tt>" . $message->header->entity_id . " : " . $message->header->type0 . "/" . $message->header->type1 . "<br>";
456 for ($i = 0; $message->entities[$i]; $i++) {
457 $msg = listEntities($message->entities[$i], $ent_id);
458 if ($msg)
459 return $msg;
460 }
461 }
462 }
463
464 // returns a $message object for a particular entity id
465 function getEntity ($message, $ent_id) {
466 if ($message) {
467 if ($message->header->entity_id == $ent_id && strlen($ent_id) == strlen($message->header->entity_id)) {
468 return $message;
469 } else {
470 for ($i = 0; isset($message->entities[$i]); $i++) {
471 $msg = getEntity ($message->entities[$i], $ent_id);
472 if ($msg)
473 return $msg;
474 }
475 }
476 }
477 }
478
479 // figures out what entity to display and returns the $message object
480 // for that entity.
481 function findDisplayEntity ($message) {
482 if ($message) {
483 if ($message->header->type0 == "text") {
484 if ($message->header->type1 == "plain" ||
485 $message->header->type1 == "html") {
486 if (isset($message->header->entity_id))
487 return $message->header->entity_id;
488 return 0;
489 }
490 } else {
491 for ($i=0; $message->entities[$i]; $i++) {
492 return findDisplayEntity($message->entities[$i]);
493 }
494 }
495 }
496 }
497
498 /** This returns a parsed string called $body. That string can then
499 be displayed as the actual message in the HTML. It contains
500 everything needed, including HTML Tags, Attachments at the
501 bottom, etc.
502 **/
503 function formatBody($imap_stream, $message, $color, $wrap_at) {
504 // this if statement checks for the entity to show as the
505 // primary message. To add more of them, just put them in the
506 // order that is their priority.
507 global $startMessage, $username, $key, $imapServerAddress, $imapPort;
508
509 $id = $message->header->id;
510 $urlmailbox = urlencode($message->header->mailbox);
511
512 // Get the right entity and redefine message to be this entity
513 $ent_num = findDisplayEntity ($message);
514 $body_message = getEntity($message, $ent_num);
515 if (($body_message->header->type0 == "text") ||
516 ($body_message->header->type0 == "rfc822")) {
517
518 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
519 $body = decodeBody($body, $body_message->header->encoding);
520
521 // If there are other types that shouldn't be formatted, add
522 // them here
523 if ($body_message->header->type1 != "html") {
524 translateText($body, $wrap_at, $body_message->header->charset);
525 }
526
527 $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>";
528
529 /** Display the ATTACHMENTS: message if there's more than one part **/
530 $body .= "</TD></TR></TABLE>";
531 if (isset($message->entities[0])) {
532 $body .= formatAttachments ($message, $ent_num, $message->header->mailbox, $id);
533 }
534 } else {
535 $body .= formatAttachments ($message, -1, $message->header->mailbox, $id);
536 }
537 return $body;
538 }
539
540 // A recursive function that returns a list of attachments with links
541 // to where to download these attachments
542 function formatAttachments ($message, $ent_id, $mailbox, $id) {
543 global $where, $what;
544 global $startMessage, $color;
545 static $ShownHTML = 0;
546
547 $body = "";
548 if ($ShownHTML == 0)
549 {
550 $ShownHTML = 1;
551
552 $body .= "<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n";
553 $body .= "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n";
554 $body .= _("Attachments") . ':';
555 $body .= "</B></TH></TR><TR><TD>\n";
556
557 $body .= "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n";
558
559 $body .= formatAttachments ($message, $ent_id, $mailbox, $id);
560
561 $body .= "</TABLE></TD></TR></TABLE>";
562
563 return $body;
564 }
565
566 if ($message) {
567 if (!$message->entities) {
568 $type0 = strtolower($message->header->type0);
569 $type1 = strtolower($message->header->type1);
570
571 if ($message->header->entity_id != $ent_id) {
572 $filename = decodeHeader($message->header->filename);
573 if (trim($filename) == "") {
574 $display_filename = "untitled-".$message->header->entity_id;
575 } else {
576 $display_filename = $filename;
577 }
578
579 $urlMailbox = urlencode($mailbox);
580 $ent = urlencode($message->header->entity_id);
581
582 $DefaultLink =
583 "../src/download.php?startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
584 if ($where && $what)
585 $DefaultLink .= '&where=' . urlencode($where) . '&what=' . urlencode($what);
586 $Links['download link']['text'] = _("download");
587 $Links['download link']['href'] =
588 "../src/download.php?absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent";
589 $ImageURL = '';
590
591 $HookResults = do_hook("attachment $type0/$type1", $Links,
592 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
593 $display_filename, $where, $what);
594
595 $Links = $HookResults[1];
596 $DefaultLink = $HookResults[6];
597
598 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>';
599 $body .= "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>";
600 $body .= '<TD><SMALL><b>' . show_readable_size($message->header->size) .
601 '</b>&nbsp;&nbsp;</small></TD>';
602 $body .= "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>";
603 $body .= '<TD><SMALL>';
604 if ($message->header->description)
605 $body .= '<b>' . htmlspecialchars($message->header->description) . '</b>';
606 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
607
608
609 $SkipSpaces = 1;
610 foreach ($Links as $Val)
611 {
612 if ($SkipSpaces)
613 {
614 $SkipSpaces = 0;
615 }
616 else
617 {
618 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
619 }
620 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
621 }
622
623 unset($Links);
624
625 $body .= "</SMALL></TD></TR>\n";
626 }
627 return $body;
628 } else {
629 for ($i = 0; $i < count($message->entities); $i++) {
630 $body .= formatAttachments ($message->entities[$i], $ent_id, $mailbox, $id);
631 }
632 return $body;
633 }
634 }
635 }
636
637
638 /** this function decodes the body depending on the encoding type. **/
639 function decodeBody($body, $encoding) {
640 $body = str_replace("\r\n", "\n", $body);
641 $encoding = strtolower($encoding);
642
643 if ($encoding == "quoted-printable") {
644 $body = quoted_printable_decode($body);
645
646 while (ereg("=\n", $body))
647 $body = ereg_replace ("=\n", "", $body);
648 } else if ($encoding == "base64") {
649 $body = base64_decode($body);
650 }
651
652 // All other encodings are returned raw.
653 return $body;
654 }
655
656
657 // This functions decode strings that is encoded according to
658 // RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
659 function decodeHeader ($string) {
660 if (eregi('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
661 $string, $res)) {
662 if (ucfirst($res[2]) == "B") {
663 $replace = base64_decode($res[3]);
664 } else {
665 $replace = ereg_replace("_", " ", $res[3]);
666 // Convert lowercase Quoted Printable to uppercase for
667 // quoted_printable_decode to understand it.
668 while (ereg("(=([0-9][abcdef])|([abcdef][0-9])|([abcdef][abcdef]))", $replace, $res)) {
669 $replace = str_replace($res[1], strtoupper($res[1]), $replace);
670 }
671 $replace = quoted_printable_decode($replace);
672 }
673
674 $replace = charset_decode ($res[1], $replace);
675
676 $string = eregi_replace
677 ('=\\?([^?]+)\\?(q|b)\\?([^?]+)\\?=',
678 $replace, $string);
679 // In case there should be more encoding in the string: recurse
680 return (decodeHeader($string));
681 } else
682 return ($string);
683 }
684
685 // Encode a string according to RFC 1522 for use in headers if it
686 // contains 8-bit characters or anything that looks like it should
687 // be encoded.
688 function encodeHeader ($string) {
689 global $default_charset;
690
691 // Encode only if the string contains 8-bit characters or =?
692 if (ereg("([\200-\377]|=\\?)", $string)) {
693 $newstring = "=?$default_charset?Q?";
694
695 // First the special characters
696 $string = str_replace("=", "=3D", $string);
697 $string = str_replace("?", "=3F", $string);
698 $string = str_replace("_", "=5F", $string);
699 $string = str_replace(" ", "_", $string);
700
701 for ( $ch = 127 ; $ch <= 255 ; $ch++ ) {
702 $replace = chr($ch);
703 $insert = sprintf("=%02X", $ch);
704 $string = str_replace($replace, $insert, $string);
705 $ch++;
706 }
707
708 $newstring = "=?$default_charset?Q?".$string."?=";
709
710 return $newstring;
711 }
712
713 return $string;
714 }
715
716 ?>