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