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