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