No idea why that line fall off
[squirrelmail.git] / functions / mime.php
CommitLineData
59177427 1<?php
2ba13803 2
35586184 3/**
4 * mime.php
5 *
15e6162e 6 * Copyright (c) 1999-2002 The SquirrelMail Project Team
35586184 7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This contains the functions necessary to detect and decode MIME
10 * messages.
11 *
12 * $Id$
13 */
b74ba498 14
35586184 15require_once('../functions/imap.php');
16require_once('../functions/attachment_common.php');
8beafbbc 17
35586184 18/** Setting up the objects that have the structure for the message **/
19class msg_header {
20 /** msg_header contains generic variables for values that **/
21 /** could be in a header. **/
b74ba498 22
88cb1b4d 23 var $type0 = '', $type1 = '', $boundary = '', $charset = '',
24 $encoding = '', $size = 0, $to = array(), $from = '', $date = '',
25 $cc = array(), $bcc = array(), $reply_to = '', $subject = '',
26 $id = 0, $mailbox = '', $description = '', $filename = '',
c9d78ab4 27 $entity_id = 0, $message_id = 0, $name = '', $priority = 3, $type = '';
35586184 28}
b74ba498 29
451f74a2 30class message {
31 /** message is the object that contains messages. It is a recursive
32 object in that through the $entities variable, it can contain
33 more objects of type message. See documentation in mime.txt for
34 a better description of how this works.
35 **/
77b88425 36 var $header = '', $entities = array();
37
451f74a2 38 function addEntity ($msg) {
39 $this->entities[] = $msg;
40 }
41}
8beafbbc 42
451f74a2 43/* --------------------------------------------------------------------------------- */
44/* MIME DECODING */
45/* --------------------------------------------------------------------------------- */
b74ba498 46
451f74a2 47/* This function gets the structure of a message and stores it in the "message" class.
48 * It will return this object for use with all relevant header information and
49 * fully parsed into the standard "message" object format.
50 */
51function mime_structure ($imap_stream, $header) {
52
451f74a2 53 $ssid = sqimap_session_id();
54 $lsid = strlen( $ssid );
55 $id = $header->id;
56 fputs ($imap_stream, "$ssid FETCH $id BODYSTRUCTURE\r\n");
57 //
58 // This should use sqimap_read_data instead of reading it itself
59 //
77b88425 60 $read = fgets ($imap_stream, 9216);
451f74a2 61 $bodystructure = '';
62 while ( substr($read, 0, $lsid) <> $ssid &&
63 !feof( $imap_stream ) ) {
64 $bodystructure .= $read;
77b88425 65 $read = fgets ($imap_stream, 9216);
451f74a2 66 }
67 $read = $bodystructure;
77b88425 68
451f74a2 69 // isolate the body structure and remove beginning and end parenthesis
70 $read = trim(substr ($read, strpos(strtolower($read), 'bodystructure') + 13));
c9d78ab4 71
451f74a2 72 $read = trim(substr ($read, 0, -1));
73 $end = mime_match_parenthesis(0, $read);
74 while ($end == strlen($read)-1) {
75 $read = trim(substr ($read, 0, -1));
76 $read = trim(substr ($read, 1));
77 $end = mime_match_parenthesis(0, $read);
78 }
77b88425 79
451f74a2 80 $msg = mime_parse_structure ($read, 0);
81 $msg->header = $header;
77b88425 82
451f74a2 83 return( $msg );
84}
b74ba498 85
451f74a2 86/* this starts the parsing of a particular structure. It is called recursively,
87 * so it can be passed different structures. It returns an object of type
88 * $message.
89 * First, it checks to see if it is a multipart message. If it is, then it
90 * handles that as it sees is necessary. If it is just a regular entity,
91 * then it parses it and adds the necessary header information (by calling out
92 * to mime_get_elements()
93 */
94function mime_parse_structure ($structure, $ent_id) {
164800ad 95 global $mailbox;
c9d78ab4 96 $properties = array();
451f74a2 97 $msg = new message();
98 if ($structure{0} == '(') {
c9d78ab4 99 $old_ent_id = $ent_id;
451f74a2 100 $ent_id = mime_new_element_level($ent_id);
101 $start = $end = -1;
102 do {
103 $start = $end+1;
104 $end = mime_match_parenthesis ($start, $structure);
164800ad 105
106 /* check if we are dealing with a new entity-level */
107 $i = strrpos($ent_id,'.');
108 if ($i>0) {
109 $ent = substr($ent_id, $i+1);
110 } else {
111 $ent = '';
112 }
c9d78ab4 113 /* add "forgotten" parent entities (alternative and relative) */
164800ad 114 if ($ent == '0') {
115 /* new entity levels have information about the type (type1) and
116 * the properties. This information is situated at the end of the
117 * structure string like for example (example between the brackets)
118 * [ "RELATED" ("BOUNDARY" "myboundary" "TYPE" "plain/html") ]
119 */
120
121 /* get the involved properties for parsing to mime_get_properties */
122 $startprop = strrpos($structure,'(');
123 $properties_str = substr($structure,$startprop);
124 $endprop = mime_match_parenthesis ($startprop, $structure);
125 $propstr = substr($structure, $startprop + 1, ($endprop - $startprop)-1);
126 /* cut off the used properties */
127 if ($startprop) {
128 $structure_end = substr($structure, $endprop+2);
129 $structure = trim(substr($structure,0,$startprop));
130 }
131
132 /* get type1 */
133 $pos = strrpos($structure,' ');
134 $type1 = strtolower(substr($structure, $pos+2, (count($structure)-2)));
135
136 /* cut off type1 */
137 if ($pos && $startprop) {
138 $structure = trim(substr($structure, 0, $pos));
139 }
140
141 /* process the found information */
142 $properties = mime_get_props($properties, $properties_str);
c9d78ab4 143 if (count($properties)>0) {
144 $msg->header->entity_id = $old_ent_id;
145 $msg->header->type0 = 'multipart';
146 $msg->header->type1 = $type1;
164800ad 147 for ($i=0; $i < count($properties); $i++) {
148 $msg->header->{$properties[$i]['name']} = $properties[$i]['value'];
149 }
c9d78ab4 150 }
164800ad 151 $structure = $structure . ' ' . $structure_end;
152 }
153 $element = substr($structure, $start+1, ($end - $start)-1);
154 $ent_id = mime_increment_id ($ent_id);
155 $newmsg = mime_parse_structure ($element, $ent_id);
156 /* set mailbox in case of message/rfc822 entities */
157 if (isset($newmsg->header->type0) && isset($newmsg->header->type1)) {
158 if ($newmsg->header->type0 == 'message' && $newmsg->header->type1 == 'rfc822') {
159 $newmsg->header->mailbox=$mailbox;
c9d78ab4 160 }
161 }
164800ad 162 $msg->addEntity ($newmsg);
451f74a2 163
451f74a2 164 } while ($structure{$end+1} == '(');
165 } else {
166 // parse the elements
c9d78ab4 167 $msg = mime_get_element ($structure, $msg, $ent_id);
451f74a2 168 }
169 return $msg;
170}
e4a256af 171
164800ad 172
451f74a2 173/* Increments the element ID. An element id can look like any of
174 * the following: 1, 1.2, 4.3.2.4.1, etc. This function increments
175 * the last number of the element id, changing 1.2 to 1.3.
176 */
177function mime_increment_id ($id) {
178
77b88425 179 if (strpos($id, '.')) {
180 $first = substr($id, 0, strrpos($id, '.'));
181 $last = substr($id, strrpos($id, '.')+1);
451f74a2 182 $last++;
77b88425 183 $new = $first . '.' .$last;
451f74a2 184 } else {
185 $new = $id + 1;
186 }
77b88425 187
451f74a2 188 return $new;
189}
190
191/*
192 * See comment for mime_increment_id().
193 * This adds another level on to the entity_id changing 1.3 to 1.3.0
194 * NOTE: 1.3.0 is not a valid element ID. It MUST be incremented
195 * before it can be used. I left it this way so as not to have
196 * to make a special case if it is the first entity_id. It
197 * always increments it, and that works fine.
198 */
199function mime_new_element_level ($id) {
200
77b88425 201 if (!$id) {
202 $id = 0;
203 } else {
204 $id = $id . '.0';
205 }
451f74a2 206
77b88425 207 return( $id );
451f74a2 208}
209
210function mime_get_element (&$structure, $msg, $ent_id) {
211
212 $elem_num = 1;
213 $msg->header = new msg_header();
214 $msg->header->entity_id = $ent_id;
215 $properties = array();
451f74a2 216 while (strlen($structure) > 0) {
217 $structure = trim($structure);
218 $char = $structure{0};
219
220 if (strtolower(substr($structure, 0, 3)) == 'nil') {
221 $text = '';
222 $structure = substr($structure, 3);
223 } else if ($char == '"') {
224 // loop through until we find the matching quote, and return that as a string
225 $pos = 1;
226 $text = '';
227 while ( ($char = $structure{$pos} ) <> '"' && $pos < strlen($structure)) {
228 $text .= $char;
229 $pos++;
230 }
231 $structure = substr($structure, strlen($text) + 2);
232 } else if ($char == '(') {
233 // comment me
234 $end = mime_match_parenthesis (0, $structure);
235 $sub = substr($structure, 1, $end-1);
236 $properties = mime_get_props($properties, $sub);
237 $structure = substr($structure, strlen($sub) + 2);
238 } else {
239 // loop through until we find a space or an end parenthesis
240 $pos = 0;
241 $char = $structure{$pos};
242 $text = '';
243 while ($char != ' ' && $char != ')' && $pos < strlen($structure)) {
244 $text .= $char;
245 $pos++;
246 $char = $structure{$pos};
247 }
248 $structure = substr($structure, strlen($text));
249 }
250
251 // This is where all the text parts get put into the header
252 switch ($elem_num) {
253 case 1:
254 $msg->header->type0 = strtolower($text);
255 break;
256 case 2:
257 $msg->header->type1 = strtolower($text);
258 break;
259 case 4: // Id
260 // Invisimail enclose images with <>
261 $msg->header->id = str_replace( '<', '', str_replace( '>', '', $text ) );
262 break;
263 case 5:
264 $msg->header->description = $text;
265 break;
266 case 6:
267 $msg->header->encoding = strtolower($text);
268 break;
269 case 7:
270 $msg->header->size = $text;
271 break;
272 default:
273 if ($msg->header->type0 == 'text' && $elem_num == 8) {
274 // This is a plain text message, so lets get the number of lines
275 // that it contains.
276 $msg->header->num_lines = $text;
277
278 } else if ($msg->header->type0 == 'message' && $msg->header->type1 == 'rfc822' && $elem_num == 8) {
279 // This is an encapsulated message, so lets start all over again and
280 // parse this message adding it on to the existing one.
281 $structure = trim($structure);
282 if ( $structure{0} == '(' ) {
283 $e = mime_match_parenthesis (0, $structure);
284 $structure = substr($structure, 0, $e);
285 $structure = substr($structure, 1);
286 $m = mime_parse_structure($structure, $msg->header->entity_id);
287
288 // the following conditional is there to correct a bug that wasn't
289 // incrementing the entity IDs correctly because of the special case
290 // that message/rfc822 is. This fixes it fine.
291 if (substr($structure, 1, 1) != '(')
292 $m->header->entity_id = mime_increment_id(mime_new_element_level($ent_id));
293
294 // Now we'll go through and reformat the results.
295 if ($m->entities) {
296 for ($i=0; $i < count($m->entities); $i++) {
297 $msg->addEntity($m->entities[$i]);
298 }
299 } else {
300 $msg->addEntity($m);
301 }
302 $structure = "";
303 }
304 }
305 break;
306 }
307 $elem_num++;
308 $text = "";
309 }
310 // loop through the additional properties and put those in the various headers
c9d78ab4 311 for ($i=0; $i < count($properties); $i++) {
312 $msg->header->{$properties[$i]['name']} = $properties[$i]['value'];
313 }
451f74a2 314
315 return $msg;
316}
317
318/*
319 * I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
320 * figure out how to do this part, so I decided to go to bed. I woke up
321 * in the morning and had a flash of insight. I went to the white-board
322 * and scribbled it out, then spent a bit programming it, and this is the
323 * result. Nothing complicated, but I think my brain was fried yesterday.
324 * Funny how that happens some times.
325 *
326 * This gets properties in a nested parenthesisized list. For example,
327 * this would get passed something like: ("attachment" ("filename" "luke.tar.gz"))
328 * This returns an array called $props with all paired up properties.
329 * It ignores the "attachment" for now, maybe that should change later
330 * down the road. In this case, what is returned is:
331 * $props[0]["name"] = "filename";
332 * $props[0]["value"] = "luke.tar.gz";
333 */
334function mime_get_props ($props, $structure) {
335
336 while (strlen($structure) > 0) {
337 $structure = trim($structure);
338 $char = $structure{0};
451f74a2 339 if ($char == '"') {
340 $pos = 1;
341 $tmp = '';
342 while ( ( $char = $structure{$pos} ) != '"' &&
343 $pos < strlen($structure)) {
344 $tmp .= $char;
345 $pos++;
346 }
347 $structure = trim(substr($structure, strlen($tmp) + 2));
348 $char = $structure{0};
349
350 if ($char == '"') {
351 $pos = 1;
352 $value = '';
353 while ( ( $char = $structure{$pos} ) != '"' &&
354 $pos < strlen($structure) ) {
355 $value .= $char;
356 $pos++;
357 }
c9d78ab4 358 $structure = trim(substr($structure, strlen($value) + 2));
451f74a2 359 $k = count($props);
360 $props[$k]['name'] = strtolower($tmp);
361 $props[$k]['value'] = $value;
c9d78ab4 362 if ($structure != '') {
363 mime_get_props($props, $structure);
364 } else {
365 return $props;
366 }
451f74a2 367 } else if ($char == '(') {
368 $end = mime_match_parenthesis (0, $structure);
369 $sub = substr($structure, 1, $end-1);
c9d78ab4 370 if (! isset($props))
371 $props = array();
372 $props = mime_get_props($props, $sub);
373 $structure = substr($structure, strlen($sub) + 2);
374 return $props;
451f74a2 375 }
451f74a2 376 } else if ($char == '(') {
377 $end = mime_match_parenthesis (0, $structure);
378 $sub = substr($structure, 1, $end-1);
379 $props = mime_get_props($props, $sub);
380 $structure = substr($structure, strlen($sub) + 2);
381 return $props;
382 } else {
383 return $props;
384 }
385 }
386}
387
388/*
389 * Matches parenthesis. It will return the position of the matching
390 * parenthesis in $structure. For instance, if $structure was:
391 * ("text" "plain" ("val1name", "1") nil ... )
392 * x x
393 * then this would return 42 to match up those two.
394 */
395function mime_match_parenthesis ($pos, $structure) {
396
397 $j = strlen( $structure );
398
399 // ignore all extra characters
400 // If inside of a string, skip string -- Boundary IDs and other
401 // things can have ) in them.
402 if ( $structure{$pos} != '(' ) {
403 return( $j );
404 }
405
406 while ( $pos < $j ) {
407 $pos++;
408 if ($structure{$pos} == ')') {
8beafbbc 409 return $pos;
451f74a2 410 } elseif ($structure{$pos} == '"') {
b74ba498 411 $pos++;
451f74a2 412 while ( $structure{$pos} != '"' &&
413 $pos < $j ) {
414 if (substr($structure, $pos, 2) == '\\"') {
b74ba498 415 $pos++;
451f74a2 416 } elseif (substr($structure, $pos, 2) == '\\\\') {
b74ba498 417 $pos++;
451f74a2 418 }
b74ba498 419 $pos++;
5ffe5a7e 420 }
451f74a2 421 } elseif ( $structure{$pos} == '(' ) {
8beafbbc 422 $pos = mime_match_parenthesis ($pos, $structure);
451f74a2 423 }
424 }
425 echo _("Error decoding mime structure. Report this as a bug!") . '<br>';
426 return( $pos );
427}
428
346817d4 429function mime_fetch_body($imap_stream, $id, $ent_id ) {
09a4bde3 430
431 /*
432 * do a bit of error correction. If we couldn't find the entity id, just guess
433 * that it is the first one. That is usually the case anyway.
434 */
435 if (!$ent_id) {
451f74a2 436 $ent_id = 1;
09a4bde3 437 }
346817d4 438
6ab1bd9e 439 $cmd = "FETCH $id BODY[$ent_id]";
346817d4 440 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message);
77b88425 441
442 do {
e976319c 443 $topline = trim(array_shift( $data ));
444 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
451f74a2 445 $wholemessage = implode('', $data);
446 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
77b88425 447
451f74a2 448 $ret = substr( $wholemessage, 0, $regs[1] );
449 /*
450 There is some information in the content info header that could be important
451 in order to parse html messages. Let's get them here.
452 */
453 if ( $ret{0} == '<' ) {
1c72b151 454 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message);
e5ea9327 455 /* BASE within HTML documents is illegal (see w3 spec)
456* $base = '';
457* $k = 10;
458* foreach( $data as $d ) {
459* if ( substr( $d, 0, 13 ) == 'Content-Base:' ) {
460* $j = strlen( $d );
461* $i = 13;
462* $base = '';
463* while ( $i < $j &&
464* ( !isNoSep( $d{$i} ) || $d{$i} == '"' ) )
465* $i++;
466* while ( $i < $j ) {
467* if ( isNoSep( $d{$i} ) )
468* $base .= $d{$i};
469* $i++;
470* }
471* $k = 0;
472* } elseif ( $k == 1 && !isnosep( $d{0} ) ) {
473* $base .= substr( $d, 1 );
474* }
475* $k++;
476* }
477* if ( $base <> '' ) {
478* $ret = "<base href=\"$base\">" . $ret;
479* }
7e235a1a 480* */
451f74a2 481 }
482 } else if (ereg('"([^"]*)"', $topline, $regs)) {
483 $ret = $regs[1];
484 } else {
485 global $where, $what, $mailbox, $passed_id, $startMessage;
e5ea9327 486 $par = 'mailbox=' . urlencode($mailbox) . "&amp;passed_id=$passed_id";
451f74a2 487 if (isset($where) && isset($what)) {
e5ea9327 488 $par .= '&amp;where='. urlencode($where) . "&amp;what=" . urlencode($what);
a3daaaf3 489 } else {
e5ea9327 490 $par .= "&amp;startMessage=$startMessage&amp;show_more=0";
451f74a2 491 }
e5ea9327 492 $par .= '&amp;response=' . urlencode($response) .
493 '&amp;message=' . urlencode($message).
494 '&amp;topline=' . urlencode($topline);
a019eeb8 495
346817d4 496 echo '<tt><br>' .
497 '<table width="80%"><tr>' .
498 '<tr><td colspan=2>' .
451f74a2 499 _("Body retrieval error. The reason for this is most probably that the message is malformed. Please help us making future versions better by submitting this message to the developers knowledgebase!") .
346817d4 500 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
501 _("Submit message") . '</A><BR>&nbsp;' .
502 '</td></tr>' .
503 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
504 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
505 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
506 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
507 "</table><BR></tt></font><hr>";
508
1c72b151 509 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message);
451f74a2 510 array_shift($data);
511 $wholemessage = implode('', $data);
a019eeb8 512
346817d4 513 $ret = $wholemessage;
a3daaaf3 514 }
451f74a2 515 return( $ret );
516}
d4467150 517
451f74a2 518function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
519 // do a bit of error correction. If we couldn't find the entity id, just guess
520 // that it is the first one. That is usually the case anyway.
521 if (!$ent_id) {
522 $ent_id = 1;
523 }
524 $sid = sqimap_session_id();
525 // Don't kill the connection if the browser is over a dialup
526 // and it would take over 30 seconds to download it.
b7206e1d 527
528