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