Fixed on the fly decoding of base64 attachment. We need to do on the fly
[squirrelmail.git] / functions / mime.php
CommitLineData
59177427 1<?php
2ba13803 2
35586184 3/**
4 * mime.php
5 *
82d304a0 6 * Copyright (c) 1999-2004 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$
d6c32258 13 * @package squirrelmail
35586184 14 */
b74ba498 15
d6c32258 16/** The typical includes... */
b68edc75 17require_once(SM_PATH . 'functions/imap.php');
18require_once(SM_PATH . 'functions/attachment_common.php');
8beafbbc 19
7c7b74b3 20/* -------------------------------------------------------------------------- */
21/* MIME DECODING */
22/* -------------------------------------------------------------------------- */
b74ba498 23
d6c32258 24/**
25 * Get the MIME structure
07c49f57 26 *
d6c32258 27 * This function gets the structure of a message and stores it in the "message" class.
451f74a2 28 * It will return this object for use with all relevant header information and
29 * fully parsed into the standard "message" object format.
30 */
a4a70693 31function mime_structure ($bodystructure, $flags=array()) {
c9d78ab4 32
3d8371be 33 /* Isolate the body structure and remove beginning and end parenthesis. */
a4a70693 34 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
451f74a2 35 $read = trim(substr ($read, 0, -1));
22efa9fb 36 $i = 0;
37 $msg = Message::parseStructure($read,$i);
9de42168 38 if (!is_object($msg)) {
bd9c880b 39 include_once(SM_PATH . 'functions/display_messages.php');
3d8371be 40 global $color, $mailbox;
c96c32f4 41 /* removed urldecode because $_GET is auto urldecoded ??? */
a48eba8f 42 displayPageHeader( $color, $mailbox );
5e8de8b6 43 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
3d8371be 44 $errormessage .= '<BR>'._("the provided bodystructure by your imap-server").':<BR><BR>';
472e7acb 45 $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
9de42168 46 plain_error_message( $errormessage, $color );
3d8371be 47 echo '</body></html>';
9de42168 48 exit;
49 }
a4a70693 50 if (count($flags)) {
7a9e9c89 51 foreach ($flags as $flag) {
52 $char = strtoupper($flag{1});
53 switch ($char) {
3d8371be 54 case 'S':
55 if (strtolower($flag) == '\\seen') {
56 $msg->is_seen = true;
57 }
58 break;
59 case 'A':
60 if (strtolower($flag) == '\\answered') {
61 $msg->is_answered = true;
62 }
63 break;
64 case 'D':
65 if (strtolower($flag) == '\\deleted') {
66 $msg->is_deleted = true;
67 }
68 break;
69 case 'F':
70 if (strtolower($flag) == '\\flagged') {
71 $msg->is_flagged = true;
72 }
73 break;
74 case 'M':
75 if (strtolower($flag) == '$mdnsent') {
76 $msg->is_mdnsent = true;
77 }
78 break;
79 default:
80 break;
7a9e9c89 81 }
82 }
451f74a2 83 }
7a9e9c89 84 // listEntities($msg);
3d8371be 85 return $msg;
451f74a2 86}
b74ba498 87
22efa9fb 88
89
3d8371be 90/* This starts the parsing of a particular structure. It is called recursively,
451f74a2 91 * so it can be passed different structures. It returns an object of type
92 * $message.
93 * First, it checks to see if it is a multipart message. If it is, then it
94 * handles that as it sees is necessary. If it is just a regular entity,
95 * then it parses it and adds the necessary header information (by calling out
96 * to mime_get_elements()
97 */
451f74a2 98
4d592352 99function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
3d8371be 100 /* Do a bit of error correction. If we couldn't find the entity id, just guess
09a4bde3 101 * that it is the first one. That is usually the case anyway.
102 */
7c7b74b3 103
09a4bde3 104 if (!$ent_id) {
08b7f7cc 105 $cmd = "FETCH $id BODY[]";
1035e159 106 } else {
08b7f7cc 107 $cmd = "FETCH $id BODY[$ent_id]";
09a4bde3 108 }
3d8371be 109
4d592352 110 if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
da2415c1 111
6201339c 112 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, TRUE);
77b88425 113 do {
3d8371be 114 $topline = trim(array_shift($data));
115 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
a4a70693 116
451f74a2 117 $wholemessage = implode('', $data);
118 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
3d8371be 119 $ret = substr($wholemessage, 0, $regs[1]);
120 /* There is some information in the content info header that could be important
121 * in order to parse html messages. Let's get them here.
122 */
0600bdf1 123// if ($ret{0} == '<') {
6201339c 124// $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, TRUE);
0600bdf1 125// }
451f74a2 126 } else if (ereg('"([^"]*)"', $topline, $regs)) {
127 $ret = $regs[1];
128 } else {
129 global $where, $what, $mailbox, $passed_id, $startMessage;
3d8371be 130 $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
451f74a2 131 if (isset($where) && isset($what)) {
3d8371be 132 $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
a3daaaf3 133 } else {
3d8371be 134 $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
451f74a2 135 }
e5ea9327 136 $par .= '&amp;response=' . urlencode($response) .
3d8371be 137 '&amp;message=' . urlencode($message) .
138 '&amp;topline=' . urlencode($topline);
a019eeb8 139
346817d4 140 echo '<tt><br>' .
141 '<table width="80%"><tr>' .
142 '<tr><td colspan=2>' .
0e5b61b4 143 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
346817d4 144 '</td></tr>' .
0e5b61b4 145 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
146 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
147 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
148 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
346817d4 149 "</table><BR></tt></font><hr>";
150
6201339c 151 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, TRUE);
451f74a2 152 array_shift($data);
153 $wholemessage = implode('', $data);
a019eeb8 154
346817d4 155 $ret = $wholemessage;
a3daaaf3 156 }
3d8371be 157 return $ret;
451f74a2 158}
d4467150 159
1035e159 160function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding) {
1035e159 161
3d8371be 162 /* Don't kill the connection if the browser is over a dialup
163 * and it would take over 30 seconds to download it.
7e6ca3e8 164 * Dont call set_time_limit in safe mode.
3d8371be 165 */
b7206e1d 166
3d8371be 167 if (!ini_get('safe_mode')) {
b7206e1d 168 set_time_limit(0);
169 }
7c7b74b3 170 /* in case of base64 encoded attachments, do not buffer them.
171 Instead, echo the decoded attachment directly to screen */
172 if (strtolower($encoding) == 'base64') {
173 if (!$ent_id) {
174 $query = "FETCH $id BODY[]";
175 } else {
176 $query = "FETCH $id BODY[$ent_id]";
177 }
6201339c 178 sqimap_run_command($imap_stream,$query,true,$response,$message,TRUE,'sqimap_base64_decode','php://stdout',true);
1d142b8d 179 } else {
7c7b74b3 180 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
181 echo decodeBody($body, $encoding);
1d142b8d 182 }
346817d4 183
da2415c1 184 /*
7c7b74b3 185 TODO, use the same method for quoted printable.
186 However, I assume that quoted printable attachments aren't that large
187 so the performancegain / memory usage drop will be minimal.
188 If we decide to add that then we need to adapt sqimap_fread because
da2415c1 189 we need to split te result on \n and fread doesn't stop at \n. That
7c7b74b3 190 means we also should provide $results from sqimap_fread (by ref) to
191 te function and set $no_return to false. The $filter function for
da2415c1 192 quoted printable should handle unsetting of $results.
7c7b74b3 193 */
da2415c1 194 /*
7c7b74b3 195 TODO 2: find out how we write to the output stream php://stdout. fwrite
196 doesn't work because 'php://stdout isn't a stream.
197 */
198
5d9c6f73 199 return;
200/*
451f74a2 201 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
202 $cnt = 0;
203 $continue = true;
1d142b8d 204 $read = fgets ($imap_stream,8192);
205
206
451f74a2 207 // This could be bad -- if the section has sqimap_session_id() . ' OK'
208 // or similar, it will kill the download.
1d142b8d 209 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
5d9c6f73 210 if (trim($read) == ')==') {
211 $read1 = $read;
212 $read = fgets ($imap_stream,4096);
213 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
214 return;
215 } else {
216 echo decodeBody($read1, $encoding) .
217 decodeBody($read, $encoding);
218 }
219 } else if ($cnt) {
220 echo decodeBody($read, $encoding);
221 }
222 $read = fgets ($imap_stream,4096);
223 $cnt++;
1d142b8d 224// break;
451f74a2 225 }
5d9c6f73 226*/
451f74a2 227}
beb9e459 228
451f74a2 229/* -[ END MIME DECODING ]----------------------------------------------------------- */
d4467150 230
3d8371be 231/* This is here for debugging purposes. It will print out a list
232 * of all the entity IDs that are in the $message object.
233 */
451f74a2 234function listEntities ($message) {
3d8371be 235 if ($message) {
236 echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br>';
237 for ($i = 0; isset($message->entities[$i]); $i++) {
238 echo "$i : ";
239 $msg = listEntities($message->entities[$i]);
240
241 if ($msg) {
242 echo "return: ";
243 return $msg;
244 }
245 }
a4a70693 246 }
451f74a2 247}
f0c4dc12 248
f792c641 249function getPriorityStr($priority) {
3d8371be 250 $priority_level = substr($priority,0,1);
251
252 switch($priority_level) {
253 /* Check for a higher then normal priority. */
254 case '1':
255 case '2':
256 $priority_string = _("High");
257 break;
258
259 /* Check for a lower then normal priority. */
260 case '4':
261 case '5':
262 $priority_string = _("Low");
263 break;
264
265 /* Check for a normal priority. */
266 case '3':
267 default:
268 $priority_level = '3';
269 $priority_string = _("Normal");
270 break;
271
272 }
273 return $priority_string;
f792c641 274}
275
451f74a2 276/* returns a $message object for a particular entity id */
277function getEntity ($message, $ent_id) {
a4a70693 278 return $message->getEntity($ent_id);
451f74a2 279}
8beafbbc 280
3d8371be 281/* translateText
da4c66e8 282 * Extracted from strings.php 23/03/2002
283 */
284
285function translateText(&$body, $wrap_at, $charset) {
3d8371be 286 global $where, $what; /* from searching */
287 global $color; /* color theme */
da4c66e8 288
b68edc75 289 require_once(SM_PATH . 'functions/url_parser.php');
da4c66e8 290
291 $body_ary = explode("\n", $body);
da4c66e8 292 for ($i=0; $i < count($body_ary); $i++) {
293 $line = $body_ary[$i];
294 if (strlen($line) - 2 >= $wrap_at) {
295 sqWordWrap($line, $wrap_at);
296 }
297 $line = charset_decode($charset, $line);
298 $line = str_replace("\t", ' ', $line);
299
300 parseUrl ($line);
301
3d8371be 302 $quotes = 0;
da4c66e8 303 $pos = 0;
3d8371be 304 $j = strlen($line);
da4c66e8 305
3d8371be 306 while ($pos < $j) {
da4c66e8 307 if ($line[$pos] == ' ') {
3d8371be 308 $pos++;
da4c66e8 309 } else if (strpos($line, '&gt;', $pos) === $pos) {
310 $pos += 4;
3d8371be 311 $quotes++;
da4c66e8 312 } else {
313 break;
314 }
315 }
3d8371be 316
83c94382 317 if ($quotes % 2) {
3d8371be 318 if (!isset($color[13])) {
da4c66e8 319 $color[13] = '#800000';
320 }
4c25967c 321 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
322 } elseif ($quotes) {
323 if (!isset($color[14])) {
324 $color[14] = '#FF0000';
325 }
326 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
da4c66e8 327 }
3d8371be 328
da4c66e8 329 $body_ary[$i] = $line;
330 }
331 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
332}
333
451f74a2 334/* This returns a parsed string called $body. That string can then
3d8371be 335 * be displayed as the actual message in the HTML. It contains
336 * everything needed, including HTML Tags, Attachments at the
337 * bottom, etc.
338 */
b3af12ef 339function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
3d8371be 340 /* This if statement checks for the entity to show as the
341 * primary message. To add more of them, just put them in the
342 * order that is their priority.
343 */
008989da 344 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
23f617b8 345 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
08b7f7cc 346 global $languages, $squirrelmail_language;
77bfbd2e 347
5262d9a6 348 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
349 $view_unsafe_images = false;
77bfbd2e 350 }
d03c24f4 351
cc34b00d 352 $body = '';
23bcec6f 353 $urlmailbox = urlencode($mailbox);
451f74a2 354 $body_message = getEntity($message, $ent_num);
355 if (($body_message->header->type0 == 'text') ||
356 ($body_message->header->type0 == 'rfc822')) {
3d8371be 357 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
451f74a2 358 $body = decodeBody($body, $body_message->header->encoding);
e842b215 359
360 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
361 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
362 if (mb_detect_encoding($body) != 'ASCII') {
363 $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
364 }
365 }
451f74a2 366 $hookResults = do_hook("message_body", $body);
367 $body = $hookResults[1];
23bcec6f 368
3d8371be 369 /* If there are other types that shouldn't be formatted, add
370 * them here.
371 */
372
451f74a2 373 if ($body_message->header->type1 == 'html') {
3d8371be 374 if ($show_html_default <> 1) {
85015544 375 $entity_conv = array('&nbsp;' => ' ',
3d8371be 376 '<p>' => "\n",
3d8371be 377 '<P>' => "\n",
aad8203f 378 '<br>' => "\n",
3d8371be 379 '<BR>' => "\n",
aad8203f 380 '<br />' => "\n",
381 '<BR />' => "\n",
85015544 382 '&gt;' => '>',
383 '&lt;' => '<');
85015544 384 $body = strtr($body, $entity_conv);
3d8371be 385 $body = strip_tags($body);
85015544 386 $body = trim($body);
387 translateText($body, $wrap_at,
807e884a 388 $body_message->header->getParameter('charset'));
a3daaaf3 389 } else {
3d8371be 390 $body = magicHTML($body, $id, $message, $mailbox);
a3daaaf3 391 }
451f74a2 392 } else {
3d8371be 393 translateText($body, $wrap_at,
394 $body_message->header->getParameter('charset'));
451f74a2 395 }
83cf04bd 396 $link = 'passed_id=' . $id . '&amp;ent_id='.$ent_num.
08b7f7cc 397 '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
da2415c1 398 '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
08b7f7cc 399 if (isset($passed_ent_id)) {
400 $link .= '&amp;passed_ent_id='.$passed_ent_id;
401 }
8d863f64 402 $body .= '<center><small><a href="download.php?absolute_dl=true&amp;' .
83cf04bd 403 $link . '">' . _("Download this as a file") . '</a>';
7aad7b77 404 if ($view_unsafe_images) {
23f617b8 405 $text = _("Hide Unsafe Images");
7aad7b77 406 } else {
08b7f7cc 407 if (isset($has_unsafe_images) && $has_unsafe_images) {
408 $link .= '&amp;view_unsafe_images=1';
409 $text = _("View Unsafe Images");
410 } else {
411 $text = '';
412 }
3d8371be 413 }
83cf04bd 414 if($text != '') {
415 $body .= '&nbsp;|&nbsp;<a href="read_body.php?' . $link . '">' . $text . '</a>';
416 }
417 $body .= '</small></center><br>' . "\n";
3d8371be 418 }
419 return $body;
451f74a2 420}
b74ba498 421
23bcec6f 422
423function formatAttachments($message, $exclude_id, $mailbox, $id) {
b583c3e8 424 global $where, $what, $startMessage, $color;
77b88425 425 static $ShownHTML = 0;
451f74a2 426
23bcec6f 427 $att_ar = $message->getAttachments($exclude_id);
451f74a2 428
23bcec6f 429 if (!count($att_ar)) return '';
2e25760a 430
8f5425ec 431 $attachments = '';
2e25760a 432
23bcec6f 433 $urlMailbox = urlencode($mailbox);
434
435 foreach ($att_ar as $att) {
fdc9d9b5 436 $ent = $att->entity_id;
2e25760a 437 $header = $att->header;
f0c4dc12 438 $type0 = strtolower($header->type0);
439 $type1 = strtolower($header->type1);
2e25760a 440 $name = '';
3d8371be 441 $links['download link']['text'] = _("download");
6b04287c 442 $links['download link']['href'] = SM_PATH .
443 "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
2e25760a 444 $ImageURL = '';
445 if ($type0 =='message' && $type1 == 'rfc822') {
6b04287c 446 $default_page = SM_PATH . 'src/read_body.php';
2e25760a 447 $rfc822_header = $att->rfc822_header;
098ea084 448 $filename = $rfc822_header->subject;
6cc08d8b 449 if (trim( $filename ) == '') {
450 $filename = 'untitled-[' . $ent . ']' ;
08b7f7cc 451 }
2e25760a 452 $from_o = $rfc822_header->from;
453 if (is_object($from_o)) {
04ea844e 454 $from_name = decodeHeader($from_o->getAddress(false));
2e25760a 455 } else {
456 $from_name = _("Unknown sender");
f0c4dc12 457 }
3d8371be 458 $description = $from_name;
23bcec6f 459 } else {
6b04287c 460 $default_page = SM_PATH . 'src/download.php';
3d8371be 461 if (is_object($header->disposition)) {
098ea084 462 $filename = $header->disposition->getProperty('filename');
3d8371be 463 if (trim($filename) == '') {
464 $name = decodeHeader($header->disposition->getProperty('name'));
465 if (trim($name) == '') {
098ea084 466 $name = $header->getParameter('name');
1035e159 467 if(trim($name) == '') {
468 if (trim( $header->id ) == '') {
469 $filename = 'untitled-[' . $ent . ']' ;
470 } else {
471 $filename = 'cid: ' . $header->id;
08b7f7cc 472 }
3d8371be 473 } else {
08b7f7cc 474 $filename = $name;
3d8371be 475 }
476 } else {
477 $filename = $name;
478 }
479 }
480 } else {
08b7f7cc 481 $filename = $header->getParameter('name');
482 if (!trim($filename)) {
483 if (trim( $header->id ) == '') {
484 $filename = 'untitled-[' . $ent . ']' ;
485 } else {
486 $filename = 'cid: ' . $header->id;
487 }
488 }
489 }
f810c0b2 490 if ($header->description) {
098ea084 491 $description = decodeHeader($header->description);
f810c0b2 492 } else {
3d8371be 493 $description = '';
494 }
2e25760a 495 }
496
497 $display_filename = $filename;
3d8371be 498 if (isset($passed_ent_id)) {
499 $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
500 } else {
501 $passed_ent_id_link = '';
502 }
503 $defaultlink = $default_page . "?startMessage=$startMessage"
2e25760a 504 . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
6b04287c 505 . '&amp;ent_id='.$ent.$passed_ent_id_link;
2e25760a 506 if ($where && $what) {
09f4707e 507 $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
2e25760a 508 }
3d8371be 509 /* This executes the attachment hook with a specific MIME-type.
510 * If that doesn't have results, it tries if there's a rule
511 * for a more generic type.
512 */
513 $hookresults = do_hook("attachment $type0/$type1", $links,
514 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
515 $display_filename, $where, $what);
516 if(count($hookresults[1]) <= 1) {
517 $hookresults = do_hook("attachment $type0/*", $links,
518 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
519 $display_filename, $where, $what);
2e25760a 520 }
451f74a2 521
3d8371be 522 $links = $hookresults[1];
523 $defaultlink = $hookresults[6];
77b88425 524
2e25760a 525 $attachments .= '<TR><TD>' .
098ea084 526 '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A>&nbsp;</TD>' .
23bcec6f 527 '<TD><SMALL><b>' . show_readable_size($header->size) .
77b88425 528 '</b>&nbsp;&nbsp;</small></TD>' .
529 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
530 '<TD><SMALL>';
f810c0b2 531 $attachments .= '<b>' . $description . '</b>';
2e25760a 532 $attachments .= '</SMALL></TD><TD><SMALL>&nbsp;';
b74ba498 533
3d8371be 534 $skipspaces = 1;
535 foreach ($links as $val) {
536 if ($skipspaces) {
537 $skipspaces = 0;
2e25760a 538 } else {
539 $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
77b88425 540 }
3d8371be 541 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
2e25760a 542 }
3d8371be 543 unset($links);
2e25760a 544 $attachments .= "</TD></TR>\n";
545 }
9ad17edb 546 $attachmentadd = do_hook_function('attachments_bottom',$attachments);
547 if ($attachmentadd != '')
548 $attachments = $attachmentadd;
2e25760a 549 return $attachments;
451f74a2 550}
b74ba498 551
7c7b74b3 552function sqimap_base64_decode(&$string) {
7c0ec1d8 553
554 // base64 enoded data goes in pairs of 4 bytes. To achieve on the
555 // fly decoding (to reduce memory usage) you have to check if the
556 // data has incomplete pairs
557
558 // remove the noise in order to check if the 4 bytes pairs are complete
559 $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
560
561 $sStringRem = '';
562 $iMod = strlen($string) % 4;
563 if ($iMod) {
564 $sStringRem = substr($string,-$iMod);
565 // check if $sStringRem contains padding characters
566 if (substr($sStringRem,-1) != '=') {
567 $string = substr($string,0,-$iMod);
568 } else {
569 $sStringRem = '';
570 }
571 }
7c7b74b3 572 $string = base64_decode($string);
7c0ec1d8 573 return $sStringRem;
7c7b74b3 574}
575
7c0ec1d8 576
3d8371be 577/* This function decodes the body depending on the encoding type. */
451f74a2 578function decodeBody($body, $encoding) {
3d8371be 579 global $show_html_default;
83be314a 580
b583c3e8 581 $body = str_replace("\r\n", "\n", $body);
582 $encoding = strtolower($encoding);
3d8371be 583
5166f86a 584 $encoding_handler = do_hook_function('decode_body', $encoding);
585
586
587 // plugins get first shot at decoding the body
588 //
589 if (!empty($encoding_handler) && function_exists($encoding_handler)) {
590 $body = $encoding_handler('decode', $body);
591
592 } else if ($encoding == 'quoted-printable' ||
3d8371be 593 $encoding == 'quoted_printable') {
b583c3e8 594 $body = quoted_printable_decode($body);
3d8371be 595
b583c3e8 596 while (ereg("=\n", $body)) {
597 $body = ereg_replace ("=\n", '', $body);
598 }
3d8371be 599
b583c3e8 600 } else if ($encoding == 'base64') {
601 $body = base64_decode($body);
602 }
3d8371be 603
b583c3e8 604 // All other encodings are returned raw.
3d8371be 605 return $body;
451f74a2 606}
607
9f7f68c3 608/**
609 * Decodes headers
610 *
451f74a2 611 * This functions decode strings that is encoded according to
612 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
79e07c7e 613 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
9f7f68c3 614 *
615 * @param string $string header string that has to be made readable
616 * @param boolean $utfencode change message in order to be readable on user's charset. defaults to true
617 * @param boolean $htmlsave preserve spaces and sanitize html special characters. defaults to true
618 * @param boolean $decide decide if string can be utfencoded. defaults to false
619 * @return string decoded header string
451f74a2 620 */
9f7f68c3 621function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
d7448126 622 global $languages, $squirrelmail_language;
79e07c7e 623 if (is_array($string)) {
624 $string = implode("\n", $string);
625 }
da2415c1 626
10dec454 627 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
628 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
6fbd125b 629 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
08b7f7cc 630 // Do we need to return at this point?
631 // return $string;
83be314a 632 }
79e07c7e 633 $i = 0;
08b7f7cc 634 $iLastMatch = -2;
db65b6b0 635 $encoded = true;
0a06275a 636
098ea084 637 $aString = explode(' ',$string);
08b7f7cc 638 $ret = '';
098ea084 639 foreach ($aString as $chunk) {
358a78a1 640 if ($encoded && $chunk === '') {
08b7f7cc 641 continue;
358a78a1 642 } elseif ($chunk === '') {
08b7f7cc 643 $ret .= ' ';
644 continue;
645 }
098ea084 646 $encoded = false;
08b7f7cc 647 /* if encoded words are not separated by a linear-space-white we still catch them */
648 $j = $i-1;
7e6ca3e8 649
08b7f7cc 650 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
651 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
652 if ($iLastMatch !== $j) {
653 if ($htmlsave) {
9f7f68c3 654 $ret .= '&#32;';
08b7f7cc 655 } else {
656 $ret .= ' ';
657 }
658 }
659 $iLastMatch = $i;
660 $j = $i;
661 $ret .= $res[1];
098ea084 662 $encoding = ucfirst($res[3]);
663 switch ($encoding)
664 {
665 case 'B':
666 $replace = base64_decode($res[4]);
08b7f7cc 667 $ret .= charset_decode($res[2],$replace);
098ea084 668 break;
669 case 'Q':
098ea084 670 $replace = str_replace('_', ' ', $res[4]);
da2415c1 671 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
79e07c7e 672 $replace);
8d863f64 673 /* decide about valid decoding */
674 if ($decide && is_conversion_safe($res[2])) {
675 $utfencode=true;
676 $can_be_decoded=true;
677 } else {
678 $can_be_decoded=false;
679 }
098ea084 680 /* Only encode into entities by default. Some places
681 * don't need the encoding, like the compose form.
682 */
683 if ($utfencode) {
684 $replace = charset_decode($res[2], $replace);
685 } else {
686 if ($htmlsave) {
c96c32f4 687 $replace = htmlspecialchars($replace);
098ea084 688 }
689 }
08b7f7cc 690 $ret .= $replace;
098ea084 691 break;
692 default:
693 break;
79e07c7e 694 }
098ea084 695 $chunk = $res[5];
696 $encoded = true;
08b7f7cc 697 }
698 if (!$encoded) {
699 if ($htmlsave) {
9f7f68c3 700 $ret .= '&#32;';
08b7f7cc 701 } else {
702 $ret .= ' ';
da2415c1 703 }
08b7f7cc 704 }
dc3d13a7 705
706 if (!$encoded && $htmlsave) {
707 $ret .= htmlspecialchars($chunk);
708 } else {
709 $ret .= $chunk;
710 }
098ea084 711 ++$i;
712 }
fd81e884 713 /* remove the first added space */
714 if ($ret) {
715 if ($htmlsave) {
9f7f68c3 716 $ret = substr($ret,5);
fd81e884 717 } else {
718 $ret = substr($ret,1);
719 }
720 }
da2415c1 721
08b7f7cc 722 return $ret;
451f74a2 723}
724
9f7f68c3 725/**
726 * Encodes header as quoted-printable
727 *
451f74a2 728 * Encode a string according to RFC 1522 for use in headers if it
729 * contains 8-bit characters or anything that looks like it should
730 * be encoded.
9f7f68c3 731 *
732 * @param string $string header string, that has to be encoded
733 * @return string quoted-printable encoded string
451f74a2 734 */
735function encodeHeader ($string) {
6fbd125b 736 global $default_charset, $languages, $squirrelmail_language;
83be314a 737
10dec454 738 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
739 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
6fbd125b 740 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
83be314a 741 }
9f7f68c3 742 // instead of removing nbsp here, we don't add it in decodeHeader
743 // if (strtolower($default_charset) == 'iso-8859-1') {
744 // $string = str_replace("\240",' ',$string);
745 //}
793cc001 746
451f74a2 747 // Encode only if the string contains 8-bit characters or =?
3d8371be 748 $j = strlen($string);
098ea084 749 $max_l = 75 - strlen($default_charset) - 7;
750 $aRet = array();
451f74a2 751 $ret = '';
c96c32f4 752 $iEncStart = $enc_init = false;
0d53f0f9 753 $cur_l = $iOffset = 0;
3d8371be 754 for($i = 0; $i < $j; ++$i) {
c96c32f4 755 switch($string{$i})
756 {
757 case '=':
758 case '<':
759 case '>':
760 case ',':
761 case '?':
762 case '_':
763 if ($iEncStart === false) {
764 $iEncStart = $i;
765 }
766 $cur_l+=3;
767 if ($cur_l > ($max_l-2)) {
08b7f7cc 768 /* if there is an stringpart that doesn't need encoding, add it */
c96c32f4 769 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
770 $aRet[] = "=?$default_charset?Q?$ret?=";
771 $iOffset = $i;
772 $cur_l = 0;
773 $ret = '';
774 $iEncStart = false;
775 } else {
776 $ret .= sprintf("=%02X",ord($string{$i}));
777 }
778 break;
779 case '(':
780 case ')':
781 if ($iEncStart !== false) {
08b7f7cc 782 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
c96c32f4 783 $aRet[] = "=?$default_charset?Q?$ret?=";
784 $iOffset = $i;
785 $cur_l = 0;
786 $ret = '';
787 $iEncStart = false;
788 }
789 break;
790 case ' ':
791 if ($iEncStart !== false) {
098ea084 792 $cur_l++;
793 if ($cur_l > $max_l) {
08b7f7cc 794 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
c96c32f4 795 $aRet[] = "=?$default_charset?Q?$ret?=";
796 $iOffset = $i;
797 $cur_l = 0;
798 $ret = '';
799 $iEncStart = false;
08b7f7cc 800 } else {
c96c32f4 801 $ret .= '_';
802 }
803 }
804 break;
805 default:
806 $k = ord($string{$i});
807 if ($k > 126) {
808 if ($iEncStart === false) {
325978ac 809 // do not start encoding in the middle of a string, also take the rest of the word.
810 $sLeadString = substr($string,0,$i);
811 $aLeadString = explode(' ',$sLeadString);
da2415c1 812 $sToBeEncoded = array_pop($aLeadString);
325978ac 813 $iEncStart = $i - strlen($sToBeEncoded);
814 $ret .= $sToBeEncoded;
815 $cur_l += strlen($sToBeEncoded);
c96c32f4 816 }
817 $cur_l += 3;
08b7f7cc 818 /* first we add the encoded string that reached it's max size */
c96c32f4 819 if ($cur_l > ($max_l-2)) {
08b7f7cc 820 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
821 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
c96c32f4 822 $cur_l = 3;
823 $ret = '';
824 $iOffset = $i;
08b7f7cc 825 $iEncStart = $i;
c96c32f4 826 }
08b7f7cc 827 $enc_init = true;
c96c32f4 828 $ret .= sprintf("=%02X", $k);
829 } else {
830 if ($iEncStart !== false) {
098ea084 831 $cur_l++;
832 if ($cur_l > $max_l) {
08b7f7cc 833 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
c96c32f4 834 $aRet[] = "=?$default_charset?Q?$ret?=";
835 $iEncStart = false;
836 $iOffset = $i;
837 $cur_l = 0;
098ea084 838 $ret = '';
08b7f7cc 839 } else {
c96c32f4 840 $ret .= $string{$i};
841 }
3d8371be 842 }
c96c32f4 843 }
844 break;
f7b3ba37 845 }
451f74a2 846 }
793cc001 847
c96c32f4 848 if ($enc_init) {
849 if ($iEncStart !== false) {
850 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
851 $aRet[] = "=?$default_charset?Q?$ret?=";
852 } else {
853 $aRet[] = substr($string,$iOffset);
854 }
855 $string = implode('',$aRet);
451f74a2 856 }
3d8371be 857 return $string;
451f74a2 858}
b74ba498 859
691a2d25 860/* This function trys to locate the entity_id of a specific mime element */
3d8371be 861function find_ent_id($id, $message) {
a171b359 862 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
863 if ($message->entities[$i]->header->type0 == 'multipart') {
3d8371be 864 $ret = find_ent_id($id, $message->entities[$i]);
451f74a2 865 } else {
3d8371be 866 if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
d8cffbab 867// if (sq_check_save_extension($message->entities[$i])) {
a171b359 868 return $message->entities[$i]->entity_id;
da2415c1 869// }
3d8371be 870 }
a3daaaf3 871 }
451f74a2 872 }
3d8371be 873 return $ret;
451f74a2 874}
a3daaaf3 875
e5e9381a 876function sq_check_save_extension($message) {
877 $filename = $message->getFilename();
878 $ext = substr($filename, strrpos($filename,'.')+1);
879 $save_extensions = array('jpg','jpeg','gif','png','bmp');
3d8371be 880 return in_array($ext, $save_extensions);
e5e9381a 881}
882
883
691a2d25 884/**
885 ** HTMLFILTER ROUTINES
886 */
451f74a2 887
2dd879b8 888/**
889 * This function is more or less a wrapper around stripslashes. Apparently
890 * Explorer is stupid enough to just remove the backslashes and then
891 * execute the content of the attribute as if nothing happened.
892 * Who does that?
893 *
894 * @param attvalue The value of the attribute
895 * @return attvalue The value of the attribute stripslashed.
896 */
897function sq_unbackslash($attvalue){
898 /**
899 * Remove any backslashes. See if there are any first.
900 */
91220ed1 901
2dd879b8 902 if (strstr($attvalue, '\\') !== false){
903 $attvalue = stripslashes($attvalue);
904 }
905 return $attvalue;
906}
907
908/**
909 * Kill any tabs, newlines, or carriage returns. Our friends the
910 * makers of the browser with 95% market value decided that it'd
911 * be funny to make "java[tab]script" be just as good as "javascript".
da2415c1 912 *
2dd879b8 913 * @param attvalue The attribute value before extraneous spaces removed.
914 * @return attvalue The attribute value after extraneous spaces removed.
915 */
916function sq_unspace($attvalue){
917 if (strcspn($attvalue, "\t\r\n") != strlen($attvalue)){
918 $attvalue = str_replace(Array("\t", "\r", "\n"), Array('', '', ''),
919 $attvalue);
920 }
921 return $attvalue;
922}
923
691a2d25 924/**
925 * This function returns the final tag out of the tag name, an array
da2415c1 926 * of attributes, and the type of the tag. This function is called by
691a2d25 927 * sq_sanitize internally.
928 *
929 * @param $tagname the name of the tag.
930 * @param $attary the array of attributes and their values
931 * @param $tagtype The type of the tag (see in comments).
932 * @return a string with the final tag representation.
933 */
934function sq_tagprint($tagname, $attary, $tagtype){
b583c3e8 935 $me = 'sq_tagprint';
3d8371be 936
691a2d25 937 if ($tagtype == 2){
938 $fulltag = '</' . $tagname . '>';
939 } else {
940 $fulltag = '<' . $tagname;
941 if (is_array($attary) && sizeof($attary)){
942 $atts = Array();
943 while (list($attname, $attvalue) = each($attary)){
944 array_push($atts, "$attname=$attvalue");
945 }
946 $fulltag .= ' ' . join(" ", $atts);
947 }
948 if ($tagtype == 3){
b583c3e8 949 $fulltag .= ' /';
691a2d25 950 }
b583c3e8 951 $fulltag .= '>';
451f74a2 952 }
691a2d25 953 return $fulltag;
451f74a2 954}
a3daaaf3 955
691a2d25 956/**
957 * A small helper function to use with array_walk. Modifies a by-ref
958 * value and makes it lowercase.
959 *
960 * @param $val a value passed by-ref.
961 * @return void since it modifies a by-ref value.
962 */
963function sq_casenormalize(&$val){
964 $val = strtolower($val);
965}
451f74a2 966
691a2d25 967/**
968 * This function skips any whitespace from the current position within
969 * a string and to the next non-whitespace value.
da2415c1 970 *
691a2d25 971 * @param $body the string
972 * @param $offset the offset within the string where we should start
973 * looking for the next non-whitespace character.
974 * @return the location within the $body where the next
975 * non-whitespace char is located.
976 */
977function sq_skipspace($body, $offset){
b583c3e8 978 $me = 'sq_skipspace';
3d8371be 979 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
691a2d25 980 if (sizeof($matches{1})){
981 $count = strlen($matches{1});
982 $offset += $count;
451f74a2 983 }
691a2d25 984 return $offset;
451f74a2 985}
a3daaaf3 986
691a2d25 987/**
988 * This function looks for the next character within a string. It's
989 * really just a glorified "strpos", except it catches if failures
990 * nicely.
991 *
992 * @param $body The string to look for needle in.
993 * @param $offset Start looking from this position.
994 * @param $needle The character/string to look for.
995 * @return location of the next occurance of the needle, or
996 * strlen($body) if needle wasn't found.
997 */
998function sq_findnxstr($body, $offset, $needle){
3d8371be 999 $me = 'sq_findnxstr';
691a2d25 1000 $pos = strpos($body, $needle, $offset);
1001 if ($pos === FALSE){
1002 $pos = strlen($body);
451f74a2 1003 }
691a2d25 1004 return $pos;
451f74a2 1005}
a3daaaf3 1006
691a2d25 1007/**
1008 * This function takes a PCRE-style regexp and tries to match it
1009 * within the string.
1010 *
1011 * @param $body The string to look for needle in.
1012 * @param $offset Start looking from here.
1013 * @param $reg A PCRE-style regex to match.
1014 * @return Returns a false if no matches found, or an array
1015 * with the following members:
1016 * - integer with the location of the match within $body
1017 * - string with whatever content between offset and the match
1018 * - string with whatever it is we matched
1019 */
1020function sq_findnxreg($body, $offset, $reg){
b583c3e8 1021 $me = 'sq_findnxreg';
691a2d25 1022 $matches = Array();
1023 $retarr = Array();
7d06541f 1024 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
1025 if (!isset($matches{0}) || !$matches{0}){
691a2d25 1026 $retarr = false;
1027 } else {
1028 $retarr{0} = $offset + strlen($matches{1});
1029 $retarr{1} = $matches{1};
1030 $retarr{2} = $matches{2};
1031 }
1032 return $retarr;
1033}
a3daaaf3 1034
691a2d25 1035/**
1036 * This function looks for the next tag.
1037 *
1038 * @param $body String where to look for the next tag.
1039 * @param $offset Start looking from here.
1040 * @return false if no more tags exist in the body, or
1041 * an array with the following members:
1042 * - string with the name of the tag
1043 * - array with attributes and their values
1044 * - integer with tag type (1, 2, or 3)
1045 * - integer where the tag starts (starting "<")
1046 * - integer where the tag ends (ending ">")
1047 * first three members will be false, if the tag is invalid.
1048 */
1049function sq_getnxtag($body, $offset){
b583c3e8 1050 $me = 'sq_getnxtag';
691a2d25 1051 if ($offset > strlen($body)){
1052 return false;
1053 }
1054 $lt = sq_findnxstr($body, $offset, "<");
1055 if ($lt == strlen($body)){
1056 return false;
1057 }
1058 /**
1059 * We are here:
1060 * blah blah <tag attribute="value">
1061 * \---------^
1062 */
1063 $pos = sq_skipspace($body, $lt+1);
1064 if ($pos >= strlen($body)){
1065 return Array(false, false, false, $lt, strlen($body));
1066 }
1067 /**
1068 * There are 3 kinds of tags:
1069 * 1. Opening tag, e.g.:
1070 * <a href="blah">
1071 * 2. Closing tag, e.g.:
1072 * </a>
1073 * 3. XHTML-style content-less tag, e.g.:
1074 * <img src="blah"/>
1075 */
1076 $tagtype = false;
1077 switch (substr($body, $pos, 1)){
3d8371be 1078 case '/':
1079 $tagtype = 2;
1080 $pos++;
1081 break;
1082 case '!':
1083 /**
1084 * A comment or an SGML declaration.
1085 */
1086 if (substr($body, $pos+1, 2) == "--"){
1087 $gt = strpos($body, "-->", $pos);
1088 if ($gt === false){
1089 $gt = strlen($body);
1090 } else {
1091 $gt += 2;
1092 }
1093 return Array(false, false, false, $lt, $gt);
bb8d0799 1094 } else {
3d8371be 1095 $gt = sq_findnxstr($body, $pos, ">");
1096 return Array(false, false, false, $lt, $gt);
1097 }
1098 break;
1099 default:
1100 /**
1101 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1102 * later.
1103 */
1104 $tagtype = 1;
1105 break;
691a2d25 1106 }
a3daaaf3 1107
691a2d25 1108 $tag_start = $pos;
1109 $tagname = '';
1110 /**
1111 * Look for next [\W-_], which will indicate the end of the tag name.
1112 */
1113 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1114 if ($regary == false){
1115 return Array(false, false, false, $lt, strlen($body));
1116 }
1117 list($pos, $tagname, $match) = $regary;
1118 $tagname = strtolower($tagname);
1119
1120 /**
1121 * $match can be either of these:
1122 * '>' indicating the end of the tag entirely.
1123 * '\s' indicating the end of the tag name.
1124 * '/' indicating that this is type-3 xhtml tag.
da2415c1 1125 *
691a2d25 1126 * Whatever else we find there indicates an invalid tag.
1127 */
1128 switch ($match){
3d8371be 1129 case '/':
691a2d25 1130 /**
3d8371be 1131 * This is an xhtml-style tag with a closing / at the
1132 * end, like so: <img src="blah"/>. Check if it's followed
1133 * by the closing bracket. If not, then this tag is invalid
691a2d25 1134 */
3d8371be 1135 if (substr($body, $pos, 2) == "/>"){
1136 $pos++;
1137 $tagtype = 3;
1138 } else {
1139 $gt = sq_findnxstr($body, $pos, ">");
1140 $retary = Array(false, false, false, $lt, $gt);
1141 return $retary;
1142 }
1143 case '>':
1144 return Array($tagname, false, $tagtype, $lt, $pos);
1145 break;
1146 default:
1147 /**
1148 * Check if it's whitespace
1149 */
1150 if (!preg_match('/\s/', $match)){
1151 /**
1152 * This is an invalid tag! Look for the next closing ">".
1153 */
7d06541f 1154 $gt = sq_findnxstr($body, $lt, ">");
3d8371be 1155 return Array(false, false, false, $lt, $gt);
1156 }
1157 break;
691a2d25 1158 }
3d8371be 1159
691a2d25 1160 /**
1161 * At this point we're here:
1162 * <tagname attribute='blah'>
1163 * \-------^
1164 *
1165 * At this point we loop in order to find all attributes.
1166 */
1167 $attname = '';
1168 $atttype = false;
1169 $attary = Array();
1170
1171 while ($pos <= strlen($body)){
1172 $pos = sq_skipspace($body, $pos);
1173 if ($pos == strlen($body)){
1174 /**
1175 * Non-closed tag.
1176 */
1177 return Array(false, false, false, $lt, $pos);
1178 }
1179 /**
1180 * See if we arrived at a ">" or "/>", which means that we reached
1181 * the end of the tag.
1182 */
1183 $matches = Array();
164800ad 1184 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
c828931c 1185 /**
1186 * Yep. So we did.
1187 */
1188 $pos += strlen($matches{1});
1189 if ($matches{2} == "/>"){
1190 $tagtype = 3;
1191 $pos++;
1192 }
1193 return Array($tagname, $attary, $tagtype, $lt, $pos);
1194 }
a3daaaf3 1195
cca46357 1196 /**
691a2d25 1197 * There are several types of attributes, with optional
1198 * [:space:] between members.
1199 * Type 1:
1200 * attrname[:space:]=[:space:]'CDATA'
1201 * Type 2:
1202 * attrname[:space:]=[:space:]"CDATA"
1203 * Type 3:
1204 * attr[:space:]=[:space:]CDATA
1205 * Type 4:
1206 * attrname
cca46357 1207 *
691a2d25 1208 * We leave types 1 and 2 the same, type 3 we check for
1209 * '"' and convert to "&quot" if needed, then wrap in
1210 * double quotes. Type 4 we convert into:
1211 * attrname="yes".
cca46357 1212 */
3f7c623f 1213 $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
691a2d25 1214 if ($regary == false){
1215 /**
1216 * Looks like body ended before the end of tag.
1217 */
1218 return Array(false, false, false, $lt, strlen($body));
cca46357 1219 }
691a2d25 1220 list($pos, $attname, $match) = $regary;
1221 $attname = strtolower($attname);
1222 /**
1223 * We arrived at the end of attribute name. Several things possible
1224 * here:
1225 * '>' means the end of the tag and this is attribute type 4
1226 * '/' if followed by '>' means the same thing as above
1227 * '\s' means a lot of things -- look what it's followed by.
1228 * anything else means the attribute is invalid.
1229 */
1230 switch($match){
3d8371be 1231 case '/':
691a2d25 1232 /**
3d8371be 1233 * This is an xhtml-style tag with a closing / at the
1234 * end, like so: <img src="blah"/>. Check if it's followed
1235 * by the closing bracket. If not, then this tag is invalid
691a2d25 1236 */
3d8371be 1237 if (substr($body, $pos, 2) == "/>"){
691a2d25 1238 $pos++;
3d8371be 1239 $tagtype = 3;
691a2d25 1240 } else {
3d8371be 1241 $gt = sq_findnxstr($body, $pos, ">");
1242 $retary = Array(false, false, false, $lt, $gt);
1243 return $retary;
1244 }
1245 case '>':
1246 $attary{$attname} = '"yes"';
1247 return Array($tagname, $attary, $tagtype, $lt, $pos);
1248 break;
1249 default:
1250 /**
1251 * Skip whitespace and see what we arrive at.
1252 */
1253 $pos = sq_skipspace($body, $pos);
1254 $char = substr($body, $pos, 1);
1255 /**
1256 * Two things are valid here:
1257 * '=' means this is attribute type 1 2 or 3.
1258 * \w means this was attribute type 4.
1259 * anything else we ignore and re-loop. End of tag and
1260 * invalid stuff will be caught by our checks at the beginning
1261 * of the loop.
1262 */
1263 if ($char == "="){
1264 $pos++;
1265 $pos = sq_skipspace($body, $pos);
691a2d25 1266 /**
3d8371be 1267 * Here are 3 possibilities:
1268 * "'" attribute type 1
1269 * '"' attribute type 2
1270 * everything else is the content of tag type 3
691a2d25 1271 */
3d8371be 1272 $quot = substr($body, $pos, 1);
1273 if ($quot == "'"){
1274 $regary = sq_findnxreg($body, $pos+1, "\'");
1275 if ($regary == false){
1276 return Array(false, false, false, $lt, strlen($body));
1277 }
1278 list($pos, $attval, $match) = $regary;
1279 $pos++;
1280 $attary{$attname} = "'" . $attval . "'";
1281 } else if ($quot == '"'){
1282 $regary = sq_findnxreg($body, $pos+1, '\"');
1283 if ($regary == false){
1284 return Array(false, false, false, $lt, strlen($body));
1285 }
1286 list($pos, $attval, $match) = $regary;
1287 $pos++;
1288 $attary{$attname} = '"' . $attval . '"';
1289 } else {
1290 /**
1291 * These are hateful. Look for \s, or >.
1292 */
1293 $regary = sq_findnxreg($body, $pos, "[\s>]");
1294 if ($regary == false){
1295 return Array(false, false, false, $lt, strlen($body));
1296 }
1297 list($pos, $attval, $match) = $regary;
1298 /**
1299 * If it's ">" it will be caught at the top.
1300 */
1301 $attval = preg_replace("/\"/s", "&quot;", $attval);
1302 $attary{$attname} = '"' . $attval . '"';
7e235a1a 1303 }
3d8371be 1304 } else if (preg_match("|[\w/>]|", $char)) {
691a2d25 1305 /**
3d8371be 1306 * That was attribute type 4.
691a2d25 1307 */
3d8371be 1308 $attary{$attname} = '"yes"';
1309 } else {
1310 /**
1311 * An illegal character. Find next '>' and return.
1312 */
1313 $gt = sq_findnxstr($body, $pos, ">");
1314 return Array(false, false, false, $lt, $gt);
451f74a2 1315 }
3d8371be 1316 break;
691a2d25 1317 }
1318 }
1319 /**
1320 * The fact that we got here indicates that the tag end was never
1321 * found. Return invalid tag indication so it gets stripped.
1322 */
1323 return Array(false, false, false, $lt, strlen($body));
1324}
1325
1326/**
1327 * This function checks attribute values for entity-encoded values
1328 * and returns them translated into 8-bit strings so we can run
1329 * checks on them.
1330 *
1331 * @param $attvalue A string to run entity check against.
1332 * @return Translated value.
1333 */
91220ed1 1334
691a2d25 1335function sq_deent($attvalue){
b583c3e8 1336 $me = 'sq_deent';
691a2d25 1337 /**
1338 * See if we have to run the checks first. All entities must start
1339 * with "&".
1340 */
91220ed1 1341 if (strpos($attvalue, '&') === false){
691a2d25 1342 return $attvalue;
1343 }
1344 /**
1345 * Check named entities first.
1346 */
1347 $trans = get_html_translation_table(HTML_ENTITIES);
1348 /**
1349 * Leave &quot; in, as it can mess us up.
1350 */
1351 $trans = array_flip($trans);
91220ed1 1352 unset($trans{'&quot;'});
691a2d25 1353 while (list($ent, $val) = each($trans)){
91220ed1 1354 $attvalue = preg_replace('/' . $ent . '*/si', $val, $attvalue);
691a2d25 1355 }
1356 /**
1357 * Now translate numbered entities from 1 to 255 if needed.
1358 */
91220ed1 1359 if (strpos($attvalue, '#') !== false){
691a2d25 1360 $omit = Array(34, 39);
91220ed1 1361 for ($asc = 256; $asc >= 0; $asc--){
691a2d25 1362 if (!in_array($asc, $omit)){
1363 $chr = chr($asc);
91220ed1 1364 $octrule = '/\&#0*' . $asc . ';*/si';
1365 $hexrule = '/\&#x0*' . dechex($asc) . ';*/si';
1366 $attvalue = preg_replace($octrule, $chr, $attvalue);
1367 $attvalue = preg_replace($hexrule, $chr, $attvalue);
a3daaaf3 1368 }
691a2d25 1369 }
1370 }
1371 return $attvalue;
1372}
1373
1374/**
1375 * This function runs various checks against the attributes.
1376 *
1377 * @param $tagname String with the name of the tag.
1378 * @param $attary Array with all tag attributes.
1379 * @param $rm_attnames See description for sq_sanitize
1380 * @param $bad_attvals See description for sq_sanitize
1381 * @param $add_attr_to_tag See description for sq_sanitize
1382 * @param $message message object
1383 * @param $id message id
1384 * @return Array with modified attributes.
1385 */
da2415c1 1386function sq_fixatts($tagname,
1387 $attary,
691a2d25 1388 $rm_attnames,
1389 $bad_attvals,
1390 $add_attr_to_tag,
1391 $message,
b3af12ef 1392 $id,
3d8371be 1393 $mailbox
691a2d25 1394 ){
b583c3e8 1395 $me = 'sq_fixatts';
691a2d25 1396 while (list($attname, $attvalue) = each($attary)){
1397 /**
1398 * See if this attribute should be removed.
1399 */
1400 foreach ($rm_attnames as $matchtag=>$matchattrs){
1401 if (preg_match($matchtag, $tagname)){
1402 foreach ($matchattrs as $matchattr){
1403 if (preg_match($matchattr, $attname)){
1404 unset($attary{$attname});
1405 continue;
1406 }
451f74a2 1407 }
451f74a2 1408 }
691a2d25 1409 }
1410 /**
2dd879b8 1411 * Remove any backslashes, entities, and extraneous whitespace.
691a2d25 1412 */
2dd879b8 1413 $attvalue = sq_unbackslash($attvalue);
691a2d25 1414 $attvalue = sq_deent($attvalue);
2dd879b8 1415 $attvalue = sq_unspace($attvalue);
691a2d25 1416
af861a34 1417 /**
1418 * Remove \r \n \t \0 " " "\\"
1419 */
8d863f64 1420 $attvalue = str_replace(Array("\r", "\n", "\t", "\0", " ", "\\"),
af861a34 1421 Array('', '','','','',''), $attvalue);
1422
691a2d25 1423 /**
1424 * Now let's run checks on the attvalues.
1425 * I don't expect anyone to comprehend this. If you do,
1426 * get in touch with me so I can drive to where you live and
1427 * shake your hand personally. :)
1428 */
1429 foreach ($bad_attvals as $matchtag=>$matchattrs){
1430 if (preg_match($matchtag, $tagname)){
1431 foreach ($matchattrs as $matchattr=>$valary){
1432 if (preg_match($matchattr, $attname)){
1433 /**
1434 * There are two arrays in valary.
1435 * First is matches.
1436 * Second one is replacements
1437 */
1438 list($valmatch, $valrepl) = $valary;
da2415c1 1439 $newvalue =
691a2d25 1440 preg_replace($valmatch, $valrepl, $attvalue);
1441 if ($newvalue != $attvalue){
1442 $attary{$attname} = $newvalue;
1443 }
1444 }
1445 }
451f74a2 1446 }
a3daaaf3 1447 }
691a2d25 1448 /**
1449 * Turn cid: urls into http-friendly ones.
1450 */
1451 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
b3af12ef 1452 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
691a2d25 1453 }
a3daaaf3 1454 }
691a2d25 1455 /**
1456 * See if we need to append any attributes to this tag.
1457 */
1458 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1459 if (preg_match($matchtag, $tagname)){
1460 $attary = array_merge($attary, $addattary);
1461 }
1462 }
1463 return $attary;
451f74a2 1464}
a3daaaf3 1465
691a2d25 1466/**
1467 * This function edits the style definition to make them friendly and
1468 * usable in squirrelmail.
da2415c1 1469 *
691a2d25 1470 * @param $message the message object
1471 * @param $id the message id
1472 * @param $content a string with whatever is between <style> and </style>
e60a299a 1473 * @param $mailbox the message mailbox
691a2d25 1474 * @return a string with edited content.
1475 */
e60a299a 1476function sq_fixstyle($body, $pos, $message, $id, $mailbox){
691a2d25 1477 global $view_unsafe_images;
b583c3e8 1478 $me = 'sq_fixstyle';
7d06541f 1479 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1480 if ($ret == FALSE){
1481 return array(FALSE, strlen($body));
1482 }
1483 $newpos = $ret[0] + strlen($ret[2]);
1484 $content = $ret[1];
691a2d25 1485 /**
1486 * First look for general BODY style declaration, which would be
1487 * like so:
1488 * body {background: blah-blah}
1489 * and change it to .bodyclass so we can just assign it to a <div>
1490 */
1491 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
3d8371be 1492 $secremoveimg = '../images/' . _("sec_remove_eng.png");
691a2d25 1493 /**
1494 * Fix url('blah') declarations.
1495 */
7d06541f 1496 $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
691a2d25 1497 "url(\\1$secremoveimg\\2)", $content);
1498 /**
1499 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1500 * is false.
1501 */
1502 if (!$view_unsafe_images){
7d06541f 1503 $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
691a2d25 1504 "url(\\1$secremoveimg\\2)", $content);
1505 }
da2415c1 1506
691a2d25 1507 /**
1508 * Fix urls that refer to cid:
1509 */
da2415c1 1510 while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
7d06541f 1511 $content, $matches)){
691a2d25 1512 $cidurl = $matches{1};
e60a299a 1513 $httpurl = sq_cid2http($message, $id, $cidurl, $mailbox);
7d06541f 1514 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
691a2d25 1515 "url($httpurl)", $content);
1516 }
a3daaaf3 1517
691a2d25 1518 /**
bb8d0799 1519 * Fix stupid css declarations which lead to vulnerabilities
691a2d25 1520 * in IE.
1521 */
f83c60a2 1522 $match = Array('/expression/i',
1523 '/behaviou*r/i',
2dd879b8 1524 '/binding/i',
1525 '/include-source/i');
1526 $replace = Array('idiocy', 'idiocy', 'idiocy', 'idiocy');
bb8d0799 1527 $content = preg_replace($match, $replace, $content);
7d06541f 1528 return array($content, $newpos);
691a2d25 1529}
a3daaaf3 1530
691a2d25 1531/**
1532 * This function converts cid: url's into the ones that can be viewed in
1533 * the browser.
1534 *
1535 * @param $message the message object
1536 * @param $id the message id
1537 * @param $cidurl the cid: url.
e60a299a 1538 * @param $mailbox the message mailbox
691a2d25 1539 * @return a string with a http-friendly url
1540 */
b3af12ef 1541function sq_cid2http($message, $id, $cidurl, $mailbox){
691a2d25 1542 /**
1543 * Get rid of quotes.
1544 */
1545 $quotchar = substr($cidurl, 0, 1);
2dd879b8 1546 if ($quotchar == '"' || $quotchar == "'"){
1547 $cidurl = str_replace($quotchar, "", $cidurl);
1548 } else {
1549 $quotchar = '';
1550 }
691a2d25 1551 $cidurl = substr(trim($cidurl), 4);
e5e9381a 1552 $linkurl = find_ent_id($cidurl, $message);
1553 /* in case of non-save cid links $httpurl should be replaced by a sort of
1554 unsave link image */
1555 $httpurl = '';
1556 if ($linkurl) {
6b04287c 1557 $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
e5e9381a 1558 "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
3d8371be 1559 '&amp;ent_id=' . $linkurl . $quotchar;
e5e9381a 1560 }
691a2d25 1561 return $httpurl;
1562}
1563
1564/**
1565 * This function changes the <body> tag into a <div> tag since we
1566 * can't really have a body-within-body.
1567 *
2dd879b8 1568 * @param $attary an array of attributes and values of <body>
1569 * @param $mailbox mailbox we're currently reading (for cid2http)
1570 * @param $message current message (for cid2http)
1571 * @param $id current message id (for cid2http)
1572 * @return a modified array of attributes to be set for <div>
691a2d25 1573 */
2dd879b8 1574function sq_body2div($attary, $mailbox, $message, $id){
b583c3e8 1575 $me = 'sq_body2div';
3d8371be 1576 $divattary = Array('class' => "'bodyclass'");
b583c3e8 1577 $bgcolor = '#ffffff';
1578 $text = '#000000';
80b4debd 1579 $has_bgc_stl = $has_txt_stl = false;
b583c3e8 1580 $styledef = '';
691a2d25 1581 if (is_array($attary) && sizeof($attary) > 0){
1582 foreach ($attary as $attname=>$attvalue){
1583 $quotchar = substr($attvalue, 0, 1);
1584 $attvalue = str_replace($quotchar, "", $attvalue);
1585 switch ($attname){
3d8371be 1586 case 'background':
da2415c1 1587 $attvalue = sq_cid2http($message, $id,
2dd879b8 1588 $attvalue, $mailbox);
3d8371be 1589 $styledef .= "background-image: url('$attvalue'); ";
1590 break;
1591 case 'bgcolor':
80b4debd 1592 $has_bgc_stl = true;
3d8371be 1593 $styledef .= "background-color: $attvalue; ";
1594 break;
1595 case 'text':
80b4debd 1596 $has_txt_stl = true;
3d8371be 1597 $styledef .= "color: $attvalue; ";
1598 break;
691a2d25 1599 }
a3daaaf3 1600 }
80b4debd 1601 // Outlook defines a white bgcolor and no text color. This can lead to
1602 // white text on a white bg with certain themes.
1603 if ($has_bgc_stl && !$has_txt_stl) {
1604 $styledef .= "color: $text; ";
1605 }
691a2d25 1606 if (strlen($styledef) > 0){
1607 $divattary{"style"} = "\"$styledef\"";
1608 }
1609 }
1610 return $divattary;
1611}
a3daaaf3 1612
691a2d25 1613/**
1614 * This is the main function and the one you should actually be calling.
1615 * There are several variables you should be aware of an which need
1616 * special description.
1617 *
1618 * Since the description is quite lengthy, see it here:
1619 * http://www.mricon.com/html/phpfilter.html
1620 *
1621 * @param $body the string with HTML you wish to filter
1622 * @param $tag_list see description above
1623 * @param $rm_tags_with_content see description above
1624 * @param $self_closing_tags see description above
1625 * @param $force_tag_closing see description above
1626 * @param $rm_attnames see description above
1627 * @param $bad_attvals see description above
1628 * @param $add_attr_to_tag see description above
1629 * @param $message message object
1630 * @param $id message id
1631 * @return sanitized html safe to show on your pages.
1632 */
da2415c1 1633function sq_sanitize($body,
1634 $tag_list,
691a2d25 1635 $rm_tags_with_content,
1636 $self_closing_tags,
1637 $force_tag_closing,
1638 $rm_attnames,
1639 $bad_attvals,
1640 $add_attr_to_tag,
1641 $message,
b3af12ef 1642 $id,
3d8371be 1643 $mailbox
691a2d25 1644 ){
b583c3e8 1645 $me = 'sq_sanitize';
7d06541f 1646 $rm_tags = array_shift($tag_list);
691a2d25 1647 /**
1648 * Normalize rm_tags and rm_tags_with_content.
1649 */
7d06541f 1650 @array_walk($tag_list, 'sq_casenormalize');
691a2d25 1651 @array_walk($rm_tags_with_content, 'sq_casenormalize');
1652 @array_walk($self_closing_tags, 'sq_casenormalize');
1653 /**
1654 * See if tag_list is of tags to remove or tags to allow.
1655 * false means remove these tags
1656 * true means allow these tags
1657 */
691a2d25 1658 $curpos = 0;
1659 $open_tags = Array();
2dd879b8 1660 $trusted = "\n<!-- begin sanitized html -->\n";
691a2d25 1661 $skip_content = false;
bb8d0799 1662 /**
1663 * Take care of netscape's stupid javascript entities like
1664 * &{alert('boo')};
1665 */
1666 $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
691a2d25 1667
7d06541f 1668 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
691a2d25 1669 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1670 $free_content = substr($body, $curpos, $lt-$curpos);
1671 /**
1672 * Take care of <style>
1673 */
7d06541f 1674 if ($tagname == "style" && $tagtype == 1){
da2415c1 1675 list($free_content, $curpos) =
e60a299a 1676 sq_fixstyle($body, $gt+1, $message, $id, $mailbox);
7d06541f 1677 if ($free_content != FALSE){
1678 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1679 $trusted .= $free_content;
1680 $trusted .= sq_tagprint($tagname, false, 2);
1681 }
1682 continue;
691a2d25 1683 }
1684 if ($skip_content == false){
1685 $trusted .= $free_content;
691a2d25 1686 }
1687 if ($tagname != FALSE){
1688 if ($tagtype == 2){
1689 if ($skip_content == $tagname){
1690 /**
1691 * Got to the end of tag we needed to remove.
1692 */
1693 $tagname = false;
1694 $skip_content = false;
1695 } else {
1696 if ($skip_content == false){
c828931c 1697 if ($tagname == "body"){
1698 $tagname = "div";
2dd879b8 1699 }
da2415c1 1700 if (isset($open_tags{$tagname}) &&
2dd879b8 1701 $open_tags{$tagname} > 0){
1702 $open_tags{$tagname}--;
691a2d25 1703 } else {
2dd879b8 1704 $tagname = false;
691a2d25 1705 }
691a2d25 1706 }
1707 }
1708 } else {
1709 /**
1710 * $rm_tags_with_content
1711 */
1712 if ($skip_content == false){
1713 /**
1714 * See if this is a self-closing type and change
1715 * tagtype appropriately.
1716 */
1717 if ($tagtype == 1
1718 && in_array($tagname, $self_closing_tags)){
2dd879b8 1719 $tagtype = 3;
691a2d25 1720 }
1721 /**
1722 * See if we should skip this tag and any content
1723 * inside it.
1724 */
1725 if ($tagtype == 1 &&
1726 in_array($tagname, $rm_tags_with_content)){
1727 $skip_content = $tagname;
1728 } else {
da2415c1 1729 if (($rm_tags == false
691a2d25 1730 && in_array($tagname, $tag_list)) ||
1731 ($rm_tags == true &&
1732 !in_array($tagname, $tag_list))){
1733 $tagname = false;
1734 } else {
2dd879b8 1735 /**
1736 * Convert body into div.
1737 */
1738 if ($tagname == "body"){
1739 $tagname = "div";
da2415c1 1740 $attary = sq_body2div($attary, $mailbox,
2dd879b8 1741 $message, $id);
1742 }
691a2d25 1743 if ($tagtype == 1){
1744 if (isset($open_tags{$tagname})){
1745 $open_tags{$tagname}++;
1746 } else {
1747 $open_tags{$tagname}=1;
1748 }
1749 }
1750 /**
1751 * This is where we run other checks.
1752 */
1753 if (is_array($attary) && sizeof($attary) > 0){
1754 $attary = sq_fixatts($tagname,
1755 $attary,
1756 $rm_attnames,
1757 $bad_attvals,
1758 $add_attr_to_tag,
1759 $message,
b3af12ef 1760 $id,
3d8371be 1761 $mailbox
691a2d25 1762 );
1763 }
1764 }
1765 }
691a2d25 1766 }
1767 }
1768 if ($tagname != false && $skip_content == false){
1769 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1770 }
691a2d25 1771 }
1772 $curpos = $gt+1;
a3daaaf3 1773 }
691a2d25 1774 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1775 if ($force_tag_closing == true){
1776 foreach ($open_tags as $tagname=>$opentimes){
1777 while ($opentimes > 0){
1778 $trusted .= '</' . $tagname . '>';
1779 $opentimes--;
1780 }
1781 }
1782 $trusted .= "\n";
1783 }
1784 $trusted .= "<!-- end sanitized html -->\n";
1785 return $trusted;
1786}
451f74a2 1787
691a2d25 1788/**
1789 * This is a wrapper function to call html sanitizing routines.
1790 *
1791 * @param $body the body of the message
1792 * @param $id the id of the message
1793 * @return a string with html safe to display in the browser.
1794 */
7aad7b77 1795function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
691a2d25 1796 global $attachment_common_show_images, $view_unsafe_images,
3d8371be 1797 $has_unsafe_images;
691a2d25 1798 /**
1799 * Don't display attached images in HTML mode.
1800 */
1801 $attachment_common_show_images = false;
1802 $tag_list = Array(
1803 false,
1804 "object",
1805 "meta",
1806 "html",
1807 "head",
cc34b00d 1808 "base",
e18cb31b 1809 "link",
45071bd6 1810 "frame",
2dd879b8 1811 "iframe",
1812 "plaintext",
1813 "marquee"
691a2d25 1814 );
1815
1816 $rm_tags_with_content = Array(
1817 "script",
1818 "applet",
1819 "embed",
2dd879b8 1820 "title",
1821 "frameset",
1822 "xml"
691a2d25 1823 );
1824
1825 $self_closing_tags = Array(
1826 "img",
1827 "br",
1828 "hr",
1829 "input"
1830 );
1831
2dd879b8 1832 $force_tag_closing = true;
691a2d25 1833
1834 $rm_attnames = Array(
1835 "/.*/" =>
1836 Array(
3a50c8d2 1837 "/target/i",
1838 "/^on.*/i",
1839 "/^dynsrc/i",
1840 "/^data.*/i",
1841 "/^lowsrc.*/i"
691a2d25 1842 )
1843 );
1844
1845 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1846 $bad_attvals = Array(
1847 "/.*/" =>
1848 Array(
0a6ec9b5 1849 "/^src|background/i" =>
691a2d25 1850 Array(
1851 Array(
f83c60a2 1852 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1853 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1854 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
691a2d25 1855 ),
1856 Array(
1857 "\\1$secremoveimg\\2",
bb8d0799 1858 "\\1$secremoveimg\\2",
3d8371be 1859 "\\1$secremoveimg\\2",
1860 "\\1$secremoveimg\\2"
691a2d25 1861 )
1862 ),
0a6ec9b5 1863 "/^href|action/i" =>
1864 Array(
1865 Array(
f83c60a2 1866 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1867 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1868 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
0a6ec9b5 1869 ),
1870 Array(
2dd879b8 1871 "\\1#\\1",
1872 "\\1#\\1",
1873 "\\1#\\1",
1874 "\\1#\\1"
0a6ec9b5 1875 )
1876 ),
f83c60a2 1877 "/^style/i" =>
691a2d25 1878 Array(
1879 Array(
f83c60a2 1880 "/expression/i",
1881 "/binding/i",
1882 "/behaviou*r/i",
2dd879b8 1883 "/include-source/i",
7d06541f 1884 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
1885 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
af861a34 1886 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
1887 "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si"
691a2d25 1888 ),
1889 Array(
bb8d0799 1890 "idiocy",
3d8371be 1891 "idiocy",
1892 "idiocy",
2dd879b8 1893 "idiocy",
1894 "url(\\1#\\1)",
1895 "url(\\1#\\1)",
1896 "url(\\1#\\1)",
af861a34 1897 "url(\\1#\\1)",
1898 "\\1:url(\\2#\\3)"
691a2d25 1899 )
1900 )
1901 )
1902 );
5262d9a6 1903 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
2dd879b8 1904 $view_unsafe_images = false;
45071bd6 1905 }
691a2d25 1906 if (!$view_unsafe_images){
1907 /**
1908 * Remove any references to http/https if view_unsafe_images set
1909 * to false.
1910 */
0a6ec9b5 1911 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
f83c60a2 1912 '/^([\'\"])\s*https*:.*([\'\"])/si');
0a6ec9b5 1913 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
2dd879b8 1914 "\\1$secremoveimg\\1");
3a50c8d2 1915 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
43d678b6 1916 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
3a50c8d2 1917 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
2dd879b8 1918 "url(\\1$secremoveimg\\1)");
691a2d25 1919 }
451f74a2 1920
691a2d25 1921 $add_attr_to_tag = Array(
da2415c1 1922 "/^a$/i" =>
2dd879b8 1923 Array('target'=>'"_new"',
1924 'title'=>'"'._("This external link will open in a new window").'"'
1925 )
1926 );
da2415c1 1927 $trusted = sq_sanitize($body,
1928 $tag_list,
691a2d25 1929 $rm_tags_with_content,
1930 $self_closing_tags,
1931 $force_tag_closing,
1932 $rm_attnames,
1933 $bad_attvals,
1934 $add_attr_to_tag,
1935 $message,
b3af12ef 1936 $id,
3d8371be 1937 $mailbox
691a2d25 1938 );
f83c60a2 1939 if (preg_match("|$secremoveimg|i", $trusted)){
691a2d25 1940 $has_unsafe_images = true;
da2415c1 1941 }
691a2d25 1942 return $trusted;
451f74a2 1943}
a4a70693 1944
da2415c1 1945/**
1946 * function SendDownloadHeaders - send file to the browser
1947 *
1948 * Original Source: SM core src/download.php
1949 * moved here to make it available to other code, and separate
1950 * front end from back end functionality.
1951 *
1952 * @param string $type0 first half of mime type
1953 * @param string $type1 second half of mime type
1954 * @param string $filename filename to tell the browser for downloaded file
1955 * @param boolean $force whether to force the download dialog to pop
8d863f64 1956 * @param optional integer $filesize send the Content-Header and length to the browser
da2415c1 1957 * @return void
1958 */
07c49f57 1959 function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
da2415c1 1960 global $languages, $squirrelmail_language;
1961 $isIE = $isIE6 = 0;
1962
1963 sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER);
1964
1965 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
1966 strstr($HTTP_USER_AGENT, 'Opera') === false) {
1967 $isIE = 1;
1968 }
1969
1970 if (strstr($HTTP_USER_AGENT, 'compatible; MSIE 6') !== false &&
1971 strstr($HTTP_USER_AGENT, 'Opera') === false) {
1972 $isIE6 = 1;
1973 }
1974
1975 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
1976 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
1977 $filename =
8d863f64 1978 $languages[$squirrelmail_language]['XTRA_CODE']('downloadfilename', $filename, $HTTP_USER_AGENT);
da2415c1 1979 } else {
8d863f64 1980 $filename = ereg_replace('[\\/:\*\?"<>\|;]', '_', str_replace('&nbsp;', ' ', $filename));
1981 }
1982
1983 // A Pox on Microsoft and it's Internet Explorer!
1984 //
1985 // IE has lots of bugs with file downloads.
1986 // It also has problems with SSL. Both of these cause problems
1987 // for us in this function.
1988 //
1989 // See this article on Cache Control headers and SSL
1990 // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
1991 //
1992 // The best thing you can do for IE is to upgrade to the latest
1993 // version
1994 //set all the Cache Control Headers for IE
0859656a 1995 if ($isIE) {
8d863f64 1996 header ("Pragma: public");
1997 header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); # HTTP/1.1
1998 header ("Cache-Control: post-check=0, pre-check=0", false);
1999 header ("Cache-control: private");
2000
2001 //set the inline header for IE, we'll add the attachment header later if we need it
2002 header ("Content-Disposition: inline; filename=$filename");
da2415c1 2003 }
2004
da2415c1 2005 if (!$force) {
2006 // Try to show in browser window
8d863f64 2007 header ("Content-Disposition: inline; filename=\"$filename\"");
2008 header ("Content-Type: $type0/$type1; name=\"$filename\"");
da2415c1 2009 } else {
2010 // Try to pop up the "save as" box
8d863f64 2011
da2415c1 2012 // IE makes this hard. It pops up 2 save boxes, or none.
2013 // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
8d863f64 2014 // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
2015 // But, according to Microsoft, it is "RFC compliant but doesn't
da2415c1 2016 // take into account some deviations that allowed within the
2017 // specification." Doesn't that mean RFC non-compliant?
2018 // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
8d863f64 2019
2020 // all browsers need the application/octet-stream header for this
2021 header ("Content-Type: application/octet-stream; name=\"$filename\"");
2022
2023 // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
2024 // Do not have quotes around filename, but that applied to
2025 // "attachment"... does it apply to inline too?
2026 header ("Content-Disposition: attachment; filename=\"$filename\"");
2027
da2415c1 2028 if ($isIE && !$isIE6) {
da2415c1 2029 // This combination seems to work mostly. IE 5.5 SP 1 has
2030 // known issues (see the Microsoft Knowledge Base)
8d863f64 2031
da2415c1 2032 // This works for most types, but doesn't work with Word files
8d863f64 2033 header ("Content-Type: application/download; name=\"$filename\"");
da2415c1 2034
2035 // These are spares, just in case. :-)
2036 //header("Content-Type: $type0/$type1; name=\"$filename\"");
2037 //header("Content-Type: application/x-msdownload; name=\"$filename\"");
2038 //header("Content-Type: application/octet-stream; name=\"$filename\"");
2039 } else {
8d863f64 2040 // another application/octet-stream forces download for Netscape
2041 header ("Content-Type: application/octet-stream; name=\"$filename\"");
da2415c1 2042 }
2043 }
07c49f57 2044
2045 //send the content-length header if the calling function provides it
2046 if ($filesize > 0) {
8d863f64 2047 header("Content-Length: $filesize");
07c49f57 2048 }
2049
8d863f64 2050} // end fn SendDownloadHeaders
da2415c1 2051
0859656a 2052?>