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