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