squirrelmail-webmail  1.4.22
About: SquirrelMail is a standards-based webmail package with strong MIME support, address books, and folder manipulation (written in PHP4).
  Fossies Dox: squirrelmail-webmail-1.4.22.tar.gz  ("inofficial" and yet experimental doxygen-generated source code documentation)  

mime.php
Go to the documentation of this file.
1 <?php
2 
16 require_once(SM_PATH . 'functions/imap.php');
17 require_once(SM_PATH . 'functions/attachment_common.php');
18 
19 /* -------------------------------------------------------------------------- */
20 /* MIME DECODING */
21 /* -------------------------------------------------------------------------- */
22 
30 function mime_structure ($bodystructure, $flags=array()) {
31 
32  /* Isolate the body structure and remove beginning and end parenthesis. */
33  $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
34  $read = trim(substr ($read, 0, -1));
35  $i = 0;
36  $msg = Message::parseStructure($read,$i);
37  if (!is_object($msg)) {
38  include_once(SM_PATH . 'functions/display_messages.php');
39  global $color, $mailbox;
40  /* removed urldecode because $_GET is auto urldecoded ??? */
42  echo "<body text=\"$color[8]\" bgcolor=\"$color[4]\" link=\"$color[7]\" vlink=\"$color[7]\" alink=\"$color[7]\">\n\n" .
43  '<center>';
44  $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
45  $errormessage .= '<br />'._("The bodystructure provided by your IMAP server:").'<br /><br />';
46  $errormessage .= '<table><tr><td>' . htmlspecialchars($read) . '</td></tr></table>';
47  plain_error_message( $errormessage, $color );
48  echo '</body></html>';
49  exit;
50  }
51  if (count($flags)) {
52  foreach ($flags as $flag) {
53  $char = strtoupper($flag{1});
54  switch ($char) {
55  case 'S':
56  if (strtolower($flag) == '\\seen') {
57  $msg->is_seen = true;
58  }
59  break;
60  case 'A':
61  if (strtolower($flag) == '\\answered') {
62  $msg->is_answered = true;
63  }
64  break;
65  case 'D':
66  if (strtolower($flag) == '\\deleted') {
67  $msg->is_deleted = true;
68  }
69  break;
70  case 'F':
71  if (strtolower($flag) == '\\flagged') {
72  $msg->is_flagged = true;
73  }
74  break;
75  case 'M':
76  if (strtolower($flag) == '$mdnsent') {
77  $msg->is_mdnsent = true;
78  }
79  break;
80  default:
81  break;
82  }
83  }
84  }
85  // listEntities($msg);
86  return $msg;
87 }
88 
89 
90 
91 /* This starts the parsing of a particular structure. It is called recursively,
92  * so it can be passed different structures. It returns an object of type
93  * $message.
94  * First, it checks to see if it is a multipart message. If it is, then it
95  * handles that as it sees is necessary. If it is just a regular entity,
96  * then it parses it and adds the necessary header information (by calling out
97  * to mime_get_elements()
98  */
99 
100 function mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0) {
101  global $uid_support;
102  /* Do a bit of error correction. If we couldn't find the entity id, just guess
103  * that it is the first one. That is usually the case anyway.
104  */
105 
106  if (!$ent_id) {
107  $cmd = "FETCH $id BODY[]";
108  } else {
109  $cmd = "FETCH $id BODY[$ent_id]";
110  }
111 
112  if ($fetch_size!=0) $cmd .= "<0.$fetch_size>";
113 
114  $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
115  do {
116  $topline = trim(array_shift($data));
117  } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
118 
119  $wholemessage = implode('', $data);
120  if (preg_match('/\{([^\}]*)\}/', $topline, $regs)) {
121  $ret = substr($wholemessage, 0, $regs[1]);
122  /* There is some information in the content info header that could be important
123  * in order to parse html messages. Let's get them here.
124  */
125 // if ($ret{0} == '<') {
126 // $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
127 // }
128  } else if (preg_match('/"([^"]*)"/', $topline, $regs)) {
129  $ret = $regs[1];
130  } else if ((stristr($topline, 'nil') !== false) && (empty($wholemessage))) {
131  $ret = $wholemessage;
132  } else {
133  global $where, $what, $mailbox, $passed_id, $startMessage;
134  $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
135  if (isset($where) && isset($what)) {
136  $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
137  } else {
138  $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
139  }
140  $par .= '&amp;response=' . urlencode($response) .
141  '&amp;message=' . urlencode($message) .
142  '&amp;topline=' . urlencode($topline);
143 
144  echo '<tt><br />' .
145  '<table width="80%"><tr>' .
146  '<tr><td colspan="2">' .
147  _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
148  '</td></tr>' .
149  '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
150  '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
151  '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
152  '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
153  "</table><br /></tt></font><hr />";
154 
155  $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
156  array_shift($data);
157  $wholemessage = implode('', $data);
158 
159  $ret = $wholemessage;
160  }
161  return $ret;
162 }
163 
164 function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout') {
165  global $uid_support;
166 
167  /* Don't kill the connection if the browser is over a dialup
168  * and it would take over 30 seconds to download it.
169  * Don't call set_time_limit in safe mode.
170  */
171 
172  if (!ini_get('safe_mode')) {
173  set_time_limit(0);
174  }
175  /* in case of base64 encoded attachments, do not buffer them.
176  Instead, echo the decoded attachment directly to screen */
177  if (strtolower($encoding) == 'base64') {
178  if (!$ent_id) {
179  $query = "FETCH $id BODY[]";
180  } else {
181  $query = "FETCH $id BODY[$ent_id]";
182  }
183  sqimap_run_command($imap_stream,$query,true,$response,$message,$uid_support,'sqimap_base64_decode',$rStream,true);
184  } else {
185  $body = mime_fetch_body ($imap_stream, $id, $ent_id);
186  if ($rStream !== 'php://stdout') {
187  fwrite($rStream, decodeBody($body, $encoding));
188  } else {
189  echo decodeBody($body, $encoding);
190  }
191  }
192  return;
193 }
194 
195 /* -[ END MIME DECODING ]----------------------------------------------------------- */
196 
197 /* This is here for debugging purposes. It will print out a list
198  * of all the entity IDs that are in the $message object.
199  */
200 function listEntities ($message) {
201  if ($message) {
202  echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br />';
203  for ($i = 0; isset($message->entities[$i]); $i++) {
204  echo "$i : ";
205  $msg = listEntities($message->entities[$i]);
206 
207  if ($msg) {
208  echo "return: ";
209  return $msg;
210  }
211  }
212  }
213 }
214 
215 function getPriorityStr($priority) {
216  $priority_level = substr($priority,0,1);
217 
218  switch($priority_level) {
219  /* Check for a higher then normal priority. */
220  case '1':
221  case '2':
222  $priority_string = _("High");
223  break;
224 
225  /* Check for a lower then normal priority. */
226  case '4':
227  case '5':
228  $priority_string = _("Low");
229  break;
230 
231  /* Check for a normal priority. */
232  case '3':
233  default:
234  $priority_level = '3';
235  $priority_string = _("Normal");
236  break;
237 
238  }
239  return $priority_string;
240 }
241 
242 /* returns a $message object for a particular entity id */
243 function getEntity ($message, $ent_id) {
244  return $message->getEntity($ent_id);
245 }
246 
247 /* translateText
248  * Extracted from strings.php 23/03/2002
249  */
250 
252  global $where, $what; /* from searching */
253  global $color; /* color theme */
254 
255  require_once(SM_PATH . 'functions/url_parser.php');
256 
257  $body_ary = explode("\n", $body);
258  for ($i=0; $i < count($body_ary); $i++) {
259  $line = $body_ary[$i];
260  if (strlen($line) - 2 >= $wrap_at) {
261  sqWordWrap($line, $wrap_at, $charset);
262  }
263  $line = charset_decode($charset, $line);
264  $line = str_replace("\t", ' ', $line);
265 
266  parseUrl ($line);
267 
268  $quotes = 0;
269  $pos = 0;
270  $j = strlen($line);
271 
272  while ($pos < $j) {
273  if ($line[$pos] == ' ') {
274  $pos++;
275  } else if (strpos($line, '&gt;', $pos) === $pos) {
276  $pos += 4;
277  $quotes++;
278  } else {
279  break;
280  }
281  }
282 
283  if ($quotes % 2) {
284  if (!isset($color[13])) {
285  $color[13] = '#800000';
286  }
287  $line = '<font color="' . $color[13] . '">' . $line . '</font>';
288  } elseif ($quotes) {
289  if (!isset($color[14])) {
290  $color[14] = '#FF0000';
291  }
292  $line = '<font color="' . $color[14] . '">' . $line . '</font>';
293  }
294 
295  $body_ary[$i] = $line;
296  }
297  $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
298 }
299 
306 function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX',$clean=false) {
307  /* This if statement checks for the entity to show as the
308  * primary message. To add more of them, just put them in the
309  * order that is their priority.
310  */
311  global $startMessage, $languages, $squirrelmail_language,
312  $show_html_default, $sort, $has_unsafe_images, $passed_ent_id,
314  $download_and_unsafe_link;
315 
316  // If there's no "view_unsafe_images" variable in the URL, turn unsafe
317  // images off by default.
318  if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
319  $view_unsafe_images = false;
320  }
321 
322  $body = '';
323  $urlmailbox = urlencode($mailbox);
324  $body_message = getEntity($message, $ent_num);
325  if (($body_message->header->type0 == 'text') ||
326  ($body_message->header->type0 == 'rfc822')) {
327  $body = mime_fetch_body ($imap_stream, $id, $ent_num);
328  $body = decodeBody($body, $body_message->header->encoding);
329 
330  if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
331  function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
332  if (mb_detect_encoding($body) != 'ASCII') {
333  $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
334  }
335  }
336  $hookResults = do_hook("message_body", $body);
337  $body = $hookResults[1];
338 
339  /* If there are other types that shouldn't be formatted, add
340  * them here.
341  */
342 
343  if ($body_message->header->type1 == 'html') {
344  if ($show_html_default <> 1) {
345  $entity_conv = array('&nbsp;' => ' ',
346  '<p>' => "\n",
347  '<P>' => "\n",
348  '<br>' => "\n",
349  '<BR>' => "\n",
350  '<br />' => "\n",
351  '<BR />' => "\n",
352  '&gt;' => '>',
353  '&lt;' => '<');
354  $body = strtr($body, $entity_conv);
355  $body = strip_tags($body);
356  $body = trim($body);
358  $body_message->header->getParameter('charset'));
359  } else {
360  $charset = $body_message->header->getParameter('charset');
361  if (!empty($charset))
362  $body = charset_decode($charset,$body,false,true);
364  }
365  } else {
367  $body_message->header->getParameter('charset'));
368  }
369 
370  // if this is the clean display (i.e. printer friendly), stop here.
371  if ( $clean ) {
372  return $body;
373  }
374 
375  /*
376  * Previously the links for downloading and unsafe images were printed
377  * under the mail. By putting the links in a global variable we can
378  * print it in the toolbar where it belongs. Since the original code was
379  * in this place it's left here. It might be possible to move it to some
380  * other place if that makes sense. The possibility to do so has not
381  * been evaluated yet.
382  */
383 
384  // Initialize the global variable to an empty string.
385  $download_and_unsafe_link = '';
386 
387  // Prepare and build a link for downloading the mail.
388  $link = 'passed_id=' . $id . '&amp;ent_id='.$ent_num.
389  '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
390  '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
391  if (isset($passed_ent_id)) {
392  $link .= '&amp;passed_ent_id='.$passed_ent_id;
393  }
394 
395  // Always add the link for downloading the mail as a file to the global
396  // variable.
397  $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="download.php?absolute_dl=true&amp;' .
398  $link . '">' . _("Download this as a file") . '</a>';
399 
400  // Find out the right text to use in the link depending on the
401  // circumstances. If the unsafe images are displayed the link should
402  // hide them, if they aren't displayed the link should only appear if
403  // the mail really contains unsafe images.
404  if ($view_unsafe_images) {
405  $text = _("Hide Unsafe Images");
406  } else {
407  if (isset($has_unsafe_images) && $has_unsafe_images) {
408  $link .= '&amp;view_unsafe_images=1';
409  $text = _("View Unsafe Images");
410  } else {
411  $text = '';
412  }
413  }
414 
415  // Only create a link for unsafe images if there's need for one. If so:
416  // add it to the global variable.
417  if($text != '') {
418  $download_and_unsafe_link .= '&nbsp;|&nbsp;<a href="read_body.php?' . $link . '">' . $text . '</a>';
419  }
420  }
421  return $body;
422 }
423 
424 
425 function formatAttachments($message, $exclude_id, $mailbox, $id) {
426  global $where, $what, $startMessage, $color, $passed_ent_id;
427  static $ShownHTML = 0;
428 
429  $att_ar = $message->getAttachments($exclude_id);
430 
431  if (!count($att_ar)) return '';
432 
433  $attachments = '';
434 
435  $urlMailbox = urlencode($mailbox);
436 
437  foreach ($att_ar as $att) {
438  $ent = $att->entity_id;
439  $header = $att->header;
440  $type0 = strtolower($header->type0);
441  $type1 = strtolower($header->type1);
442  $name = '';
443  $links['download link']['text'] = _("Download");
444  $links['download link']['href'] = SM_PATH .
445  "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
446  $ImageURL = '';
447  if ($type0 =='message' && $type1 == 'rfc822') {
448  $default_page = SM_PATH . 'src/read_body.php';
449  $rfc822_header = $att->rfc822_header;
450  $filename = $rfc822_header->subject;
451  if (trim( $filename ) == '') {
452  $filename = 'untitled-[' . $ent . ']' ;
453  }
454  $from_o = $rfc822_header->from;
455  if (is_object($from_o)) {
456  $from_name = $from_o->getAddress(false);
457  } elseif (is_array($from_o) && count($from_o) && is_object($from_o[0])) {
458  // when a digest message is opened and you return to the digest
459  // now the from object is part of an array. This is a workaround.
460  $from_name = $from_o[0]->getAddress(false);
461  } else {
462  $from_name = _("Unknown sender");
463  }
464  $from_name = decodeHeader(($from_name));
465  $description = $from_name;
466  } else {
467  $default_page = SM_PATH . 'src/download.php';
468  if (is_object($header->disposition)) {
469  $filename = $header->disposition->getProperty('filename');
470  if (trim($filename) == '') {
471  $name = decodeHeader($header->disposition->getProperty('name'));
472  if (trim($name) == '') {
473  $name = $header->getParameter('name');
474  if(trim($name) == '') {
475  if (trim( $header->id ) == '') {
476  $filename = 'untitled-[' . $ent . ']' . '.' . strtolower($header->type1);
477  } else {
478  $filename = 'cid: ' . $header->id . '.' . strtolower($header->type1);
479  }
480  } else {
481  $filename = $name;
482  }
483  } else {
484  $filename = $name;
485  }
486  }
487  } else {
488  $filename = $header->getParameter('name');
489  if (!trim($filename)) {
490  if (trim( $header->id ) == '') {
491  $filename = 'untitled-[' . $ent . ']' . '.' . strtolower($header->type1) ;
492  } else {
493  $filename = 'cid: ' . $header->id . '.' . strtolower($header->type1);
494  }
495  }
496  }
497  if ($header->description) {
498  $description = decodeHeader($header->description);
499  } else {
500  $description = '';
501  }
502  }
503 
504  $display_filename = $filename;
505  if (isset($passed_ent_id)) {
506  $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
507  } else {
508  $passed_ent_id_link = '';
509  }
510  $defaultlink = $default_page . "?startMessage=$startMessage"
511  . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
512  . '&amp;ent_id='.$ent.$passed_ent_id_link;
513  if ($where && $what) {
514  $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
515  }
516  // IE does make use of mime content sniffing. Forcing a download
517  // prohibit execution of XSS inside an application/octet-stream attachment
518  if ($type0 == 'application' && $type1 == 'octet-stream') {
519  $defaultlink .= '&amp;absolute_dl=true';
520  }
521  /* This executes the attachment hook with a specific MIME-type.
522  * If that doesn't have results, it tries if there's a rule
523  * for a more generic type. Finally, a hook for ALL attachment
524  * types is run as well.
525  */
526  $hookresults = do_hook("attachment $type0/$type1", $links,
527  $startMessage, $id, $urlMailbox, $ent, $defaultlink,
528  $display_filename, $where, $what);
529  $hookresults = do_hook("attachment $type0/*", $hookresults[1],
530  $startMessage, $id, $urlMailbox, $ent, $hookresults[6],
531  $display_filename, $where, $what);
532  $hookresults = do_hook("attachment */*", $hookresults[1],
533  $startMessage, $id, $urlMailbox, $ent, $hookresults[6],
534  $display_filename, $where, $what);
535 
536  $links = $hookresults[1];
537  $defaultlink = $hookresults[6];
538 
539  $attachments .= '<tr><td>' .
540  '<a href="'.$defaultlink.'">'.decodeHeader($display_filename).'</a>&nbsp;</td>' .
541  '<td><small><b>' . show_readable_size($header->size) .
542  '</b>&nbsp;&nbsp;</small></td>' .
543  '<td><small>[ '.htmlspecialchars($type0).'/'.htmlspecialchars($type1).' ]&nbsp;</small></td>' .
544  '<td><small>';
545  $attachments .= '<b>' . $description . '</b>';
546  $attachments .= '</small></td><td><small>&nbsp;';
547 
548  $skipspaces = 1;
549  foreach ($links as $val) {
550  if ($skipspaces) {
551  $skipspaces = 0;
552  } else {
553  $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
554  }
555  $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
556  }
557  unset($links);
558  $attachments .= "</td></tr>\n";
559  }
560  return $attachments;
561 }
562 
563 function sqimap_base64_decode(&$string) {
564 
565  // Base64 encoded data goes in pairs of 4 bytes. To achieve on the
566  // fly decoding (to reduce memory usage) you have to check if the
567  // data has incomplete pairs
568 
569  // Remove the noise in order to check if the 4 bytes pairs are complete
570  $string = str_replace(array("\r\n","\n", "\r", " "),array('','','',''),$string);
571 
572  $sStringRem = '';
573  $iMod = strlen($string) % 4;
574  if ($iMod) {
575  $sStringRem = substr($string,-$iMod);
576  // Check if $sStringRem contains padding characters
577  if (substr($sStringRem,-1) != '=') {
578  $string = substr($string,0,-$iMod);
579  } else {
580  $sStringRem = '';
581  }
582  }
583  $string = base64_decode($string);
584  return $sStringRem;
585 }
586 
599 
600  $body = str_replace("\r\n", "\n", $body);
601  $encoding = strtolower($encoding);
602 
603  $encoding_handler = do_hook_function('decode_body', $encoding);
604 
605  // plugins get first shot at decoding the body
606  if (!empty($encoding_handler) && function_exists($encoding_handler)) {
607  $body = $encoding_handler('decode', $body);
608 
609  } elseif ($encoding == 'quoted-printable' ||
610  $encoding == 'quoted_printable') {
617  $body = quoted_printable_decode($body);
618  } elseif ($encoding == 'base64') {
619  $body = base64_decode($body);
620  }
621 
622  // All other encodings are returned raw.
623  return $body;
624 }
625 
633 function decodeHeader ($string, $utfencode=true,$htmlsave=true,$decide=false) {
635  if (is_array($string)) {
636  $string = implode("\n", $string);
637  }
638 
639  if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
640  function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
641  $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
642  // Do we need to return at this point?
643  // return $string;
644  }
645  $i = 0;
646  $iLastMatch = -2;
647  $encoded = false;
648 
649  $aString = explode(' ',$string);
650  $ret = '';
651  foreach ($aString as $chunk) {
652  if ($encoded && $chunk === '') {
653  continue;
654  } elseif ($chunk === '') {
655  $ret .= ' ';
656  continue;
657  }
658  $encoded = false;
659  /* if encoded words are not separated by a linear-space-white we still catch them */
660  $j = $i-1;
661 
662  while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
663  /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
664  if ($iLastMatch !== $j) {
665  if ($htmlsave) {
666  $ret .= '&#32;';
667  } else {
668  $ret .= ' ';
669  }
670  }
671  $iLastMatch = $i;
672  $j = $i;
673  if ($htmlsave) {
674  $ret .= htmlspecialchars($res[1]);
675  } else {
676  $ret .= $res[1];
677  }
678  $encoding = ucfirst($res[3]);
679 
680  /* decide about valid decoding */
681  if ($decide && is_conversion_safe($res[2])) {
682  $can_be_encoded=true;
683  } else {
684  $can_be_encoded=false;
685  }
686 
687  switch ($encoding)
688  {
689  case 'B':
690  $replace = base64_decode($res[4]);
691  if ($can_be_encoded) {
692  // string is converted from one charset to another. sanitizing depends on $htmlsave
693  $replace = charset_convert($res[2],$replace,$default_charset,$htmlsave);
694  } elseif ($utfencode) {
695  // string is converted to htmlentities and sanitized
696  $replace = charset_decode($res[2],$replace);
697  } elseif ($htmlsave) {
698  // string is not converted, but still sanitized
699  $replace = htmlspecialchars($replace);
700  }
701  $ret.= $replace;
702  break;
703  case 'Q':
704  $replace = str_replace('_', ' ', $res[4]);
705  $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
706  $replace);
707  if ($can_be_encoded) {
708  // string is converted from one charset to another. sanitizing depends on $htmlsave
709  $replace = charset_convert($res[2], $replace,$default_charset,$htmlsave);
710  } elseif ($utfencode) {
711  // string is converted to html entities and sanitized
712  $replace = charset_decode($res[2], $replace);
713  } elseif ($htmlsave) {
714  // string is not converted, but still sanizited
715  $replace = htmlspecialchars($replace);
716  }
717  $ret .= $replace;
718  break;
719  default:
720  break;
721  }
722  $chunk = $res[5];
723  $encoded = true;
724  }
725  if (!$encoded) {
726  if ($htmlsave) {
727  $ret .= '&#32;';
728  } else {
729  $ret .= ' ';
730  }
731  }
732 
733  if (!$encoded && $htmlsave) {
734  $ret .= htmlspecialchars($chunk);
735  } else {
736  $ret .= $chunk;
737  }
738  ++$i;
739  }
740  /* remove the first added space */
741  if ($ret) {
742  if ($htmlsave) {
743  $ret = substr($ret,5);
744  } else {
745  $ret = substr($ret,1);
746  }
747  }
748 
749  return $ret;
750 }
751 
759 function encodeHeader ($string) {
761 
762  if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
763  function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
764  return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
765  }
766 
767  // Use B encoding for multibyte charsets
768  $mb_charsets = array('utf-8','big5','gb2313','euc-kr');
769  if (in_array($default_charset,$mb_charsets) &&
771  sq_is8bit($string)) {
772  return encodeHeaderBase64($string,$default_charset);
773  } elseif (in_array($default_charset,$mb_charsets) &&
774  sq_is8bit($string) &&
775  ! in_array($default_charset,sq_mb_list_encodings())) {
776  // Add E_USER_NOTICE error here (can cause 'Cannot add header information' warning in compose.php)
777  // trigger_error('encodeHeader: Multibyte character set unsupported by mbstring extension.',E_USER_NOTICE);
778  }
779 
780  // Encode only if the string contains 8-bit characters or =?
781  $j = strlen($string);
782  $max_l = 75 - strlen($default_charset) - 7;
783  $aRet = array();
784  $ret = '';
785  $iEncStart = $enc_init = false;
786  $cur_l = $iOffset = 0;
787  for($i = 0; $i < $j; ++$i) {
788  switch($string{$i})
789  {
790  case '"':
791  case '=':
792  case '<':
793  case '>':
794  case ',':
795  case '?':
796  case '_':
797  if ($iEncStart === false) {
798  $iEncStart = $i;
799  }
800  $cur_l+=3;
801  if ($cur_l > ($max_l-2)) {
802  /* if there is an stringpart that doesn't need encoding, add it */
803  $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
804  $aRet[] = "=?$default_charset?Q?$ret?=";
805  $iOffset = $i;
806  $cur_l = 0;
807  $ret = '';
808  $iEncStart = false;
809  } else {
810  $ret .= sprintf("=%02X",ord($string{$i}));
811  }
812  break;
813  case '(':
814  case ')':
815  if ($iEncStart !== false) {
816  $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
817  $aRet[] = "=?$default_charset?Q?$ret?=";
818  $iOffset = $i;
819  $cur_l = 0;
820  $ret = '';
821  $iEncStart = false;
822  }
823  break;
824  case ' ':
825  if ($iEncStart !== false) {
826  $cur_l++;
827  if ($cur_l > $max_l) {
828  $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
829  $aRet[] = "=?$default_charset?Q?$ret?=";
830  $iOffset = $i;
831  $cur_l = 0;
832  $ret = '';
833  $iEncStart = false;
834  } else {
835  $ret .= '_';
836  }
837  }
838  break;
839  default:
840  $k = ord($string{$i});
841  if ($k > 126) {
842  if ($iEncStart === false) {
843  // do not start encoding in the middle of a string, also take the rest of the word.
844  $sLeadString = substr($string,0,$i);
845  $aLeadString = explode(' ',$sLeadString);
846  $sToBeEncoded = array_pop($aLeadString);
847  $iEncStart = $i - strlen($sToBeEncoded);
848  $ret .= $sToBeEncoded;
849  $cur_l += strlen($sToBeEncoded);
850  }
851  $cur_l += 3;
852  /* first we add the encoded string that reached it's max size */
853  if ($cur_l > ($max_l-2)) {
854  $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
855  $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
856  $cur_l = 3;
857  $ret = '';
858  $iOffset = $i;
859  $iEncStart = $i;
860  }
861  $enc_init = true;
862  $ret .= sprintf("=%02X", $k);
863  } else {
864  if ($iEncStart !== false) {
865  $cur_l++;
866  if ($cur_l > $max_l) {
867  $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
868  $aRet[] = "=?$default_charset?Q?$ret?=";
869  $iEncStart = false;
870  $iOffset = $i;
871  $cur_l = 0;
872  $ret = '';
873  } else {
874  $ret .= $string{$i};
875  }
876  }
877  }
878  break;
879  }
880  }
881 
882  if ($enc_init) {
883  if ($iEncStart !== false) {
884  $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
885  $aRet[] = "=?$default_charset?Q?$ret?=";
886  } else {
887  $aRet[] = substr($string,$iOffset);
888  }
889  $string = implode('',$aRet);
890  }
891  return $string;
892 }
893 
922 function encodeHeaderBase64($string,$charset) {
926  if (! function_exists('mb_strlen') ||
927  ! function_exists('mb_substr')) {
928  // set E_USER_WARNING
929  trigger_error('encodeHeaderBase64: Required mbstring functions are missing.',E_USER_WARNING);
930  // return false
931  return false;
932  }
933 
934  // initial return array
935  $aRet = array();
936 
943  $iMaxLength = 75 - strlen($charset) - 7;
944 
945  // set first character position
946  $iStartCharNum = 0;
947 
948  // loop through all characters. count characters and not bytes.
949  for ($iCharNum=1; $iCharNum<=mb_strlen($string,$charset); $iCharNum++) {
950  // encode string from starting character to current character.
951  $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
952 
953  // Check encoded string length
954  if(strlen($encoded_string)>$iMaxLength) {
955  // if string exceeds max length, reduce number of encoded characters and add encoded string part to array
956  $aRet[] = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum-1,$charset));
957 
958  // set new starting character
959  $iStartCharNum = $iCharNum-1;
960 
961  // encode last char (in case it is last character in string)
962  $encoded_string = base64_encode(mb_substr($string,$iStartCharNum,$iCharNum-$iStartCharNum,$charset));
963  } // if string is shorter than max length - add next character
964  }
965 
966  // add last encoded string to array
967  $aRet[] = $encoded_string;
968 
969  // set initial return string
970  $sRet = '';
971 
972  // loop through encoded strings
973  foreach($aRet as $string) {
974  // TODO: Do we want to control EOL (end-of-line) marker
975  if ($sRet!='') $sRet.= " ";
976 
977  // add header tags and encoded string to return string
978  $sRet.= '=?'.$charset.'?B?'.$string.'?=';
979  }
980 
981  return $sRet;
982 }
983 
984 /* This function trys to locate the entity_id of a specific mime element */
986  for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
987  if ($message->entities[$i]->header->type0 == 'multipart') {
988  $ret = find_ent_id($id, $message->entities[$i]);
989  } else {
990  if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
991 // if (sq_check_save_extension($message->entities[$i])) {
992  return $message->entities[$i]->entity_id;
993 // }
994  } elseif (!empty($message->entities[$i]->header->parameters['name'])) {
1000  if (strcasecmp($message->entities[$i]->header->parameters['name'], $id) == 0) {
1001  return $message->entities[$i]->entity_id;
1002  }
1003  }
1004  }
1005  }
1006  return $ret;
1007 }
1008 
1010  $filename = $message->getFilename();
1011  $ext = substr($filename, strrpos($filename,'.')+1);
1012  $save_extensions = array('jpg','jpeg','gif','png','bmp');
1013  return in_array($ext, $save_extensions);
1014 }
1015 
1016 
1029 function sq_defang(&$attvalue){
1030  $me = 'sq_defang';
1034  if (strpos($attvalue, '&') === false
1035  && strpos($attvalue, '\\') === false){
1036  return;
1037  }
1038  $m = false;
1039  do {
1040  $m = false;
1041  $m = $m || sq_deent($attvalue, '/\&#0*(\d+);*/s');
1042  $m = $m || sq_deent($attvalue, '/\&#x0*((\d|[a-f])+);*/si', true);
1043  $m = $m || sq_deent($attvalue, '/\\\\(\d+)/s', true);
1044  } while ($m == true);
1045  $attvalue = stripslashes($attvalue);
1046 }
1047 
1056 function sq_unspace(&$attvalue){
1057  $me = 'sq_unspace';
1058  if (strcspn($attvalue, "\t\r\n\0 ") != strlen($attvalue)){
1059  $attvalue = str_replace(Array("\t", "\r", "\n", "\0", " "),
1060  Array('', '', '', '', ''), $attvalue);
1061  }
1062 }
1063 
1072 function sq_fixIE_idiocy(&$attvalue) {
1073  // remove NUL
1074  $attvalue = str_replace("\0", "", $attvalue);
1075  // remove comments
1076  $attvalue = preg_replace("/(\/\*.*?\*\/)/","",$attvalue);
1077 
1078  // IE has the evil habit of accepting every possible value for the attribute expression.
1079  // The table below contains characters which are parsed by IE if they are used in the "expression"
1080  // attribute value.
1081  $aDangerousCharsReplacementTable = array(
1082  array('&#x029F;', '&#0671;' ,/* L UNICODE IPA Extension */
1083  '&#x0280;', '&#0640;' ,/* R UNICODE IPA Extension */
1084  '&#x0274;', '&#0628;' ,/* N UNICODE IPA Extension */
1085  '&#xFF25;', '&#65317;' ,/* Unicode FULLWIDTH LATIN CAPITAL LETTER E */
1086  '&#xFF45;', '&#65349;' ,/* Unicode FULLWIDTH LATIN SMALL LETTER E */
1087  '&#xFF38;', '&#65336;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER X */
1088  '&#xFF58;', '&#65368;',/* Unicode FULLWIDTH LATIN SMALL LETTER X */
1089  '&#xFF30;', '&#65328;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER P */
1090  '&#xFF50;', '&#65360;',/* Unicode FULLWIDTH LATIN SMALL LETTER P */
1091  '&#xFF32;', '&#65330;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER R */
1092  '&#xFF52;', '&#65362;',/* Unicode FULLWIDTH LATIN SMALL LETTER R */
1093  '&#xFF33;', '&#65331;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER S */
1094  '&#xFF53;', '&#65363;',/* Unicode FULLWIDTH LATIN SMALL LETTER S */
1095  '&#xFF29;', '&#65321;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER I */
1096  '&#xFF49;', '&#65353;',/* Unicode FULLWIDTH LATIN SMALL LETTER I */
1097  '&#xFF2F;', '&#65327;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER O */
1098  '&#xFF4F;', '&#65359;',/* Unicode FULLWIDTH LATIN SMALL LETTER O */
1099  '&#xFF2E;', '&#65326;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER N */
1100  '&#xFF4E;', '&#65358;',/* Unicode FULLWIDTH LATIN SMALL LETTER N */
1101  '&#xFF2C;', '&#65324;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER L */
1102  '&#xFF4C;', '&#65356;',/* Unicode FULLWIDTH LATIN SMALL LETTER L */
1103  '&#xFF35;', '&#65333;',/* Unicode FULLWIDTH LATIN CAPITAL LETTER U */
1104  '&#xFF55;', '&#65365;',/* Unicode FULLWIDTH LATIN SMALL LETTER U */
1105  '&#x207F;', '&#8319;' ,/* Unicode SUPERSCRIPT LATIN SMALL LETTER N */
1106  "\xEF\xBC\xA5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER E */ // in unicode this is some Chinese char range
1107  "\xEF\xBD\x85", /* Shift JIS FULLWIDTH LATIN SMALL LETTER E */
1108  "\xEF\xBC\xB8", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER X */
1109  "\xEF\xBD\x98", /* Shift JIS FULLWIDTH LATIN SMALL LETTER X */
1110  "\xEF\xBC\xB0", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER P */
1111  "\xEF\xBD\x90", /* Shift JIS FULLWIDTH LATIN SMALL LETTER P */
1112  "\xEF\xBC\xB2", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER R */
1113  "\xEF\xBD\x92", /* Shift JIS FULLWIDTH LATIN SMALL LETTER R */
1114  "\xEF\xBC\xB3", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER S */
1115  "\xEF\xBD\x93", /* Shift JIS FULLWIDTH LATIN SMALL LETTER S */
1116  "\xEF\xBC\xA9", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER I */
1117  "\xEF\xBD\x89", /* Shift JIS FULLWIDTH LATIN SMALL LETTER I */
1118  "\xEF\xBC\xAF", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER O */
1119  "\xEF\xBD\x8F", /* Shift JIS FULLWIDTH LATIN SMALL LETTER O */
1120  "\xEF\xBC\xAE", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER N */
1121  "\xEF\xBD\x8E", /* Shift JIS FULLWIDTH LATIN SMALL LETTER N */
1122  "\xEF\xBC\xAC", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER L */
1123  "\xEF\xBD\x8C", /* Shift JIS FULLWIDTH LATIN SMALL LETTER L */
1124  "\xEF\xBC\xB5", /* Shift JIS FULLWIDTH LATIN CAPITAL LETTER U */
1125  "\xEF\xBD\x95", /* Shift JIS FULLWIDTH LATIN SMALL LETTER U */
1126  "\xE2\x81\xBF", /* Shift JIS FULLWIDTH SUPERSCRIPT N */
1127  "\xCA\x9F", /* L UNICODE IPA Extension */
1128  "\xCA\x80", /* R UNICODE IPA Extension */
1129  "\xC9\xB4"), /* N UNICODE IPA Extension */
1130  array('l', 'l', 'r','r','n','n',
1131  'E','E','e','e','X','X','x','x','P','P','p','p','R','R','r','r','S','S','s','s','I','I',
1132  'i','i','O','O','o','o','N','N','n','n','L','L','l','l','U','U','u','u','n','n',
1133  'E','e','X','x','P','p','R','r','S','s','I','i','O','o','N','n','L','l','U','u','n','l','r','n'));
1134  $attvalue = str_replace($aDangerousCharsReplacementTable[0],$aDangerousCharsReplacementTable[1],$attvalue);
1135 
1136  // Escapes are useful for special characters like "{}[]()'&. In other cases they are
1137  // used for XSS.
1138  $attvalue = preg_replace("/(\\\\)([a-zA-Z]{1})/",'$2',$attvalue);
1139 }
1140 
1151 function sq_tagprint($tagname, $attary, $tagtype){
1152  $me = 'sq_tagprint';
1153 
1154  if ($tagtype == 2){
1155  $fulltag = '</' . $tagname . '>';
1156  } else {
1157  $fulltag = '<' . $tagname;
1158  if (is_array($attary) && sizeof($attary)){
1159  $atts = Array();
1160  while (list($attname, $attvalue) = each($attary)){
1161  array_push($atts, "$attname=$attvalue");
1162  }
1163  $fulltag .= ' ' . join(" ", $atts);
1164  }
1165  if ($tagtype == 3){
1166  $fulltag .= ' /';
1167  }
1168  $fulltag .= '>';
1169  }
1170  return $fulltag;
1171 }
1172 
1180 function sq_casenormalize(&$val){
1181  $val = strtolower($val);
1182 }
1183 
1194 function sq_skipspace($body, $offset){
1195  $me = 'sq_skipspace';
1196  preg_match('/^(\s*)/s', substr($body, $offset), $matches);
1197  if (sizeof($matches{1})){
1198  $count = strlen($matches{1});
1199  $offset += $count;
1200  }
1201  return $offset;
1202 }
1203 
1215 function sq_findnxstr($body, $offset, $needle){
1216  $me = 'sq_findnxstr';
1217  $pos = strpos($body, $needle, $offset);
1218  if ($pos === FALSE){
1219  $pos = strlen($body);
1220  }
1221  return $pos;
1222 }
1223 
1237 function sq_findnxreg($body, $offset, $reg){
1238  $me = 'sq_findnxreg';
1239  $matches = Array();
1240  $retarr = Array();
1241  preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
1242  if (!isset($matches{0}) || !$matches{0}){
1243  $retarr = false;
1244  } else {
1245  $retarr{0} = $offset + strlen($matches{1});
1246  $retarr{1} = $matches{1};
1247  $retarr{2} = $matches{2};
1248  }
1249  return $retarr;
1250 }
1251 
1266 function sq_getnxtag($body, $offset){
1267  $me = 'sq_getnxtag';
1268  if ($offset > strlen($body)){
1269  return false;
1270  }
1271  $lt = sq_findnxstr($body, $offset, "<");
1272  if ($lt == strlen($body)){
1273  return false;
1274  }
1280  $pos = sq_skipspace($body, $lt+1);
1281  if ($pos >= strlen($body)){
1282  return Array(false, false, false, $lt, strlen($body));
1283  }
1293  $tagtype = false;
1294  switch (substr($body, $pos, 1)){
1295  case '/':
1296  $tagtype = 2;
1297  $pos++;
1298  break;
1299  case '!':
1303  if (substr($body, $pos+1, 2) == "--"){
1304  $gt = strpos($body, "-->", $pos);
1305  if ($gt === false){
1306  $gt = strlen($body);
1307  } else {
1308  $gt += 2;
1309  }
1310  return Array(false, false, false, $lt, $gt);
1311  } else {
1312  $gt = sq_findnxstr($body, $pos, ">");
1313  return Array(false, false, false, $lt, $gt);
1314  }
1315  break;
1316  default:
1321  $tagtype = 1;
1322  break;
1323  }
1324 
1325  $tag_start = $pos;
1326  $tagname = '';
1330  $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1331  if ($regary == false){
1332  return Array(false, false, false, $lt, strlen($body));
1333  }
1334  list($pos, $tagname, $match) = $regary;
1335  $tagname = strtolower($tagname);
1336 
1345  switch ($match){
1346  case '/':
1352  if (substr($body, $pos, 2) == "/>"){
1353  $pos++;
1354  $tagtype = 3;
1355  } else {
1356  $gt = sq_findnxstr($body, $pos, ">");
1357  $retary = Array(false, false, false, $lt, $gt);
1358  return $retary;
1359  }
1360  case '>':
1361  return Array($tagname, false, $tagtype, $lt, $pos);
1362  break;
1363  default:
1367  if (!preg_match('/\s/', $match)){
1371  $gt = sq_findnxstr($body, $lt, ">");
1372  return Array(false, false, false, $lt, $gt);
1373  }
1374  break;
1375  }
1376 
1384  $attname = '';
1385  $atttype = false;
1386  $attary = Array();
1387 
1388  while ($pos <= strlen($body)){
1389  $pos = sq_skipspace($body, $pos);
1390  if ($pos == strlen($body)){
1394  return Array(false, false, false, $lt, $pos);
1395  }
1400  $matches = Array();
1401  if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
1405  $pos += strlen($matches{1});
1406  if ($matches{2} == "/>"){
1407  $tagtype = 3;
1408  $pos++;
1409  }
1410  return Array($tagname, $attary, $tagtype, $lt, $pos);
1411  }
1412 
1430  $regary = sq_findnxreg($body, $pos, "[^:\w\-_]");
1431  if ($regary == false){
1435  return Array(false, false, false, $lt, strlen($body));
1436  }
1437  list($pos, $attname, $match) = $regary;
1438  $attname = strtolower($attname);
1447  switch($match){
1448  case '/':
1454  if (substr($body, $pos, 2) == "/>"){
1455  $pos++;
1456  $tagtype = 3;
1457  } else {
1458  $gt = sq_findnxstr($body, $pos, ">");
1459  $retary = Array(false, false, false, $lt, $gt);
1460  return $retary;
1461  }
1462  case '>':
1463  $attary{$attname} = '"yes"';
1464  return Array($tagname, $attary, $tagtype, $lt, $pos);
1465  break;
1466  default:
1470  $pos = sq_skipspace($body, $pos);
1471  $char = substr($body, $pos, 1);
1480  if ($char == "="){
1481  $pos++;
1482  $pos = sq_skipspace($body, $pos);
1489  $quot = substr($body, $pos, 1);
1490  if ($quot == "'"){
1491  $regary = sq_findnxreg($body, $pos+1, "\'");
1492  if ($regary == false){
1493  return Array(false, false, false, $lt, strlen($body));
1494  }
1495  list($pos, $attval, $match) = $regary;
1496  $pos++;
1497  $attary{$attname} = "'" . $attval . "'";
1498  } else if ($quot == '"'){
1499  $regary = sq_findnxreg($body, $pos+1, '\"');
1500  if ($regary == false){
1501  return Array(false, false, false, $lt, strlen($body));
1502  }
1503  list($pos, $attval, $match) = $regary;
1504  $pos++;
1505  $attary{$attname} = '"' . $attval . '"';
1506  } else {
1510  $regary = sq_findnxreg($body, $pos, "[\s>]");
1511  if ($regary == false){
1512  return Array(false, false, false, $lt, strlen($body));
1513  }
1514  list($pos, $attval, $match) = $regary;
1518  $attval = preg_replace("/\"/s", "&quot;", $attval);
1519  $attary{$attname} = '"' . $attval . '"';
1520  }
1521  } else if (preg_match("|[\w/>]|", $char)) {
1525  $attary{$attname} = '"yes"';
1526  } else {
1530  $gt = sq_findnxstr($body, $pos, ">");
1531  return Array(false, false, false, $lt, $gt);
1532  }
1533  break;
1534  }
1535  }
1540  return Array(false, false, false, $lt, strlen($body));
1541 }
1542 
1551 function sq_deent(&$attvalue, $regex, $hex=false){
1552  $me = 'sq_deent';
1553  $ret_match = false;
1554  preg_match_all($regex, $attvalue, $matches);
1555  if (is_array($matches) && sizeof($matches[0]) > 0){
1556  $repl = Array();
1557  for ($i = 0; $i < sizeof($matches[0]); $i++){
1558  $numval = $matches[1][$i];
1559  if ($hex){
1560  $numval = hexdec($numval);
1561  }
1562  $repl{$matches[0][$i]} = chr($numval);
1563  }
1564  $attvalue = strtr($attvalue, $repl);
1565  return true;
1566  } else {
1567  return false;
1568  }
1569 }
1570 
1584 function sq_fixatts($tagname,
1585  $attary,
1586  $rm_attnames,
1587  $bad_attvals,
1588  $add_attr_to_tag,
1589  $message,
1590  $id,
1591  $mailbox
1592  ){
1593  $me = 'sq_fixatts';
1594  while (list($attname, $attvalue) = each($attary)){
1598  foreach ($rm_attnames as $matchtag=>$matchattrs){
1599  if (preg_match($matchtag, $tagname)){
1600  foreach ($matchattrs as $matchattr){
1601  if (preg_match($matchattr, $attname)){
1602  unset($attary{$attname});
1603  continue;
1604  }
1605  }
1606  }
1607  }
1608 
1612  sq_fixIE_idiocy($attvalue);
1613 
1617  $oldattvalue = $attvalue;
1618  sq_defang($attvalue);
1619  if ($attname == 'style' && $attvalue !== $oldattvalue) {
1620  // entities are used in the attribute value. In 99% of the cases it's there as XSS
1621  // i.e.<div style="{ left:exp&#x0280;essio&#x0274;( alert('XSS') ) }">
1622  $attvalue = "idiocy";
1623  $attary{$attname} = $attvalue;
1624  }
1625  sq_unspace($attvalue);
1626 
1633  foreach ($bad_attvals as $matchtag=>$matchattrs){
1634  if (preg_match($matchtag, $tagname)){
1635  foreach ($matchattrs as $matchattr=>$valary){
1636  if (preg_match($matchattr, $attname)){
1642  list($valmatch, $valrepl) = $valary;
1643  $newvalue =
1644  preg_replace($valmatch, $valrepl, $attvalue);
1645  if ($newvalue != $attvalue){
1646  $attary{$attname} = $newvalue;
1647  $attvalue = $newvalue;
1648  }
1649  }
1650  }
1651  }
1652  }
1653  if ($attname == 'style') {
1654  if (preg_match('/[\0-\37\200-\377]+/',$attvalue)) {
1655  // 8bit and control characters in style attribute values can be used for XSS, remove them
1656  $attary{$attname} = '"disallowed character"';
1657  }
1658  preg_match_all("/url\s*\((.+)\)/si",$attvalue,$aMatch);
1659  if (count($aMatch)) {
1660  foreach($aMatch[1] as $sMatch) {
1661  // url value
1662  $urlvalue = $sMatch;
1663  sq_fix_url($attname, $urlvalue, $message, $id, $mailbox,"'");
1664  $attary{$attname} = str_replace($sMatch,$urlvalue,$attvalue);
1665  }
1666  }
1667  }
1671  else if ($attname == 'href' || $attname == 'src' || $attname == 'background') {
1672  sq_fix_url($attname, $attvalue, $message, $id, $mailbox);
1673  $attary{$attname} = $attvalue;
1674  }
1675  }
1679  foreach ($add_attr_to_tag as $matchtag=>$addattary){
1680  if (preg_match($matchtag, $tagname)){
1681  $attary = array_merge($attary, $addattary);
1682  }
1683  }
1684  return $attary;
1685 }
1686 
1696 function sq_fix_url($attname, &$attvalue, $message, $id, $mailbox,$sQuote = '"') {
1697  $attvalue = trim($attvalue);
1698  if ($attvalue && ($attvalue[0] =='"'|| $attvalue[0] == "'")) {
1699  // remove the double quotes
1700  $sQuote = $attvalue[0];
1701  $attvalue = trim(substr($attvalue,1,-1));
1702  }
1703 
1704  // If there's no "view_unsafe_images" variable in the URL, turn unsafe
1705  // images off by default.
1706  if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
1707  $view_unsafe_images = false;
1708  }
1709 
1710  $secremoveimg = '../images/' . _("sec_remove_eng.png");
1711 
1718  if ($attvalue == '') {
1719  $attvalue = '"' . SM_PATH . 'images/blank.png"';
1720  } else {
1721  // first, disallow 8 bit characters and control characters
1722  if (preg_match('/[\0-\37\200-\377]+/',$attvalue)) {
1723  switch ($attname) {
1724  case 'href':
1725  $attvalue = $sQuote . 'http://invalid-stuff-detected.example.com' . $sQuote;
1726  break;
1727  default:
1728  $attvalue = $sQuote . SM_PATH . 'images/blank.png'. $sQuote;
1729  break;
1730  }
1731  } else {
1732  $aUrl = parse_url($attvalue);
1733  if (isset($aUrl['scheme'])) {
1734  switch(strtolower($aUrl['scheme'])) {
1735  case 'mailto':
1736  case 'http':
1737  case 'https':
1738  case 'ftp':
1739  if ($attname != 'href') {
1740  if ($view_unsafe_images == false) {
1741  $attvalue = $sQuote . $secremoveimg . $sQuote;
1742  } else {
1743  if (isset($aUrl['path'])) {
1744 
1745  // No one has been able to show that image URIs
1746  // can be exploited, so for now, no restrictions
1747  // are made at all. If this proves to be a problem,
1748  // the commented-out code below can be of help.
1749  // (One consideration is that I see nothing in this
1750  // function that specifically says that we will
1751  // only ever arrive here when inspecting an image
1752  // tag, although that does seem to be the end
1753  // result - e.g., <script src="..."> where malicious
1754  // image URIs are in fact a problem are already
1755  // filtered out elsewhere.
1756  /* ---------------------------------
1757  // validate image extension.
1758  $ext = strtolower(substr($aUrl['path'],strrpos($aUrl['path'],'.')));
1759  if (!in_array($ext,array('.jpeg','.jpg','xjpeg','.gif','.bmp','.jpe','.png','.xbm'))) {
1760  // If URI is to something other than
1761  // a regular image file, get the contents
1762  // and try to see if it is an image.
1763  // Don't use Fileinfo (finfo_file()) because
1764  // we'd need to make the admin configure the
1765  // location of the magic.mime file (FIXME: add finfo_file() support later?)
1766  //
1767  $mime_type = '';
1768  if (function_exists('mime_content_type')
1769  && ($FILE = @fopen($attvalue, 'rb', FALSE))) {
1770 
1771  // fetch file
1772  //
1773  $file_contents = '';
1774  while (!feof($FILE)) {
1775  $file_contents .= fread($FILE, 8192);
1776  }
1777  fclose($FILE);
1778 
1779  // store file locally
1780  //
1781  global $attachment_dir, $username;
1782  $hashed_attachment_dir = getHashedDir($username, $attachment_dir);
1783  $localfilename = GenerateRandomString(32, '', 7);
1784  $full_localfilename = "$hashed_attachment_dir/$localfilename";
1785  while (file_exists($full_localfilename)) {
1786  $localfilename = GenerateRandomString(32, '', 7);
1787  $full_localfilename = "$hashed_attachment_dir/$localfilename";
1788  }
1789  $FILE = fopen("$hashed_attachment_dir/$localfilename", 'wb');
1790  fwrite($FILE, $file_contents);
1791  fclose($FILE);
1792 
1793  // get mime type and remove file
1794  //
1795  $mime_type = mime_content_type("$hashed_attachment_dir/$localfilename");
1796  unlink("$hashed_attachment_dir/$localfilename");
1797  }
1798  // debug: echo "$attvalue FILE TYPE IS $mime_type<HR>";
1799  if (substr(strtolower($mime_type), 0, 5) != 'image') {
1800  $attvalue = $sQuote . SM_PATH . 'images/blank.png'. $sQuote;
1801  }
1802  }
1803  --------------------------------- */
1804  } else {
1805  $attvalue = $sQuote . SM_PATH . 'images/blank.png'. $sQuote;
1806  }
1807  }
1808  } else {
1809  $attvalue = $sQuote . $attvalue . $sQuote;
1810  }
1811  break;
1812  case 'outbind':
1818  $attvalue = $sQuote . sq_cid2http($message, $id, $attvalue, $mailbox) . $sQuote;
1819  break;
1820  case 'cid':
1824  $attvalue = $sQuote . sq_cid2http($message, $id, $attvalue, $mailbox) . $sQuote;
1825  break;
1826  default:
1827  $attvalue = $sQuote . SM_PATH . 'images/blank.png' . $sQuote;
1828  break;
1829  }
1830  } else {
1831  if (!(isset($aUrl['path']) && $aUrl['path'] == $secremoveimg)) {
1832  // parse_url did not lead to satisfying result
1833  $attvalue = $sQuote . SM_PATH . 'images/blank.png' . $sQuote;
1834  }
1835  }
1836  }
1837  }
1838 }
1839 
1851  // FIXME: Is the global "view_unsafe_images" really needed here?
1852  global $view_unsafe_images;
1853  $me = 'sq_fixstyle';
1854 
1855  // workaround for </style> in between comments
1856  $iCurrentPos = $pos;
1857  $content = '';
1858  $sToken = '';
1859  $bSucces = false;
1860  $bEndTag = false;
1861  for ($i=$pos,$iCount=strlen($body);$i<$iCount;++$i) {
1862  $char = $body{$i};
1863  switch ($char) {
1864  case '<':
1865  $sToken = $char;
1866  break;
1867  case '/':
1868  if ($sToken == '<') {
1869  $sToken .= $char;
1870  $bEndTag = true;
1871  } else {
1872  $content .= $char;
1873  }
1874  break;
1875  case '>':
1876  if ($bEndTag) {
1877  $sToken .= $char;
1878  if (preg_match('/<\/\s*style\s*>/i',$sToken,$aMatch)) {
1879  $newpos = $i + 1;
1880  $bSucces = true;
1881  break 2;
1882  } else {
1883  $content .= $sToken;
1884  }
1885  $bEndTag = false;
1886  } else {
1887  $content .= $char;
1888  }
1889  break;
1890  case '!':
1891  if ($sToken == '<') {
1892  // possible comment
1893  if (isset($body{$i+2}) && substr($body,$i,3) == '!--') {
1894  $i = strpos($body,'-->',$i+3);
1895  if ($i === false) { // no end comment
1896  $i = strlen($body);
1897  }
1898  $sToken = '';
1899  }
1900  } else {
1901  $content .= $char;
1902  }
1903  break;
1904  default:
1905  if ($bEndTag) {
1906  $sToken .= $char;
1907  } else {
1908  $content .= $char;
1909  }
1910  break;
1911  }
1912  }
1913  if ($bSucces == FALSE){
1914  return array(FALSE, strlen($body));
1915  }
1916 
1923  $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1924  $secremoveimg = '../images/' . _("sec_remove_eng.png");
1925 
1926  // first check for 8bit sequences and disallowed control characters
1927  if (preg_match('/[\16-\37\200-\377]+/',$content)) {
1928  $content = '<!-- style block removed by html filter due to presence of 8bit characters -->';
1929  return array($content, $newpos);
1930  }
1931 
1932  // IE Sucks hard. We have a special function for it.
1934 
1935  // remove @import line
1936  $content = preg_replace("/^\s*(@import.*)$/mi","\n<!-- @import rules forbidden -->\n",$content);
1937 
1941  // translate ur\l and variations into url (IE parses that)
1942  // TODO check if the sq_fixIE_idiocy function already handles this.
1943  $content = preg_replace("/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i",'url', $content);
1944  preg_match_all("/url\s*\((.+)\)/si",$content,$aMatch);
1945  if (count($aMatch)) {
1946  $aValue = $aReplace = array();
1947  foreach($aMatch[1] as $sMatch) {
1948  // url value
1949  $urlvalue = $sMatch;
1950  sq_fix_url('style',$urlvalue, $message, $id, $mailbox,"'");
1951  $aValue[] = $sMatch;
1952  $aReplace[] = $urlvalue;
1953  }
1954  $content = str_replace($aValue,$aReplace,$content);
1955  }
1956 
1960  $contentTemp = $content;
1961  sq_defang($contentTemp);
1962  sq_unspace($contentTemp);
1963 
1974  $match = Array('/\/\*.*\*\//',
1975  '/expression/i',
1976  '/behaviou*r/i',
1977  '/binding/i',
1978  '/include-source/i',
1979  '/javascript/i',
1980  '/script/i',
1981  '/position/i');
1982  $replace = Array('','idiocy', 'idiocy', 'idiocy', 'idiocy', 'idiocy', 'idiocy', '');
1983  $contentNew = preg_replace($match, $replace, $contentTemp);
1984  if ($contentNew !== $contentTemp) {
1985  // insecure css declarations are used. From now on we don't care
1986  // anymore if the css is destroyed by sq_deent, sq_unspace or sq_unbackslash
1987  $content = $contentNew;
1988  }
1989  return array($content, $newpos);
1990 }
1991 
1992 
2003 function sq_cid2http($message, $id, $cidurl, $mailbox){
2007  $quotchar = substr($cidurl, 0, 1);
2008  if ($quotchar == '"' || $quotchar == "'"){
2009  $cidurl = str_replace($quotchar, "", $cidurl);
2010  } else {
2011  $quotchar = '';
2012  }
2013  $cidurl = substr(trim($cidurl), 4);
2014 
2015  $match_str = '/\{.*?\}\//';
2016  $str_rep = '';
2017  $cidurl = preg_replace($match_str, $str_rep, $cidurl);
2018 
2019  $linkurl = find_ent_id($cidurl, $message);
2020  /* in case of non-safe cid links $httpurl should be replaced by a sort of
2021  unsafe link image */
2022  $httpurl = '';
2023 
2033  if (empty($linkurl)) {
2034  if (preg_match('/{.*}\//', $cidurl)) {
2035  $cidurl = preg_replace('/{.*}\//','', $cidurl);
2036  if (!empty($cidurl)) {
2037  $linkurl = find_ent_id($cidurl, $message);
2038  }
2039  }
2040  }
2041 
2042  if (!empty($linkurl)) {
2043  $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
2044  "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
2045  '&amp;ent_id=' . $linkurl . $quotchar;
2046  } else {
2051  $httpurl = $quotchar . SM_PATH . 'images/blank.png' . $quotchar;
2052  }
2053 
2054  return $httpurl;
2055 }
2056 
2067 function sq_body2div($attary, $mailbox, $message, $id){
2068  $me = 'sq_body2div';
2069  $divattary = Array('class' => "'bodyclass'");
2070  $bgcolor = '#ffffff';
2071  $text = '#000000';
2072  $styledef = '';
2073  if (is_array($attary) && sizeof($attary) > 0){
2074  foreach ($attary as $attname=>$attvalue){
2075  $quotchar = substr($attvalue, 0, 1);
2076  $attvalue = str_replace($quotchar, "", $attvalue);
2077  switch ($attname){
2078  case 'background':
2079  $attvalue = sq_cid2http($message, $id, $attvalue, $mailbox);
2080  $styledef .= "background-image: url('$attvalue'); ";
2081  break;
2082  case 'bgcolor':
2083  $styledef .= "background-color: $attvalue; ";
2084  break;
2085  case 'text':
2086  $styledef .= "color: $attvalue; ";
2087  break;
2088  }
2089  }
2090  if (strlen($styledef) > 0){
2091  $divattary{"style"} = "\"$styledef\"";
2092  }
2093  }
2094  return $divattary;
2095 }
2096 
2118  $tag_list,
2119  $rm_tags_with_content,
2120  $self_closing_tags,
2121  $force_tag_closing,
2122  $rm_attnames,
2123  $bad_attvals,
2124  $add_attr_to_tag,
2125  $message,
2126  $id,
2127  $mailbox
2128  ){
2129  $me = 'sq_sanitize';
2130  $rm_tags = array_shift($tag_list);
2134  @array_walk($tag_list, 'sq_casenormalize');
2135  @array_walk($rm_tags_with_content, 'sq_casenormalize');
2136  @array_walk($self_closing_tags, 'sq_casenormalize');
2142  $curpos = 0;
2143  $open_tags = Array();
2144  $trusted = "\n<!-- begin sanitized html -->\n";
2145  $skip_content = false;
2150  $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
2151 
2152  while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
2153  list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
2154  $free_content = substr($body, $curpos, $lt-$curpos);
2158  if ($tagname == "style" && $tagtype == 1){
2159  list($free_content, $curpos) =
2161  if ($free_content != FALSE){
2162  $attary = sq_fixatts($tagname,
2163  $attary,
2164  $rm_attnames,
2165  $bad_attvals,
2166  $add_attr_to_tag,
2167  $message,
2168  $id,
2169  $mailbox
2170  );
2171  $trusted .= sq_tagprint($tagname, $attary, $tagtype);
2172  $trusted .= $free_content;
2173  $trusted .= sq_tagprint($tagname, false, 2);
2174  }
2175  continue;
2176  }
2177  if ($skip_content == false){
2178  $trusted .= $free_content;
2179  }
2180  if ($tagname != FALSE){
2181  if ($tagtype == 2){
2182  if ($skip_content == $tagname){
2186  $tagname = false;
2187  $skip_content = false;
2188  } else {
2189  if ($skip_content == false){
2190  if ($tagname == "body"){
2191  $tagname = "div";
2192  }
2193  if (isset($open_tags{$tagname}) &&
2194  $open_tags{$tagname} > 0){
2195  $open_tags{$tagname}--;
2196  } else {
2197  $tagname = false;
2198  }
2199  }
2200  }
2201  } else {
2205  if ($skip_content == false){
2210  if ($tagtype == 1
2211  && in_array($tagname, $self_closing_tags)){
2212  $tagtype = 3;
2213  }
2218  if ($tagtype == 1 &&
2219  in_array($tagname, $rm_tags_with_content)){
2220  $skip_content = $tagname;
2221  } else {
2222  if (($rm_tags == false
2223  && in_array($tagname, $tag_list)) ||
2224  ($rm_tags == true &&
2225  !in_array($tagname, $tag_list))){
2226  $tagname = false;
2227  } else {
2231  if ($tagname == "body"){
2232  $tagname = "div";
2233  $attary = sq_body2div($attary, $mailbox,
2234  $message, $id);
2235  }
2236  if ($tagtype == 1){
2237  if (isset($open_tags{$tagname})){
2238  $open_tags{$tagname}++;
2239  } else {
2240  $open_tags{$tagname}=1;
2241  }
2242  }
2246  if (is_array($attary) && sizeof($attary) > 0){
2247  $attary = sq_fixatts($tagname,
2248  $attary,
2249  $rm_attnames,
2250  $bad_attvals,
2251  $add_attr_to_tag,
2252  $message,
2253  $id,
2254  $mailbox
2255  );
2256  }
2257  }
2258  }
2259  }
2260  }
2261  if ($tagname != false && $skip_content == false){
2262  $trusted .= sq_tagprint($tagname, $attary, $tagtype);
2263  }
2264  }
2265  $curpos = $gt+1;
2266  }
2267  $trusted .= substr($body, $curpos, strlen($body)-$curpos);
2268  if ($force_tag_closing == true){
2269  foreach ($open_tags as $tagname=>$opentimes){
2270  while ($opentimes > 0){
2271  $trusted .= '</' . $tagname . '>';
2272  $opentimes--;
2273  }
2274  }
2275  $trusted .= "\n";
2276  }
2277  $trusted .= "<!-- end sanitized html -->\n";
2278  return $trusted;
2279 }
2280 
2291 function magicHTML($body, $id, $message, $mailbox = 'INBOX', $take_mailto_links =true) {
2292 
2293  require_once(SM_PATH . 'functions/url_parser.php'); // for $MailTo_PReg_Match
2294 
2296  $has_unsafe_images;
2301  $tag_list = Array(
2302  false,
2303  "object",
2304  "meta",
2305  "html",
2306  "head",
2307  "base",
2308  "link",
2309  "frame",
2310  "iframe",
2311  "plaintext",
2312  "marquee"
2313  );
2314 
2315  $rm_tags_with_content = Array(
2316  "script",
2317  "applet",
2318  "embed",
2319  "title",
2320  "frameset",
2321  "xmp",
2322  "xml"
2323  );
2324 
2325  $self_closing_tags = Array(
2326  "img",
2327  "br",
2328  "hr",
2329  "input",
2330  "outbind"
2331  );
2332 
2333  $force_tag_closing = true;
2334 
2335  $rm_attnames = Array(
2336  "/.*/" =>
2337  Array(
2338  "/target/i",
2339  "/^on.*/i",
2340  "/^dynsrc/i",
2341  "/^data.*/i",
2342  "/^lowsrc.*/i"
2343  )
2344  );
2345 
2346  $secremoveimg = "../images/" . _("sec_remove_eng.png");
2347  $bad_attvals = Array(
2348  "/.*/" =>
2349  Array(
2350  "/^src|background/i" =>
2351  Array(
2352  Array(
2353  "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2354  "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2355  "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2356  ),
2357  Array(
2358  "\\1$secremoveimg\\2",
2359  "\\1$secremoveimg\\2",
2360  "\\1$secremoveimg\\2"
2361  )
2362  ),
2363  "/^href|action/i" =>
2364  Array(
2365  Array(
2366  "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
2367  "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
2368  "/^([\'\"])\s*about\s*:.*([\'\"])/si"
2369  ),
2370  Array(
2371  "\\1#\\1",
2372  "\\1#\\1",
2373  "\\1#\\1"
2374  )
2375  ),
2376  "/^style/i" =>
2377  Array(
2378  Array(
2379  "/\/\*.*\*\//",
2380  "/expression/i",
2381  "/binding/i",
2382  "/behaviou*r/i",
2383  "/include-source/i",
2384 
2385  // position:relative can also be exploited
2386  // to put content outside of email body area
2387  // and position:fixed is similarly exploitable
2388  // as position:absolute, so we'll remove it
2389  // altogether....
2390  //
2391  // Does this screw up legitimate HTML messages?
2392  // If so, the only fix I see is to allow position
2393  // attributes (any values? I think we still have
2394  // to block static and fixed) only if $use_iframe
2395  // is enabled (1.5.0+)
2396  //
2397  // was: "/position\s*:\s*absolute/i",
2398  //
2399  "/position\s*:/i",
2400 
2401  "/(\\\\)?u(\\\\)?r(\\\\)?l(\\\\)?/i",
2402  "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
2403  "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
2404  "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si",
2405  "/(.*)\s*:\s*url\s*\(\s*([\'\"]*)\s*\S+script\s*:.*([\'\"]*)\s*\)/si",
2406  ),
2407  Array(
2408  "",
2409  "idiocy",
2410  "idiocy",
2411  "idiocy",
2412  "idiocy",
2413  "idiocy",
2414  "url",
2415  "url(\\1#\\1)",
2416  "url(\\1#\\1)",
2417  "url(\\1#\\1)",
2418  "\\1:url(\\2#\\3)"
2419  )
2420  )
2421  )
2422  );
2423 
2424  // If there's no "view_unsafe_images" variable in the URL, turn unsafe
2425  // images off by default.
2426  if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
2427  $view_unsafe_images = false;
2428  }
2429 
2430  if (!$view_unsafe_images){
2435  array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
2436  '/^([\'\"])\s*https*:.*([\'\"])/si');
2437  array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
2438  "\\1$secremoveimg\\1");
2439  array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
2440  '/url\([\'\"]?https?:[^\)]*[\'\"]?\)/si');
2441  array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
2442  "url(\\1$secremoveimg\\1)");
2443  }
2444 
2445  $add_attr_to_tag = Array(
2446  "/^a$/i" =>
2447  Array('target'=>'"_blank"',
2448  'title'=>'"'._("This external link will open in a new window").'"'
2449  )
2450  );
2451  $trusted = sq_sanitize($body,
2452  $tag_list,
2453  $rm_tags_with_content,
2454  $self_closing_tags,
2455  $force_tag_closing,
2456  $rm_attnames,
2457  $bad_attvals,
2458  $add_attr_to_tag,
2459  $message,
2460  $id,
2461  $mailbox
2462  );
2463  if (strpos($trusted,$secremoveimg)){
2464  $has_unsafe_images = true;
2465  }
2466 
2467  // we want to parse mailto's in HTML output, change to SM compose links
2468  // this is a modified version of code from url_parser.php... but Marc is
2469  // right: we need a better filtering implementation; adding this randomly
2470  // here is not a great solution
2471  //
2472  if ($take_mailto_links) {
2473  // parseUrl($trusted); // this even parses URLs inside of tags... too aggressive
2474  global $MailTo_PReg_Match;
2475  $MailTo_PReg_Match = '/mailto:' . substr($MailTo_PReg_Match, 1) ;
2476  if ((preg_match_all($MailTo_PReg_Match, $trusted, $regs)) && ($regs[0][0] != '')) {
2477  foreach ($regs[0] as $i => $mailto_before) {
2478  $mailto_params = $regs[10][$i];
2479  // get rid of any tailing quote since we have to add send_to to the end
2480  //
2481  if (substr($mailto_before, strlen($mailto_before) - 1) == '"')
2482  $mailto_before = substr($mailto_before, 0, strlen($mailto_before) - 1);
2483  if (substr($mailto_params, strlen($mailto_params) - 1) == '"')
2484  $mailto_params = substr($mailto_params, 0, strlen($mailto_params) - 1);
2485 
2486  if ($regs[1][$i]) { //if there is an email addr before '?', we need to merge it with the params
2487  $to = 'to=' . $regs[1][$i];
2488  if (strpos($mailto_params, 'to=') > -1) //already a 'to='
2489  $mailto_params = str_replace('to=', $to . '%2C%20', $mailto_params);
2490  else {
2491  if ($mailto_params) //already some params, append to them
2492  $mailto_params .= '&amp;' . $to;
2493  else
2494  $mailto_params .= '?' . $to;
2495  }
2496  }
2497 
2498  $url_str = preg_replace(array('/to=/i', '/(?<!b)cc=/i', '/bcc=/i'), array('send_to=', 'send_to_cc=', 'send_to_bcc='), $mailto_params);
2499 
2500  // we'll already have target=_blank, no need to allow comp_in_new
2501  // here (which would be a lot more work anyway)
2502  //
2503  global $compose_new_win;
2504  $temp_comp_in_new = $compose_new_win;
2505  $compose_new_win = 0;
2506  $comp_uri = makeComposeLink('src/compose.php' . $url_str, $mailto_before);
2507  $compose_new_win = $temp_comp_in_new;
2508 
2509  // remove <a href=" and anything after the next quote (we only
2510  // need the uri, not the link HTML) in compose uri
2511  //
2512  $comp_uri = substr($comp_uri, 9);
2513  $comp_uri = substr($comp_uri, 0, strpos($comp_uri, '"', 1));
2514  $trusted = str_replace($mailto_before, $comp_uri, $trusted);
2515  }
2516  }
2517  }
2518 
2519  return $trusted;
2520 }
2521 
2536 function SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0) {
2538  $isIE = $isIE6plus = false;
2539 
2540  sqgetGlobalVar('HTTP_USER_AGENT', $HTTP_USER_AGENT, SQ_SERVER);
2541 
2542  if (strstr($HTTP_USER_AGENT, 'compatible; MSIE ') !== false &&
2543  strstr($HTTP_USER_AGENT, 'Opera') === false) {
2544  $isIE = true;
2545  }
2546 
2547  if (preg_match('/compatible; MSIE ([0-9]+)/', $HTTP_USER_AGENT, $match) &&
2548  ((int)$match[1]) >= 6 && strstr($HTTP_USER_AGENT, 'Opera') === false) {
2549  $isIE6plus = true;
2550  }
2551 
2552  if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
2553  function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
2554  $filename =
2555  $languages[$squirrelmail_language]['XTRA_CODE']('downloadfilename', $filename, $HTTP_USER_AGENT);
2556  } else {
2557  $filename = preg_replace('/[\\\\\/:*?"<>|;]/', '_', str_replace('&#32;', ' ', $filename));
2558  }
2559 
2560  // A Pox on Microsoft and it's Internet Explorer!
2561  //
2562  // IE has lots of bugs with file downloads.
2563  // It also has problems with SSL. Both of these cause problems
2564  // for us in this function.
2565  //
2566  // See this article on Cache Control headers and SSL
2567  // http://support.microsoft.com/default.aspx?scid=kb;en-us;323308
2568  //
2569  // The best thing you can do for IE is to upgrade to the latest
2570  // version
2571  //set all the Cache Control Headers for IE
2572  if ($isIE) {
2573  $filename=rawurlencode($filename);
2574  header ("Pragma: public");
2575  header ("Cache-Control: no-store, max-age=0, no-cache, must-revalidate"); // HTTP/1.1
2576  header ("Cache-Control: post-check=0, pre-check=0", false);
2577  header ("Cache-Control: private");
2578 
2579  //set the inline header for IE, we'll add the attachment header later if we need it
2580  header ("Content-Disposition: inline; filename=$filename");
2581  }
2582 
2583  if (!$force) {
2584  // Try to show in browser window
2585  header ("Content-Disposition: inline; filename=\"$filename\"");
2586  header ("Content-Type: $type0/$type1; name=\"$filename\"");
2587  } else {
2588  // Try to pop up the "save as" box
2589 
2590  // IE makes this hard. It pops up 2 save boxes, or none.
2591  // http://support.microsoft.com/support/kb/articles/Q238/5/88.ASP
2592  // http://support.microsoft.com/default.aspx?scid=kb;EN-US;260519
2593  // But, according to Microsoft, it is "RFC compliant but doesn't
2594  // take into account some deviations that allowed within the
2595  // specification." Doesn't that mean RFC non-compliant?
2596  // http://support.microsoft.com/support/kb/articles/Q258/4/52.ASP
2597 
2598  // all browsers need the application/octet-stream header for this
2599  header ("Content-Type: application/octet-stream; name=\"$filename\"");
2600 
2601  // http://support.microsoft.com/support/kb/articles/Q182/3/15.asp
2602  // Do not have quotes around filename, but that applied to
2603  // "attachment"... does it apply to inline too?
2604  header ("Content-Disposition: attachment; filename=\"$filename\"");
2605 
2606  if ($isIE && !$isIE6plus) {
2607  // This combination seems to work mostly. IE 5.5 SP 1 has
2608  // known issues (see the Microsoft Knowledge Base)
2609 
2610  // This works for most types, but doesn't work with Word files
2611  header ("Content-Type: application/download; name=\"$filename\"");
2612  // This is to prevent IE for MIME sniffing and auto open a file in IE
2613  header ("Content-Type: application/force-download; name=\"$filename\"");
2614  // These are spares, just in case. :-)
2615  //header("Content-Type: $type0/$type1; name=\"$filename\"");
2616  //header("Content-Type: application/x-msdownload; name=\"$filename\"");
2617  //header("Content-Type: application/octet-stream; name=\"$filename\"");
2618  } else if ($isIE) {
2619  // This is to prevent IE for MIME sniffing and auto open a file in IE
2620  header ("Content-Type: application/force-download; name=\"$filename\"");
2621  } else {
2622  // another application/octet-stream forces download for Netscape
2623  header ("Content-Type: application/octet-stream; name=\"$filename\"");
2624  }
2625  }
2626 
2627  //send the content-length header if the calling function provides it
2628  if ($filesize > 0) {
2629  header("Content-Length: $filesize");
2630  }
2631 
2632 } // end fn SendDownloadHeaders
plain_error_message
plain_error_message($message, $color)
Definition: display_messages.php:40
$body
if(isset($ldap_server) && $ldap_server[0] &&! extension_loaded('ldap')) $body
Definition: bug_report.php:106
elseif
if(! sqgetGlobalVar('sound', $sound, SQ_GET)) elseif($sound=='(none)')
Definition: testsound.php:25
sqgetGlobalVar
sqgetGlobalVar($name, &$value, $search=SQ_INORDER)
Definition: global.php:344
sq_unspace
sq_unspace(&$attvalue)
Definition: mime.php:1056
$ret
$ret
Definition: webmail.php:172
sq_skipspace
sq_skipspace($body, $offset)
Definition: mime.php:1194
formatBody
formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX', $clean=false)
Definition: mime.php:306
sq_fixstyle
sq_fixstyle($body, $pos, $message, $id, $mailbox)
Definition: mime.php:1850
$count
$count
Definition: message_details_bottom.php:97
$imapServerAddress
$imapServerAddress
Definition: config_default.php:202
getPriorityStr
getPriorityStr($priority)
Definition: mime.php:215
formatAttachments
formatAttachments($message, $exclude_id, $mailbox, $id)
Definition: mime.php:425
$show_html_default
$show_html_default
Definition: load_prefs.php:222
$rfc822_header
$rfc822_header
Definition: compose.php:362
$charset
$charset
Definition: view_text.php:67
SendDownloadHeaders
SendDownloadHeaders($type0, $type1, $filename, $force, $filesize=0)
Definition: mime.php:2536
$MailTo_PReg_Match
global $MailTo_PReg_Match
Definition: url_parser.php:45
$imap_stream
$imap_stream
Definition: bug_report.php:119
mime_structure
mime_structure($bodystructure, $flags=array())
Definition: mime.php:30
sq_getnxtag
sq_getnxtag($body, $offset)
Definition: mime.php:1266
$id
$id
Definition: move_messages.php:190
sq_findnxstr
sq_findnxstr($body, $offset, $needle)
Definition: mime.php:1215
displayPageHeader
displayPageHeader($color, $mailbox, $xtra='', $session=false)
Definition: page_header.php:105
$mailbox
$mailbox
Definition: options.php:28
sprintf
powered by Systran sprintf(_("Number of supported language pairs: %s"), '36').' '
Definition: options.php:107
sq_cid2http
sq_cid2http($message, $id, $cidurl, $mailbox)
Definition: mime.php:2003
$username
global $username
Definition: validate.php:55
do_hook
do_hook($name)
Definition: plugin.php:42
magicHTML
magicHTML($body, $id, $message, $mailbox='INBOX', $take_mailto_links=true)
Definition: mime.php:2291
Message\parseStructure
parseStructure($read, &$i, $sub_msg='')
Definition: Message.class.php:295
mime_fetch_body
mime_fetch_body($imap_stream, $id, $ent_id=1, $fetch_size=0)
Definition: mime.php:100
$content
$content
Definition: message_details_bottom.php:93
$sort
$sort
Definition: load_prefs.php:170
$uid_support
$uid_support
Definition: config_default.php:643
parseUrl
parseUrl(&$body)
Definition: url_parser.php:95
sq_fixatts
sq_fixatts($tagname, $attary, $rm_attnames, $bad_attvals, $add_attr_to_tag, $message, $id, $mailbox)
Definition: mime.php:1584
sq_is8bit
sq_is8bit($string, $charset='')
Definition: strings.php:784
$message
$message
Definition: download.php:54
decodeBody
decodeBody($body, $encoding)
Definition: mime.php:598
$gt
$gt
Definition: monostochastic.php:42
sq_casenormalize
sq_casenormalize(&$val)
Definition: mime.php:1180
$languages
global $languages
Definition: i18n.php:774
sq_fix_url
sq_fix_url($attname, &$attvalue, $message, $id, $mailbox, $sQuote='"')
Definition: mime.php:1696
makeComposeLink
makeComposeLink($url, $text=null, $target='')
Definition: strings.php:704
$attachments
$attachments
Definition: printer_friendly_bottom.php:113
mime_print_body_lines
mime_print_body_lines($imap_stream, $id, $ent_id=1, $encoding, $rStream='php://stdout')
Definition: mime.php:164
sq_tagprint
sq_tagprint($tagname, $attary, $tagtype)
Definition: mime.php:1151
do_hook_function
do_hook_function($name, $parm=NULL)
Definition: plugin.php:69
sq_mb_list_encodings
sq_mb_list_encodings()
Definition: strings.php:1186
listEntities
listEntities($message)
Definition: mime.php:200
SQ_GET
const SQ_GET
Definition: global.php:16
sq_deent
sq_deent(&$attvalue, $regex, $hex=false)
Definition: mime.php:1551
$j
for($i=0; $i< $numboxes; $i++) $j
Definition: empty_trash.php:72
encodeHeader
encodeHeader($string)
Definition: mime.php:759
show_readable_size
show_readable_size($bytes)
Definition: strings.php:582
sq_defang
sq_defang(&$attvalue)
Definition: mime.php:1029
$view_unsafe_images
$view_unsafe_images
Definition: printer_friendly_main.php:33
is_conversion_safe
is_conversion_safe($input_charset)
Definition: i18n.php:540
SQ_SERVER
const SQ_SERVER
Definition: global.php:20
sq_check_save_extension
sq_check_save_extension($message)
Definition: mime.php:1009
find_ent_id
find_ent_id($id, $message)
Definition: mime.php:985
decodeHeader
decodeHeader($string, $utfencode=true, $htmlsave=true, $decide=false)
Definition: mime.php:633
$filename
if(isset($override_type0)) if(isset($override_type1)) $filename
Definition: download.php:97
$data
$data
Definition: mailto.php:83
exit
exit
Definition: help.php:128
SM_PATH
const SM_PATH
Definition: decrypt_headers.php:16
$wrap_at
$wrap_at
Definition: load_prefs.php:132
_
_($str)
Definition: gettext.php:160
sqimap_base64_decode
sqimap_base64_decode(&$string)
Definition: mime.php:563
$read
$read
Definition: message_details_bottom.php:75
$default_charset
$default_charset
Definition: config_default.php:1027
translateText
translateText(&$body, $wrap_at, $charset)
Definition: mime.php:251
$type0
$type0
Definition: view_text.php:65
charset_decode
charset_decode($charset, $string, $force_decode=false, $save_html=false)
Definition: i18n.php:178
sq_fixIE_idiocy
sq_fixIE_idiocy(&$attvalue)
Definition: mime.php:1072
sq_findnxreg
sq_findnxreg($body, $offset, $reg)
Definition: mime.php:1237
$attachment_common_show_images
$attachment_common_show_images
Definition: load_prefs.php:233
$to
$to
Definition: printer_friendly_bottom.php:66
sqimap_run_command
sqimap_run_command($imap_stream, $query, $handle_errors, &$response, &$message, $unique_id=false, $filter=false, $outputstream=false, $no_return=false)
Definition: imap_general.php:58
$imapPort
$imapPort
Definition: config_default.php:210
sqWordWrap
if(file_exists(SM_PATH . 'plugins/compatibility/functions.php')) sqWordWrap(&$line, $wrap, $charset=null)
Definition: strings.php:48
charset_convert
charset_convert($in_charset, $string, $out_charset, $htmlencode=true)
Definition: i18n.php:264
$color
$color
Definition: load_prefs.php:28
$squirrelmail_language
global $squirrelmail_language
Definition: i18n.php:774
getEntity
getEntity($message, $ent_id)
Definition: mime.php:243
$encoding
$encoding
Definition: download.php:81
encodeHeaderBase64
encodeHeaderBase64($string, $charset)
Definition: mime.php:922
$type1
$type1
Definition: download.php:80
$header
$header
Definition: message_details_bottom.php:81
sq_sanitize
sq_sanitize($body, $tag_list, $rm_tags_with_content, $self_closing_tags, $force_tag_closing, $rm_attnames, $bad_attvals, $add_attr_to_tag, $message, $id, $mailbox)
Definition: mime.php:2117
sq_body2div
sq_body2div($attary, $mailbox, $message, $id)
Definition: mime.php:2067
$compose_new_win
$compose_new_win
Definition: load_prefs.php:251