ce2be9b894cef4b9b36c9f8bad8ff4bf27d625e6
[squirrelmail.git] / functions / mime.php
1 <?php
2
3 /**
4 * mime.php
5 *
6 * Copyright (c) 1999-2002 The SquirrelMail Project Team
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 */
14
15 require_once('../functions/imap.php');
16 require_once('../functions/attachment_common.php');
17
18 /* --------------------------------------------------------------------------------- */
19 /* MIME DECODING */
20 /* --------------------------------------------------------------------------------- */
21
22 /* This function gets the structure of a message and stores it in the "message" class.
23 * It will return this object for use with all relevant header information and
24 * fully parsed into the standard "message" object format.
25 */
26
27 function mime_structure ($bodystructure, $flags=array()) {
28
29 // isolate the body structure and remove beginning and end parenthesis
30 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
31 $msg = &new message();
32 $read = trim(substr ($read, 0, -1));
33 $msg = $msg->parseStructure($read,0);
34 $msg->setEnt('0');
35 if (count($flags)) {
36 foreach ($flags as $flag) {
37 $char = strtoupper($flag{1});
38 switch ($char) {
39 case 'S':
40 if (strtolower($flag) == '\\seen') {
41 $msg->is_seen = true;
42 }
43 break;
44 case 'A':
45 if (strtolower($flag) == '\\answered') {
46 $msg->is_answered = true;
47 }
48 break;
49 case 'D':
50 if (strtolower($flag) == '\\deleted') {
51 $msg->is_deleted = true;
52 }
53 break;
54 case 'F':
55 if (strtolower($flag) == '\\flagged') {
56 $msg->is_flagged = true;
57 }
58 break;
59 case 'M':
60 if (strtolower($flag) == '\$mdnsent') {
61 $msg->is_mdn = true;
62 }
63 break;
64 default:
65 break;
66 }
67 }
68 }
69 // listEntities($msg);
70 return( $msg );
71 }
72
73 /* this starts the parsing of a particular structure. It is called recursively,
74 * so it can be passed different structures. It returns an object of type
75 * $message.
76 * First, it checks to see if it is a multipart message. If it is, then it
77 * handles that as it sees is necessary. If it is just a regular entity,
78 * then it parses it and adds the necessary header information (by calling out
79 * to mime_get_elements()
80 */
81
82 function mime_fetch_body($imap_stream, $id, $ent_id) {
83 global $uid_support;
84 /*
85 * do a bit of error correction. If we couldn't find the entity id, just guess
86 * that it is the first one. That is usually the case anyway.
87 */
88 if (!$ent_id) {
89 $ent_id = 1;
90 }
91 $cmd = "FETCH $id BODY[$ent_id]";
92
93 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
94 do {
95 $topline = trim(array_shift( $data ));
96 } while( $topline && $topline[0] == '*' && !preg_match( '/\* [0-9]+ FETCH.*/i', $topline )) ;
97
98 $wholemessage = implode('', $data);
99 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
100
101 $ret = substr( $wholemessage, 0, $regs[1] );
102 /*
103 There is some information in the content info header that could be important
104 in order to parse html messages. Let's get them here.
105 */
106 if ( $ret{0} == '<' ) {
107 $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
108 }
109 } else if (ereg('"([^"]*)"', $topline, $regs)) {
110 $ret = $regs[1];
111 } else {
112 global $where, $what, $mailbox, $passed_id, $startMessage;
113 $par = 'mailbox=' . urlencode($mailbox) . "&amp;passed_id=$passed_id";
114 if (isset($where) && isset($what)) {
115 $par .= '&amp;where='. urlencode($where) . "&amp;what=" . urlencode($what);
116 } else {
117 $par .= "&amp;startMessage=$startMessage&amp;show_more=0";
118 }
119 $par .= '&amp;response=' . urlencode($response) .
120 '&amp;message=' . urlencode($message).
121 '&amp;topline=' . urlencode($topline);
122
123 echo '<tt><br>' .
124 '<table width="80%"><tr>' .
125 '<tr><td colspan=2>' .
126 _("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!") .
127 " <A HREF=\"../src/retrievalerror.php?$par\"><br>" .
128 _("Submit message") . '</A><BR>&nbsp;' .
129 '</td></tr>' .
130 '<td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
131 '<td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
132 '<td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
133 '<td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
134 "</table><BR></tt></font><hr>";
135
136 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
137 array_shift($data);
138 $wholemessage = implode('', $data);
139
140 $ret = $wholemessage;
141 }
142 return( $ret );
143 }
144
145 function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
146 global $uid_support;
147 // do a bit of error correction. If we couldn't find the entity id, just guess
148 // that it is the first one. That is usually the case anyway.
149 if (!$ent_id) {
150 $ent_id = 1;
151 }
152 $sid = sqimap_session_id($uid_support);
153 // Don't kill the connection if the browser is over a dialup
154 // and it would take over 30 seconds to download it.
155
156 // donĀ“t call set_time_limit in safe mode.
157 if (!ini_get("safe_mode")) {
158 set_time_limit(0);
159 }
160 if ($uid_support) {
161 $sid_s = substr($sid,0,strpos($sid, ' '));
162 } else {
163 $sid_s = $sid;
164 }
165
166 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
167 $cnt = 0;
168 $continue = true;
169 $read = fgets ($imap_stream,8192);
170
171
172 // if (preg_match('/.*\{(\d+)\}.*/',$read,$regs)) {
173 /*
174 $size = $regs[1];
175 $size_div = (int) ($size / 4096);
176 $size_mod = $size % 4096;
177 if (!$size_mod) $size_div++;
178 $read = '';
179 for ($i=0;$i<$size_div;$i++) {
180 $read .= fread ($imap_stream,4096);
181 }
182 if ($size_mod > 0) {
183 $read .= fread ($imap_stream, $size_mod);
184 }
185 echo decodeBody($read, $encoding);
186 }
187 */
188 // This could be bad -- if the section has sqimap_session_id() . ' OK'
189 // or similar, it will kill the download.
190 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
191 if (trim($read) == ')==') {
192 $read1 = $read;
193 $read = fgets ($imap_stream,4096);
194 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
195 return;
196 } else {
197 echo decodeBody($read1, $encoding) .
198 decodeBody($read, $encoding);
199 }
200 } else if ($cnt) {
201 echo decodeBody($read, $encoding);
202 }
203 $read = fgets ($imap_stream,4096);
204 $cnt++;
205 // break;
206 }
207 }
208
209 /* -[ END MIME DECODING ]----------------------------------------------------------- */
210
211
212 // This is here for debugging purposese. It will print out a list
213 // of all the entity IDs that are in the $message object.
214
215 function listEntities ($message) {
216 if ($message) {
217 echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br>';
218 for ($i = 0;isset($message->entities[$i]); $i++) {
219 echo "$i : ";
220 $msg = listEntities($message->entities[$i]);
221
222 if ($msg) {
223 echo "return: ";
224 return $msg;
225 }
226 }
227 }
228 }
229
230
231 /* returns a $message object for a particular entity id */
232 function getEntity ($message, $ent_id) {
233 return $message->getEntity($ent_id);
234 }
235
236 /*
237 * figures out what entity to display and returns the $message object
238 * for that entity.
239 */
240 function findDisplayEntity ($msg, $textOnly = true, $entity = array() ) {
241 global $show_html_default;
242
243 $found = false;
244 if ($msg) {
245 $type = $msg->type0.'/'.$msg->type1;
246 if ( $type == 'multipart/alternative') {
247 $msg = findAlternativeEntity($msg, $textOnly);
248 if (count($msg->entities) == 0) {
249 $entity[] = $msg->entity_id;
250 } else {
251 $found = true;
252 $entity =findDisplayEntity($msg,$textOnly, $entity);
253 }
254 } else if ( $type == 'multipart/related') {
255 $msgs = findRelatedEntity($msg);
256 for ($i = 0; $i < count($msgs); $i++) {
257 $msg = $msgs[$i];
258 if (count($msg->entities) == 0) {
259 $entity[] = $msg->entity_id;
260 } else {
261 $found = true;
262 $entity =findDisplayEntity($msg,$textOnly, $entity);
263 }
264 }
265 } else if ( count($entity) == 0 &&
266 $msg->type0 == 'text' &&
267 ( $msg->type1 == 'plain' ||
268 $msg->type1 == 'html' ) &&
269 isset($msg->entity_id) ) {
270 if (count($msg->entities) == 0) {
271 $entity[] = $msg->entity_id;
272 }
273 }
274 $i = 0;
275 while ( isset($msg->entities[$i]) && count($entity) == 0 && !$found ) {
276 $entity = findDisplayEntity($msg->entities[$i], $textOnly, $entity);
277 $i++;
278 }
279 }
280 if ( !isset($entity[0]) ) {
281 $entity[]="";
282 }
283 return( $entity );
284 }
285
286 /* Shows the HTML version */
287 function findDisplayEntityHTML ($message) {
288
289 if ( $message->header->type0 == 'text' &&
290 $message->header->type1 == 'html' &&
291 isset($message->header->entity_id)) {
292 return $message->header->entity_id;
293 }
294 for ($i = 0; isset($message->entities[$i]); $i ++) {
295 if ( $message->header->type0 == 'message' &&
296 $message->header->type1 == 'rfc822' &&
297 isset($message->header->entity_id)) {
298 return 0;
299 }
300
301 $entity = findDisplayEntityHTML($message->entities[$i]);
302 if ($entity != 0) {
303 return $entity;
304 }
305 }
306
307 return 0;
308 }
309
310 function findAlternativeEntity ($message, $textOnly) {
311 global $show_html_default;
312 /* if we are dealing with alternative parts then we choose the best
313 * viewable message supported by SM.
314 */
315 if ($show_html_default && !$textOnly) {
316 $alt_order = array ('text/plain','text/html');
317 } else {
318 $alt_order = array ('text/plain');
319 }
320 $best_view = 0;
321 $ent_id = 0;
322 $k = 0;
323 for ($i = 0; $i < count($message->entities); $i ++) {
324 $type = $message->entities[$i]->header->type0.'/'.$message->entities[$i]->header->type1;
325 if ($type == 'multipart/related') {
326 $type = $message->entities[$i]->header->type;
327 }
328 for ($j = $k; $j < count($alt_order); $j++) {
329 if ($alt_order[$j] == $type && $j > $best_view) {
330 $best_view = $j;
331 $ent_id = $i;
332 $k = $j;
333 }
334 }
335 }
336 return $message->entities[$ent_id];
337 }
338
339 function findRelatedEntity ($message) {
340 $msgs = array();
341 for ($i = 0; $i < count($message->entities); $i ++) {
342 $type = $message->entities[$i]->header->type0.'/'.$message->entities[$i]->header->type1;
343 if ($message->header->type == $type) {
344 $msgs[] = $message->entities[$i];
345 }
346 }
347 return $msgs;
348 }
349
350 /*
351 * translateText
352 * Extracted from strings.php 23/03/2002
353 */
354
355 function translateText(&$body, $wrap_at, $charset) {
356 global $where, $what; /* from searching */
357 global $color; /* color theme */
358
359 require_once('../functions/url_parser.php');
360
361 $body_ary = explode("\n", $body);
362 $PriorQuotes = 0;
363 for ($i=0; $i < count($body_ary); $i++) {
364 $line = $body_ary[$i];
365 if (strlen($line) - 2 >= $wrap_at) {
366 sqWordWrap($line, $wrap_at);
367 }
368 $line = charset_decode($charset, $line);
369 $line = str_replace("\t", ' ', $line);
370
371 parseUrl ($line);
372
373 $Quotes = 0;
374 $pos = 0;
375 $j = strlen( $line );
376
377 while ( $pos < $j ) {
378 if ($line[$pos] == ' ') {
379 $pos ++;
380 } else if (strpos($line, '&gt;', $pos) === $pos) {
381 $pos += 4;
382 $Quotes ++;
383 } else {
384 break;
385 }
386 }
387
388 if ($Quotes > 1) {
389 if (! isset($color[14])) {
390 $color[14] = '#FF0000';
391 }
392 $line = '<FONT COLOR="' . $color[14] . '">' . $line . '</FONT>';
393 } elseif ($Quotes) {
394 if (! isset($color[13])) {
395 $color[13] = '#800000';
396 }
397 $line = '<FONT COLOR="' . $color[13] . '">' . $line . '</FONT>';
398 }
399
400 $body_ary[$i] = $line;
401 }
402 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
403 }
404
405
406 /* This returns a parsed string called $body. That string can then
407 be displayed as the actual message in the HTML. It contains
408 everything needed, including HTML Tags, Attachments at the
409 bottom, etc.
410 */
411 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
412 // this if statement checks for the entity to show as the
413 // primary message. To add more of them, just put them in the
414 // order that is their priority.
415 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
416 $show_html_default, $has_unsafe_images, $view_unsafe_images, $sort;
417
418 $has_unsafe_images = 0;
419
420 if ($message->type0 == 'message' && $message->type1 == 'rfc822') {
421 $message = $message->entities[0];
422 }
423 $urlmailbox = urlencode($message->mailbox);
424 $body_message = getEntity($message, $ent_num);
425 if (($body_message->header->type0 == 'text') ||
426 ($body_message->header->type0 == 'rfc822')) {
427 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
428
429 $body = decodeBody($body, $body_message->header->encoding);
430 $hookResults = do_hook("message_body", $body);
431 $body = $hookResults[1];
432 // If there are other types that shouldn't be formatted, add
433 // them here
434 if ($body_message->header->type1 == 'html') {
435 if ( $show_html_default <> 1 ) {
436 $body = strip_tags( $body );
437 translateText($body, $wrap_at, $body_message->header->charset);
438 } else {
439 $body = magicHTML( $body, $id, $message, $mailbox );
440 }
441 } else {
442 translateText($body, $wrap_at, $body_message->header->charset);
443 }
444 $body .= "<CENTER><SMALL><A HREF=\"../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;passed_ent_id=$ent_num&amp;mailbox=$urlmailbox&amp;showHeaders=1\">". _("Download this as a file") ."</A></SMALL></CENTER><BR>";
445 if ($has_unsafe_images) {
446 if ($view_unsafe_images) {
447 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
448 } else {
449 $body .= "<CENTER><SMALL><A HREF=\"read_body.php?passed_id=$id&amp;mailbox=$urlmailbox&amp;sort=$sort&amp;startMessage=$startMessage&amp;show_more=0&amp;view_unsafe_images=1\">". _("View Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
450 }
451 }
452
453 /** Display the ATTACHMENTS: message if there's more than one part **/
454 if (isset($message->entities[1])) {
455 /* Header-type alternative means we choose the best one to display
456 so don't show the alternatives as attachment. Header-type related
457 means that the attachments are already part of the related message.
458 */
459 if ($message->header->type1 !='related' && $message->header->type1 !='alternative') {
460 $body .= formatAttachments ($message, $ent_num, $mailbox, $id);
461 }
462 }
463 } else {
464 $body = formatAttachments ($message, -1, $message->mailbox, $id);
465 }
466 return ($body);
467 }
468
469 /*
470 * A recursive function that returns a list of attachments with links
471 * to where to download these attachments
472 */
473 function formatAttachments($message, $ent_id, $mailbox, $id) {
474 global $where, $what;
475 global $startMessage, $color;
476 static $ShownHTML = 0;
477
478 $body = '';
479 if ($ShownHTML == 0) {
480
481 $ShownHTML = 1;
482 $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
483 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
484 _("Attachments") . ':' .
485 "</B></TH></TR><TR><TD>\n" .
486 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
487 formatAttachments($message, $ent_id, $mailbox, $id) .
488 "</TABLE></TD></TR></TABLE>";
489
490 } else if ($message) {
491 $header = $message->header;
492 $type0 = strtolower($header->type0);
493 $type1 = strtolower($header->type1);
494 $name = '';
495 if (isset($header->name)) {
496 $name = decodeHeader($header->name);
497 }
498 if ($type0 =='message' && $type1 == 'rfc822') {
499
500 $filename = decodeHeader($message->header->subject);
501 $display_filename = $filename;
502
503 $urlMailbox = urlencode($mailbox);
504 $ent = urlencode($message->entity_id);
505
506 $DefaultLink =
507 "../src/read_body.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
508 if ($where && $what) {
509 $DefaultLink .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
510 }
511 $Links['download link']['text'] = _("download");
512 $Links['download link']['href'] =
513 "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
514 $ImageURL = '';
515
516 /* this executes the attachment hook with a specific MIME-type.
517 * if that doens't have results, it tries if there's a rule
518 * for a more generic type. */
519 $HookResults = do_hook("attachment $type0/$type1", $Links,
520 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
521 if(count($HookResults[1]) <= 1) {
522 $HookResults = do_hook("attachment $type0/*", $Links,
523 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
524 $display_filename, $where, $what);
525 }
526
527 $Links = $HookResults[1];
528 $DefaultLink = $HookResults[6];
529
530 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
531 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
532 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
533 '</b>&nbsp;&nbsp;</small></TD>' .
534 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
535 '<TD><SMALL>';
536 $from_o = $message->header->from;
537 if (isset($from_o)) {
538 $from_name = $from_o->getAddress(false);
539 } else {
540 $from_name = _("Unknown sender");
541 }
542 $from_name = decodeHeader(htmlspecialchars($from_name));
543 $body .= '<b>' . $from_name . '</b>';
544 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
545
546 $SkipSpaces = 1;
547 foreach ($Links as $Val) {
548 if ($SkipSpaces) {
549 $SkipSpaces = 0;
550 } else {
551 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
552 }
553 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
554 }
555
556 unset($Links);
557
558 $body .= "</SMALL></TD></TR>\n";
559
560 return( $body );
561
562 } elseif (!$message->entities) {
563
564 $type0 = strtolower($message->header->type0);
565 $type1 = strtolower($message->header->type1);
566 $name = decodeHeader($message->header->name);
567
568 if ($message->entity_id != $ent_id) {
569 $filename = decodeHeader($message->header->filename);
570 if (trim($filename) == '') {
571 if (trim($name) == '') {
572 if ( trim( $message->header->id ) == '' )
573 $display_filename = 'untitled-[' . $message->entity_id . ']' ;
574 else
575 $display_filename = 'cid: ' . $message->header->id;
576 // $display_filename = 'untitled-[' . $message->entity_id . ']' ;
577 } else {
578 $display_filename = $name;
579 $filename = $name;
580 }
581 } else {
582 $display_filename = $filename;
583 }
584
585 $urlMailbox = urlencode($mailbox);
586 $ent = urlencode($message->entity_id);
587
588 $DefaultLink =
589 "../src/download.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
590 if ($where && $what) {
591 $DefaultLink = '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
592 }
593 $Links['download link']['text'] = _("download");
594 $Links['download link']['href'] =
595 "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
596 $ImageURL = '';
597
598 /* this executes the attachment hook with a specific MIME-type.
599 * if that doens't have results, it tries if there's a rule
600 * for a more generic type. */
601 $HookResults = do_hook("attachment $type0/$type1", $Links,
602 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
603 $display_filename, $where, $what);
604 if(count($HookResults[1]) <= 1) {
605 $HookResults = do_hook("attachment $type0/*", $Links,
606 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
607 $display_filename, $where, $what);
608 }
609
610 $Links = $HookResults[1];
611 $DefaultLink = $HookResults[6];
612
613 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
614 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
615 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
616 '</b>&nbsp;&nbsp;</small></TD>' .
617 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
618 '<TD><SMALL>';
619 if ($message->header->description) {
620 $body .= '<b>' . htmlspecialchars(_($message->header->description)) . '</b>';
621 }
622 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
623
624
625 $SkipSpaces = 1;
626 foreach ($Links as $Val) {
627 if ($SkipSpaces) {
628 $SkipSpaces = 0;
629 } else {
630 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
631 }
632 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
633 }
634
635 unset($Links);
636
637 $body .= "</SMALL></TD></TR>\n";
638 }
639 } else {
640 for ($i = 0; $i < count($message->entities); $i++) {
641 $body .= formatAttachments($message->entities[$i], $ent_id, $mailbox, $id);
642 }
643 }
644 }
645 return( $body );
646 }
647
648
649 /** this function decodes the body depending on the encoding type. **/
650 function decodeBody($body, $encoding) {
651 $body = str_replace("\r\n", "\n", $body);
652 $encoding = strtolower($encoding);
653
654 global $show_html_default;
655
656 if ($encoding == 'quoted-printable' ||
657 $encoding == 'quoted_printable') {
658 $body = quoted_printable_decode($body);
659
660 while (ereg("=\n", $body))
661 $body = ereg_replace ("=\n", "", $body);
662
663 } else if ($encoding == 'base64') {
664 $body = base64_decode($body);
665 }
666
667 // All other encodings are returned raw.
668 return $body;
669 }
670
671 /*
672 * This functions decode strings that is encoded according to
673 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
674 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
675 */
676 function decodeHeader ($string, $utfencode=true) {
677 if (is_array($string)) {
678 $string = implode("\n", $string);
679 }
680 $i = 0;
681 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
682 $string, $res)) {
683 $prefix = $res[1];
684 // Ignore white-space between consecutive encoded-words
685 if (strspn($res[2], " \t") != strlen($res[2])) {
686 $prefix .= $res[2];
687 }
688
689 if (ucfirst($res[4]) == 'B') {
690 $replace = base64_decode($res[5]);
691 } else {
692 $replace = str_replace('_', ' ', $res[5]);
693 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
694 $replace);
695 /* Only encode into entities by default. Some places
696 don't need the encoding, like the compose form. */
697 if ($utfencode) {
698 $replace = charset_decode($res[3], $replace);
699 }
700 }
701 $string = $prefix . $replace . substr($string, strlen($res[0]));
702 $i = strlen($prefix) + strlen($replace);
703 }
704 return( $string );
705 }
706
707 /*
708 * Encode a string according to RFC 1522 for use in headers if it
709 * contains 8-bit characters or anything that looks like it should
710 * be encoded.
711 */
712 function encodeHeader ($string) {
713 global $default_charset;
714
715 // Encode only if the string contains 8-bit characters or =?
716 $j = strlen( $string );
717 $l = strstr($string, '=?'); // Must be encoded ?
718 $ret = '';
719 for( $i=0; $i < $j; ++$i) {
720 switch( $string{$i} ) {
721 case '=':
722 $ret .= '=3D';
723 break;
724 case '?':
725 $ret .= '=3F';
726 break;
727 case '_':
728 $ret .= '=5F';
729 break;
730 case ' ':
731 $ret .= '_';
732 break;
733 default:
734 $k = ord( $string{$i} );
735 if ( $k > 126 ) {
736 $ret .= sprintf("=%02X", $k);
737 $l = TRUE;
738 } else
739 $ret .= $string{$i};
740 }
741 }
742
743 if ( $l ) {
744 $string = "=?$default_charset?Q?$ret?=";
745 }
746
747 return( $string );
748 }
749
750 /* This function trys to locate the entity_id of a specific mime element */
751
752 function find_ent_id( $id, $message ) {
753 $ret = '';
754 for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
755 if ( $message->entities[$i]->header->type0 == 'multipart') {
756 $ret = find_ent_id( $id, $message->entities[$i] );
757 } else {
758 if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
759 $ret = $message->entities[$i]->entity_id;
760 }
761 }
762 return( $ret );
763 }
764
765 /**
766 ** HTMLFILTER ROUTINES
767 */
768
769 /**
770 * This function returns the final tag out of the tag name, an array
771 * of attributes, and the type of the tag. This function is called by
772 * sq_sanitize internally.
773 *
774 * @param $tagname the name of the tag.
775 * @param $attary the array of attributes and their values
776 * @param $tagtype The type of the tag (see in comments).
777 * @return a string with the final tag representation.
778 */
779 function sq_tagprint($tagname, $attary, $tagtype){
780 $me = "sq_tagprint";
781 if ($tagtype == 2){
782 $fulltag = '</' . $tagname . '>';
783 } else {
784 $fulltag = '<' . $tagname;
785 if (is_array($attary) && sizeof($attary)){
786 $atts = Array();
787 while (list($attname, $attvalue) = each($attary)){
788 array_push($atts, "$attname=$attvalue");
789 }
790 $fulltag .= ' ' . join(" ", $atts);
791 }
792 if ($tagtype == 3){
793 $fulltag .= " /";
794 }
795 $fulltag .= ">";
796 }
797 return $fulltag;
798 }
799
800 /**
801 * A small helper function to use with array_walk. Modifies a by-ref
802 * value and makes it lowercase.
803 *
804 * @param $val a value passed by-ref.
805 * @return void since it modifies a by-ref value.
806 */
807 function sq_casenormalize(&$val){
808 $val = strtolower($val);
809 }
810
811 /**
812 * This function skips any whitespace from the current position within
813 * a string and to the next non-whitespace value.
814 *
815 * @param $body the string
816 * @param $offset the offset within the string where we should start
817 * looking for the next non-whitespace character.
818 * @return the location within the $body where the next
819 * non-whitespace char is located.
820 */
821 function sq_skipspace($body, $offset){
822 $me = "sq_skipspace";
823 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
824 if (sizeof($matches{1})){
825 $count = strlen($matches{1});
826 $offset += $count;
827 }
828 return $offset;
829 }
830
831 /**
832 * This function looks for the next character within a string. It's
833 * really just a glorified "strpos", except it catches if failures
834 * nicely.
835 *
836 * @param $body The string to look for needle in.
837 * @param $offset Start looking from this position.
838 * @param $needle The character/string to look for.
839 * @return location of the next occurance of the needle, or
840 * strlen($body) if needle wasn't found.
841 */
842 function sq_findnxstr($body, $offset, $needle){
843 $me = "sq_findnxstr";
844 $pos = strpos($body, $needle, $offset);
845 if ($pos === FALSE){
846 $pos = strlen($body);
847 }
848 return $pos;
849 }
850
851 /**
852 * This function takes a PCRE-style regexp and tries to match it
853 * within the string.
854 *
855 * @param $body The string to look for needle in.
856 * @param $offset Start looking from here.
857 * @param $reg A PCRE-style regex to match.
858 * @return Returns a false if no matches found, or an array
859 * with the following members:
860 * - integer with the location of the match within $body
861 * - string with whatever content between offset and the match
862 * - string with whatever it is we matched
863 */
864 function sq_findnxreg($body, $offset, $reg){
865 $me = "sq_findnxreg";
866 $matches = Array();
867 $retarr = Array();
868 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
869 if (!$matches{0}){
870 $retarr = false;
871 } else {
872 $retarr{0} = $offset + strlen($matches{1});
873 $retarr{1} = $matches{1};
874 $retarr{2} = $matches{2};
875 }
876 return $retarr;
877 }
878
879 /**
880 * This function looks for the next tag.
881 *
882 * @param $body String where to look for the next tag.
883 * @param $offset Start looking from here.
884 * @return false if no more tags exist in the body, or
885 * an array with the following members:
886 * - string with the name of the tag
887 * - array with attributes and their values
888 * - integer with tag type (1, 2, or 3)
889 * - integer where the tag starts (starting "<")
890 * - integer where the tag ends (ending ">")
891 * first three members will be false, if the tag is invalid.
892 */
893 function sq_getnxtag($body, $offset){
894 $me = "sq_getnxtag";
895 if ($offset > strlen($body)){
896 return false;
897 }
898 $lt = sq_findnxstr($body, $offset, "<");
899 if ($lt == strlen($body)){
900 return false;
901 }
902 /**
903 * We are here:
904 * blah blah <tag attribute="value">
905 * \---------^
906 */
907 $pos = sq_skipspace($body, $lt+1);
908 if ($pos >= strlen($body)){
909 return Array(false, false, false, $lt, strlen($body));
910 }
911 /**
912 * There are 3 kinds of tags:
913 * 1. Opening tag, e.g.:
914 * <a href="blah">
915 * 2. Closing tag, e.g.:
916 * </a>
917 * 3. XHTML-style content-less tag, e.g.:
918 * <img src="blah"/>
919 */
920 $tagtype = false;
921 switch (substr($body, $pos, 1)){
922 case "/":
923 $tagtype = 2;
924 $pos++;
925 break;
926 case "!":
927 /**
928 * A comment or an SGML declaration.
929 */
930 if (substr($body, $pos+1, 2) == "--"){
931 $gt = strpos($body, "-->", $pos);
932 if ($gt === false){
933 $gt = strlen($body);
934 } else {
935 $gt += 2;
936 }
937 return Array(false, false, false, $lt, $gt);
938 } else {
939 $gt = sq_findnxstr($body, $pos, ">");
940 return Array(false, false, false, $lt, $gt);
941 }
942 break;
943 default:
944 /**
945 * Assume tagtype 1 for now. If it's type 3, we'll switch values
946 * later.
947 */
948 $tagtype = 1;
949 break;
950 }
951
952 $tag_start = $pos;
953 $tagname = '';
954 /**
955 * Look for next [\W-_], which will indicate the end of the tag name.
956 */
957 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
958 if ($regary == false){
959 return Array(false, false, false, $lt, strlen($body));
960 }
961 list($pos, $tagname, $match) = $regary;
962 $tagname = strtolower($tagname);
963
964 /**
965 * $match can be either of these:
966 * '>' indicating the end of the tag entirely.
967 * '\s' indicating the end of the tag name.
968 * '/' indicating that this is type-3 xhtml tag.
969 *
970 * Whatever else we find there indicates an invalid tag.
971 */
972 switch ($match){
973 case "/":
974 /**
975 * This is an xhtml-style tag with a closing / at the
976 * end, like so: <img src="blah"/>. Check if it's followed
977 * by the closing bracket. If not, then this tag is invalid
978 */
979 if (substr($body, $pos, 2) == "/>"){
980 $pos++;
981 $tagtype = 3;
982 } else {
983 $gt = sq_findnxstr($body, $pos, ">");
984 $retary = Array(false, false, false, $lt, $gt);
985 return $retary;
986 }
987 case ">":
988 return Array($tagname, false, $tagtype, $lt, $pos);
989 break;
990 default:
991 /**
992 * Check if it's whitespace
993 */
994 if (preg_match("/\s/", $match)){
995 } else {
996 /**
997 * This is an invalid tag! Look for the next closing ">".
998 */
999 $gt = sq_findnxstr($body, $offset, ">");
1000 return Array(false, false, false, $lt, $gt);
1001 }
1002 }
1003
1004 /**
1005 * At this point we're here:
1006 * <tagname attribute='blah'>
1007 * \-------^
1008 *
1009 * At this point we loop in order to find all attributes.
1010 */
1011 $attname = '';
1012 $atttype = false;
1013 $attary = Array();
1014
1015 while ($pos <= strlen($body)){
1016 $pos = sq_skipspace($body, $pos);
1017 if ($pos == strlen($body)){
1018 /**
1019 * Non-closed tag.
1020 */
1021 return Array(false, false, false, $lt, $pos);
1022 }
1023 /**
1024 * See if we arrived at a ">" or "/>", which means that we reached
1025 * the end of the tag.
1026 */
1027 $matches = Array();
1028 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1029 /**
1030 * Yep. So we did.
1031 */
1032 $pos += strlen($matches{1});
1033 if ($matches{2} == "/>"){
1034 $tagtype = 3;
1035 $pos++;
1036 }
1037 return Array($tagname, $attary, $tagtype, $lt, $pos);
1038 }
1039
1040 /**
1041 * There are several types of attributes, with optional
1042 * [:space:] between members.
1043 * Type 1:
1044 * attrname[:space:]=[:space:]'CDATA'
1045 * Type 2:
1046 * attrname[:space:]=[:space:]"CDATA"
1047 * Type 3:
1048 * attr[:space:]=[:space:]CDATA
1049 * Type 4:
1050 * attrname
1051 *
1052 * We leave types 1 and 2 the same, type 3 we check for
1053 * '"' and convert to "&quot" if needed, then wrap in
1054 * double quotes. Type 4 we convert into:
1055 * attrname="yes".
1056 */
1057 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1058 if ($regary == false){
1059 /**
1060 * Looks like body ended before the end of tag.
1061 */
1062 return Array(false, false, false, $lt, strlen($body));
1063 }
1064 list($pos, $attname, $match) = $regary;
1065 $attname = strtolower($attname);
1066 /**
1067 * We arrived at the end of attribute name. Several things possible
1068 * here:
1069 * '>' means the end of the tag and this is attribute type 4
1070 * '/' if followed by '>' means the same thing as above
1071 * '\s' means a lot of things -- look what it's followed by.
1072 * anything else means the attribute is invalid.
1073 */
1074 switch($match){
1075 case "/":
1076 /**
1077 * This is an xhtml-style tag with a closing / at the
1078 * end, like so: <img src="blah"/>. Check if it's followed
1079 * by the closing bracket. If not, then this tag is invalid
1080 */
1081 if (substr($body, $pos, 2) == "/>"){
1082 $pos++;
1083 $tagtype = 3;
1084 } else {
1085 $gt = sq_findnxstr($body, $pos, ">");
1086 $retary = Array(false, false, false, $lt, $gt);
1087 return $retary;
1088 }
1089 case ">":
1090 $attary{$attname} = '"yes"';
1091 return Array($tagname, $attary, $tagtype, $lt, $pos);
1092 break;
1093 default:
1094 /**
1095 * Skip whitespace and see what we arrive at.
1096 */
1097 $pos = sq_skipspace($body, $pos);
1098 $char = substr($body, $pos, 1);
1099 /**
1100 * Two things are valid here:
1101 * '=' means this is attribute type 1 2 or 3.
1102 * \w means this was attribute type 4.
1103 * anything else we ignore and re-loop. End of tag and
1104 * invalid stuff will be caught by our checks at the beginning
1105 * of the loop.
1106 */
1107 if ($char == "="){
1108 $pos++;
1109 $pos = sq_skipspace($body, $pos);
1110 /**
1111 * Here are 3 possibilities:
1112 * "'" attribute type 1
1113 * '"' attribute type 2
1114 * everything else is the content of tag type 3
1115 */
1116 $quot = substr($body, $pos, 1);
1117 if ($quot == "'"){
1118 $regary = sq_findnxreg($body, $pos+1, "\'");
1119 if ($regary == false){
1120 return Array(false, false, false, $lt, strlen($body));
1121 }
1122 list($pos, $attval, $match) = $regary;
1123 $pos++;
1124 $attary{$attname} = "'" . $attval . "'";
1125 } else if ($quot == '"'){
1126 $regary = sq_findnxreg($body, $pos+1, '\"');
1127 if ($regary == false){
1128 return Array(false, false, false, $lt, strlen($body));
1129 }
1130 list($pos, $attval, $match) = $regary;
1131 $pos++;
1132 $attary{$attname} = '"' . $attval . '"';
1133 } else {
1134 /**
1135 * These are hateful. Look for \s, or >.
1136 */
1137 $regary = sq_findnxreg($body, $pos, "[\s>]");
1138 if ($regary == false){
1139 return Array(false, false, false, $lt, strlen($body));
1140 }
1141 list($pos, $attval, $match) = $regary;
1142 /**
1143 * If it's ">" it will be caught at the top.
1144 */
1145 $attval = preg_replace("/\"/s", "&quot;", $attval);
1146 $attary{$attname} = '"' . $attval . '"';
1147 }
1148 } else if (preg_match("|[\w/>]|", $char)) {
1149 /**
1150 * That was attribute type 4.
1151 */
1152 $attary{$attname} = '"yes"';
1153 } else {
1154 /**
1155 * An illegal character. Find next '>' and return.
1156 */
1157 $gt = sq_findnxstr($body, $pos, ">");
1158 return Array(false, false, false, $lt, $gt);
1159 }
1160 }
1161 }
1162 /**
1163 * The fact that we got here indicates that the tag end was never
1164 * found. Return invalid tag indication so it gets stripped.
1165 */
1166 return Array(false, false, false, $lt, strlen($body));
1167 }
1168
1169 /**
1170 * This function checks attribute values for entity-encoded values
1171 * and returns them translated into 8-bit strings so we can run
1172 * checks on them.
1173 *
1174 * @param $attvalue A string to run entity check against.
1175 * @return Translated value.
1176 */
1177 function sq_deent($attvalue){
1178 $me="sq_deent";
1179 /**
1180 * See if we have to run the checks first. All entities must start
1181 * with "&".
1182 */
1183 if (strpos($attvalue, "&") === false){
1184 return $attvalue;
1185 }
1186 /**
1187 * Check named entities first.
1188 */
1189 $trans = get_html_translation_table(HTML_ENTITIES);
1190 /**
1191 * Leave &quot; in, as it can mess us up.
1192 */
1193 $trans = array_flip($trans);
1194 unset($trans{"&quot;"});
1195 while (list($ent, $val) = each($trans)){
1196 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1197 }
1198 /**
1199 * Now translate numbered entities from 1 to 255 if needed.
1200 */
1201 if (strpos($attvalue, "#") !== false){
1202 $omit = Array(34, 39);
1203 for ($asc=1; $asc<256; $asc++){
1204 if (!in_array($asc, $omit)){
1205 $chr = chr($asc);
1206 $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
1207 $attvalue);
1208 $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
1209 "$chr\\1", $attvalue);
1210 }
1211 }
1212 }
1213 return $attvalue;
1214 }
1215
1216 /**
1217 * This function runs various checks against the attributes.
1218 *
1219 * @param $tagname String with the name of the tag.
1220 * @param $attary Array with all tag attributes.
1221 * @param $rm_attnames See description for sq_sanitize
1222 * @param $bad_attvals See description for sq_sanitize
1223 * @param $add_attr_to_tag See description for sq_sanitize
1224 * @param $message message object
1225 * @param $id message id
1226 * @return Array with modified attributes.
1227 */
1228 function sq_fixatts($tagname,
1229 $attary,
1230 $rm_attnames,
1231 $bad_attvals,
1232 $add_attr_to_tag,
1233 $message,
1234 $id,
1235 $mailbox
1236 ){
1237 $me = "sq_fixatts";
1238 while (list($attname, $attvalue) = each($attary)){
1239 /**
1240 * See if this attribute should be removed.
1241 */
1242 foreach ($rm_attnames as $matchtag=>$matchattrs){
1243 if (preg_match($matchtag, $tagname)){
1244 foreach ($matchattrs as $matchattr){
1245 if (preg_match($matchattr, $attname)){
1246 unset($attary{$attname});
1247 continue;
1248 }
1249 }
1250 }
1251 }
1252 /**
1253 * Remove any entities.
1254 */
1255 $attvalue = sq_deent($attvalue);
1256
1257 /**
1258 * Now let's run checks on the attvalues.
1259 * I don't expect anyone to comprehend this. If you do,
1260 * get in touch with me so I can drive to where you live and
1261 * shake your hand personally. :)
1262 */
1263 foreach ($bad_attvals as $matchtag=>$matchattrs){
1264 if (preg_match($matchtag, $tagname)){
1265 foreach ($matchattrs as $matchattr=>$valary){
1266 if (preg_match($matchattr, $attname)){
1267 /**
1268 * There are two arrays in valary.
1269 * First is matches.
1270 * Second one is replacements
1271 */
1272 list($valmatch, $valrepl) = $valary;
1273 $newvalue =
1274 preg_replace($valmatch, $valrepl, $attvalue);
1275 if ($newvalue != $attvalue){
1276 $attary{$attname} = $newvalue;
1277 }
1278 }
1279 }
1280 }
1281 }
1282 /**
1283 * Turn cid: urls into http-friendly ones.
1284 */
1285 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1286 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
1287 }
1288 }
1289 /**
1290 * See if we need to append any attributes to this tag.
1291 */
1292 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1293 if (preg_match($matchtag, $tagname)){
1294 $attary = array_merge($attary, $addattary);
1295 }
1296 }
1297 return $attary;
1298 }
1299
1300 /**
1301 * This function edits the style definition to make them friendly and
1302 * usable in squirrelmail.
1303 *
1304 * @param $message the message object
1305 * @param $id the message id
1306 * @param $content a string with whatever is between <style> and </style>
1307 * @return a string with edited content.
1308 */
1309 function sq_fixstyle($message, $id, $content){
1310 global $view_unsafe_images;
1311 $me = "sq_fixstyle";
1312 /**
1313 * First look for general BODY style declaration, which would be
1314 * like so:
1315 * body {background: blah-blah}
1316 * and change it to .bodyclass so we can just assign it to a <div>
1317 */
1318 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1319 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1320 /**
1321 * Fix url('blah') declarations.
1322 */
1323 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1324 "url(\\1$secremoveimg\\2)", $content);
1325 /**
1326 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1327 * is false.
1328 */
1329 if (!$view_unsafe_images){
1330 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1331 "url(\\1$secremoveimg\\2)", $content);
1332 }
1333
1334 /**
1335 * Fix urls that refer to cid:
1336 */
1337 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1338 $matches)){
1339 $cidurl = $matches{1};
1340 $httpurl = sq_cid2http($message, $id, $cidurl);
1341 $content = preg_replace("|url\($cidurl\)|si",
1342 "url($httpurl)", $content);
1343 }
1344
1345 /**
1346 * Fix stupid css declarations which lead to vulnerabilities
1347 * in IE.
1348 */
1349 $match = Array('/expression/si',
1350 '/behaviou*r/si',
1351 '/binding/si');
1352 $replace = Array('idiocy', 'idiocy', 'idiocy');
1353 $content = preg_replace($match, $replace, $content);
1354 return $content;
1355 }
1356
1357 /**
1358 * This function converts cid: url's into the ones that can be viewed in
1359 * the browser.
1360 *
1361 * @param $message the message object
1362 * @param $id the message id
1363 * @param $cidurl the cid: url.
1364 * @return a string with a http-friendly url
1365 */
1366 function sq_cid2http($message, $id, $cidurl, $mailbox){
1367 /**
1368 * Get rid of quotes.
1369 */
1370 $quotchar = substr($cidurl, 0, 1);
1371 $cidurl = str_replace($quotchar, "", $cidurl);
1372 $cidurl = substr(trim($cidurl), 4);
1373 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&amp;" .
1374 "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
1375 "&amp;passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1376 return $httpurl;
1377 }
1378
1379 /**
1380 * This function changes the <body> tag into a <div> tag since we
1381 * can't really have a body-within-body.
1382 *
1383 * @param $attary an array of attributes and values of <body>
1384 * @return a modified array of attributes to be set for <div>
1385 */
1386 function sq_body2div($attary){
1387 $me = "sq_body2div";
1388 $divattary = Array("class"=>"'bodyclass'");
1389 $bgcolor="#ffffff";
1390 $text="#000000";
1391 $styledef="";
1392 if (is_array($attary) && sizeof($attary) > 0){
1393 foreach ($attary as $attname=>$attvalue){
1394 $quotchar = substr($attvalue, 0, 1);
1395 $attvalue = str_replace($quotchar, "", $attvalue);
1396 switch ($attname){
1397 case "background":
1398 $styledef .= "background-image: url('$attvalue'); ";
1399 break;
1400 case "bgcolor":
1401 $styledef .= "background-color: $attvalue; ";
1402 break;
1403 case "text":
1404 $styledef .= "color: $attvalue; ";
1405 }
1406 }
1407 if (strlen($styledef) > 0){
1408 $divattary{"style"} = "\"$styledef\"";
1409 }
1410 }
1411 return $divattary;
1412 }
1413
1414 /**
1415 * This is the main function and the one you should actually be calling.
1416 * There are several variables you should be aware of an which need
1417 * special description.
1418 *
1419 * Since the description is quite lengthy, see it here:
1420 * http://www.mricon.com/html/phpfilter.html
1421 *
1422 * @param $body the string with HTML you wish to filter
1423 * @param $tag_list see description above
1424 * @param $rm_tags_with_content see description above
1425 * @param $self_closing_tags see description above
1426 * @param $force_tag_closing see description above
1427 * @param $rm_attnames see description above
1428 * @param $bad_attvals see description above
1429 * @param $add_attr_to_tag see description above
1430 * @param $message message object
1431 * @param $id message id
1432 * @return sanitized html safe to show on your pages.
1433 */
1434 function sq_sanitize($body,
1435 $tag_list,
1436 $rm_tags_with_content,
1437 $self_closing_tags,
1438 $force_tag_closing,
1439 $rm_attnames,
1440 $bad_attvals,
1441 $add_attr_to_tag,
1442 $message,
1443 $id,
1444 $mailbox
1445 ){
1446 $me = "sq_sanitize";
1447 /**
1448 * Normalize rm_tags and rm_tags_with_content.
1449 */
1450 @array_walk($rm_tags, 'sq_casenormalize');
1451 @array_walk($rm_tags_with_content, 'sq_casenormalize');
1452 @array_walk($self_closing_tags, 'sq_casenormalize');
1453 /**
1454 * See if tag_list is of tags to remove or tags to allow.
1455 * false means remove these tags
1456 * true means allow these tags
1457 */
1458 $rm_tags = array_shift($tag_list);
1459 $curpos = 0;
1460 $open_tags = Array();
1461 $trusted = "<!-- begin sanitized html -->\n";
1462 $skip_content = false;
1463 /**
1464 * Take care of netscape's stupid javascript entities like
1465 * &{alert('boo')};
1466 */
1467 $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
1468
1469 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1470 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1471 $free_content = substr($body, $curpos, $lt-$curpos);
1472 /**
1473 * Take care of <style>
1474 */
1475 if ($tagname == "style" && $tagtype == 2){
1476 /**
1477 * This is a closing </style>. Edit the
1478 * content before we apply it.
1479 */
1480 $free_content = sq_fixstyle($message, $id, $free_content);
1481 }
1482 if ($skip_content == false){
1483 $trusted .= $free_content;
1484 } else {
1485 }
1486 if ($tagname != FALSE){
1487 if ($tagtype == 2){
1488 if ($skip_content == $tagname){
1489 /**
1490 * Got to the end of tag we needed to remove.
1491 */
1492 $tagname = false;
1493 $skip_content = false;
1494 } else {
1495 if ($skip_content == false){
1496 if ($tagname == "body"){
1497 $tagname = "div";
1498 } else {
1499 if (isset($open_tags{$tagname}) &&
1500 $open_tags{$tagname} > 0){
1501 $open_tags{$tagname}--;
1502 } else {
1503 $tagname = false;
1504 }
1505 }
1506 } else {
1507 }
1508 }
1509 } else {
1510 /**
1511 * $rm_tags_with_content
1512 */
1513 if ($skip_content == false){
1514 /**
1515 * See if this is a self-closing type and change
1516 * tagtype appropriately.
1517 */
1518 if ($tagtype == 1
1519 && in_array($tagname, $self_closing_tags)){
1520 $tagtype=3;
1521 }
1522 /**
1523 * See if we should skip this tag and any content
1524 * inside it.
1525 */
1526 if ($tagtype == 1 &&
1527 in_array($tagname, $rm_tags_with_content)){
1528 $skip_content = $tagname;
1529 } else {
1530 if (($rm_tags == false
1531 && in_array($tagname, $tag_list)) ||
1532 ($rm_tags == true &&
1533 !in_array($tagname, $tag_list))){
1534 $tagname = false;
1535 } else {
1536 if ($tagtype == 1){
1537 if (isset($open_tags{$tagname})){
1538 $open_tags{$tagname}++;
1539 } else {
1540 $open_tags{$tagname}=1;
1541 }
1542 }
1543 /**
1544 * This is where we run other checks.
1545 */
1546 if (is_array($attary) && sizeof($attary) > 0){
1547 $attary = sq_fixatts($tagname,
1548 $attary,
1549 $rm_attnames,
1550 $bad_attvals,
1551 $add_attr_to_tag,
1552 $message,
1553 $id,
1554 $mailbox
1555 );
1556 }
1557 /**
1558 * Convert body into div.
1559 */
1560 if ($tagname == "body"){
1561 $tagname = "div";
1562 $attary = sq_body2div($attary, $message, $id);
1563 }
1564 }
1565 }
1566 } else {
1567 }
1568 }
1569 if ($tagname != false && $skip_content == false){
1570 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1571 }
1572 } else {
1573 }
1574 $curpos = $gt+1;
1575 }
1576 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1577 if ($force_tag_closing == true){
1578 foreach ($open_tags as $tagname=>$opentimes){
1579 while ($opentimes > 0){
1580 $trusted .= '</' . $tagname . '>';
1581 $opentimes--;
1582 }
1583 }
1584 $trusted .= "\n";
1585 }
1586 $trusted .= "<!-- end sanitized html -->\n";
1587 return $trusted;
1588 }
1589
1590 /**
1591 * This is a wrapper function to call html sanitizing routines.
1592 *
1593 * @param $body the body of the message
1594 * @param $id the id of the message
1595 * @return a string with html safe to display in the browser.
1596 */
1597 function magicHTML($body, $id, $message, $mailbox = 'INBOX'){
1598 global $attachment_common_show_images, $view_unsafe_images,
1599 $has_unsafe_images;
1600 /**
1601 * Don't display attached images in HTML mode.
1602 */
1603 $attachment_common_show_images = false;
1604 $tag_list = Array(
1605 false,
1606 "object",
1607 "meta",
1608 "html",
1609 "head",
1610 "base"
1611 );
1612
1613 $rm_tags_with_content = Array(
1614 "script",
1615 "applet",
1616 "embed",
1617 "title"
1618 );
1619
1620 $self_closing_tags = Array(
1621 "img",
1622 "br",
1623 "hr",
1624 "input"
1625 );
1626
1627 $force_tag_closing = false;
1628
1629 $rm_attnames = Array(
1630 "/.*/" =>
1631 Array(
1632 "/target/si",
1633 "/^on.*/si",
1634 "/^dynsrc/si",
1635 "/^data.*/si"
1636 )
1637 );
1638
1639 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1640 $bad_attvals = Array(
1641 "/.*/" =>
1642 Array(
1643 "/^src|background/i" =>
1644 Array(
1645 Array(
1646 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1647 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1648 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1649 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1650 ),
1651 Array(
1652 "\\1$secremoveimg\\2",
1653 "\\1$secremoveimg\\2",
1654 "\\1$secremoveimg\\2",
1655 "\\1$secremoveimg\\2"
1656 )
1657 ),
1658 "/^href|action/i" =>
1659 Array(
1660 Array(
1661 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1662 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1663 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1664 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1665 ),
1666 Array(
1667 "\\1#\\2",
1668 "\\1#\\2",
1669 "\\1#\\2",
1670 "\\1#\\2"
1671 )
1672 ),
1673 "/^style/si" =>
1674 Array(
1675 Array(
1676 "/expression/si",
1677 "/binding/si",
1678 "/behaviou*r/si",
1679 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
1680 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1681 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1682 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
1683 ),
1684 Array(
1685 "idiocy",
1686 "idiocy",
1687 "idiocy",
1688 "url(\\1#\\2)",
1689 "url(\\1#\\2)",
1690 "url(\\1#\\2)",
1691 "url(\\1#\\2)"
1692 )
1693 )
1694 )
1695 );
1696 if (!$view_unsafe_images){
1697 /**
1698 * Remove any references to http/https if view_unsafe_images set
1699 * to false.
1700 */
1701 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
1702 '/^([\'\"])\s*https*:.*([\'\"])/si');
1703 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
1704 "\\1$secremoveimg\\2");
1705 array_push($bad_attvals{'/.*/'}{'/^style/si'}[0],
1706 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
1707 array_push($bad_attvals{'/.*/'}{'/^style/si'}[1],
1708 "url(\\1$secremoveimg\\2)");
1709 }
1710
1711 $add_attr_to_tag = Array(
1712 "/^a$/si" => Array('target'=>'"_new"')
1713 );
1714 $trusted = sq_sanitize($body,
1715 $tag_list,
1716 $rm_tags_with_content,
1717 $self_closing_tags,
1718 $force_tag_closing,
1719 $rm_attnames,
1720 $bad_attvals,
1721 $add_attr_to_tag,
1722 $message,
1723 $id,
1724 $mailbox
1725 );
1726 if (preg_match("|$secremoveimg|si", $trusted)){
1727 $has_unsafe_images = true;
1728 }
1729 return $trusted;
1730 }
1731
1732 ?>