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