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