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