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