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