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