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