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