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