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