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