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