Drop obsolete function
[squirrelmail.git] / functions / mime.php
CommitLineData
59177427 1<?php
2ba13803 2
35586184 3/**
4 * mime.php
5 *
76911253 6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
35586184 7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This contains the functions necessary to detect and decode MIME
10 * messages.
11 *
12 * $Id$
13 */
b74ba498 14
b68edc75 15require_once(SM_PATH . 'functions/imap.php');
16require_once(SM_PATH . 'functions/attachment_common.php');
8beafbbc 17
7c7b74b3 18/* -------------------------------------------------------------------------- */
19/* MIME DECODING */
20/* -------------------------------------------------------------------------- */
b74ba498 21
451f74a2 22/* This function gets the structure of a message and stores it in the "message" class.
23 * It will return this object for use with all relevant header information and
24 * fully parsed into the standard "message" object format.
25 */
77b88425 26
a4a70693 27function mime_structure ($bodystructure, $flags=array()) {
c9d78ab4 28
3d8371be 29 /* Isolate the body structure and remove beginning and end parenthesis. */
a4a70693 30 $read = trim(substr ($bodystructure, strpos(strtolower($bodystructure), 'bodystructure') + 13));
451f74a2 31 $read = trim(substr ($read, 0, -1));
22efa9fb 32 $i = 0;
33 $msg = Message::parseStructure($read,$i);
9de42168 34 if (!is_object($msg)) {
bd9c880b 35 include_once(SM_PATH . 'functions/display_messages.php');
3d8371be 36 global $color, $mailbox;
c96c32f4 37 /* removed urldecode because $_GET is auto urldecoded ??? */
a48eba8f 38 displayPageHeader( $color, $mailbox );
5e8de8b6 39 $errormessage = _("SquirrelMail could not decode the bodystructure of the message");
3d8371be 40 $errormessage .= '<BR>'._("the provided bodystructure by your imap-server").':<BR><BR>';
472e7acb 41 $errormessage .= '<pre>' . htmlspecialchars($read) . '</pre>';
9de42168 42 plain_error_message( $errormessage, $color );
3d8371be 43 echo '</body></html>';
9de42168 44 exit;
45 }
a4a70693 46 if (count($flags)) {
7a9e9c89 47 foreach ($flags as $flag) {
48 $char = strtoupper($flag{1});
49 switch ($char) {
3d8371be 50 case 'S':
51 if (strtolower($flag) == '\\seen') {
52 $msg->is_seen = true;
53 }
54 break;
55 case 'A':
56 if (strtolower($flag) == '\\answered') {
57 $msg->is_answered = true;
58 }
59 break;
60 case 'D':
61 if (strtolower($flag) == '\\deleted') {
62 $msg->is_deleted = true;
63 }
64 break;
65 case 'F':
66 if (strtolower($flag) == '\\flagged') {
67 $msg->is_flagged = true;
68 }
69 break;
70 case 'M':
71 if (strtolower($flag) == '$mdnsent') {
72 $msg->is_mdnsent = true;
73 }
74 break;
75 default:
76 break;
7a9e9c89 77 }
78 }
451f74a2 79 }
7a9e9c89 80 // listEntities($msg);
3d8371be 81 return $msg;
451f74a2 82}
b74ba498 83
22efa9fb 84
85
3d8371be 86/* This starts the parsing of a particular structure. It is called recursively,
451f74a2 87 * so it can be passed different structures. It returns an object of type
88 * $message.
89 * First, it checks to see if it is a multipart message. If it is, then it
90 * handles that as it sees is necessary. If it is just a regular entity,
91 * then it parses it and adds the necessary header information (by calling out
92 * to mime_get_elements()
93 */
451f74a2 94
1035e159 95function mime_fetch_body($imap_stream, $id, $ent_id=1) {
a4a70693 96 global $uid_support;
3d8371be 97 /* Do a bit of error correction. If we couldn't find the entity id, just guess
09a4bde3 98 * that it is the first one. That is usually the case anyway.
99 */
7c7b74b3 100
09a4bde3 101 if (!$ent_id) {
08b7f7cc 102 $cmd = "FETCH $id BODY[]";
1035e159 103 } else {
08b7f7cc 104 $cmd = "FETCH $id BODY[$ent_id]";
09a4bde3 105 }
3d8371be 106
a4a70693 107 $data = sqimap_run_command ($imap_stream, $cmd, true, $response, $message, $uid_support);
77b88425 108 do {
3d8371be 109 $topline = trim(array_shift($data));
110 } while($topline && ($topline[0] == '*') && !preg_match('/\* [0-9]+ FETCH.*/i', $topline)) ;
a4a70693 111
451f74a2 112 $wholemessage = implode('', $data);
113 if (ereg('\\{([^\\}]*)\\}', $topline, $regs)) {
3d8371be 114 $ret = substr($wholemessage, 0, $regs[1]);
115 /* There is some information in the content info header that could be important
116 * in order to parse html messages. Let's get them here.
117 */
0600bdf1 118// if ($ret{0} == '<') {
119// $data = sqimap_run_command ($imap_stream, "FETCH $id BODY[$ent_id.MIME]", true, $response, $message, $uid_support);
120// }
451f74a2 121 } else if (ereg('"([^"]*)"', $topline, $regs)) {
122 $ret = $regs[1];
123 } else {
124 global $where, $what, $mailbox, $passed_id, $startMessage;
3d8371be 125 $par = 'mailbox=' . urlencode($mailbox) . '&amp;passed_id=' . $passed_id;
451f74a2 126 if (isset($where) && isset($what)) {
3d8371be 127 $par .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
a3daaaf3 128 } else {
3d8371be 129 $par .= '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
451f74a2 130 }
e5ea9327 131 $par .= '&amp;response=' . urlencode($response) .
3d8371be 132 '&amp;message=' . urlencode($message) .
133 '&amp;topline=' . urlencode($topline);
a019eeb8 134
346817d4 135 echo '<tt><br>' .
136 '<table width="80%"><tr>' .
137 '<tr><td colspan=2>' .
0e5b61b4 138 _("Body retrieval error. The reason for this is most probably that the message is malformed.") .
346817d4 139 '</td></tr>' .
0e5b61b4 140 '<tr><td><b>' . _("Command:") . "</td><td>$cmd</td></tr>" .
141 '<tr><td><b>' . _("Response:") . "</td><td>$response</td></tr>" .
142 '<tr><td><b>' . _("Message:") . "</td><td>$message</td></tr>" .
143 '<tr><td><b>' . _("FETCH line:") . "</td><td>$topline</td></tr>" .
346817d4 144 "</table><BR></tt></font><hr>";
145
a4a70693 146 $data = sqimap_run_command ($imap_stream, "FETCH $passed_id BODY[]", true, $response, $message, $uid_support);
451f74a2 147 array_shift($data);
148 $wholemessage = implode('', $data);
a019eeb8 149
346817d4 150 $ret = $wholemessage;
a3daaaf3 151 }
3d8371be 152 return $ret;
451f74a2 153}
d4467150 154
1035e159 155function mime_print_body_lines ($imap_stream, $id, $ent_id=1, $encoding) {
a4a70693 156 global $uid_support;
1035e159 157
3d8371be 158 /* Don't kill the connection if the browser is over a dialup
159 * and it would take over 30 seconds to download it.
160 * Donīt call set_time_limit in safe mode.
161 */
b7206e1d 162
3d8371be 163 if (!ini_get('safe_mode')) {
b7206e1d 164 set_time_limit(0);
165 }
7c7b74b3 166 /* in case of base64 encoded attachments, do not buffer them.
167 Instead, echo the decoded attachment directly to screen */
168 if (strtolower($encoding) == 'base64') {
169 if (!$ent_id) {
170 $query = "FETCH $id BODY[]";
171 } else {
172 $query = "FETCH $id BODY[$ent_id]";
173 }
174 sqimap_run_command($imap_stream,$query,true,$response,$message,$uid_support,'sqimap_base64_decode','php://stdout',true);
1d142b8d 175 } else {
7c7b74b3 176 $body = mime_fetch_body ($imap_stream, $id, $ent_id);
177 echo decodeBody($body, $encoding);
1d142b8d 178 }
346817d4 179
7c7b74b3 180 /*
181 TODO, use the same method for quoted printable.
182 However, I assume that quoted printable attachments aren't that large
183 so the performancegain / memory usage drop will be minimal.
184 If we decide to add that then we need to adapt sqimap_fread because
185 we need to split te result on \n and fread doesn't stop at \n. That
186 means we also should provide $results from sqimap_fread (by ref) to
187 te function and set $no_return to false. The $filter function for
188 quoted printable should handle unsetting of $results.
189 */
190 /*
191 TODO 2: find out how we write to the output stream php://stdout. fwrite
192 doesn't work because 'php://stdout isn't a stream.
193 */
194
5d9c6f73 195 return;
196/*
451f74a2 197 fputs ($imap_stream, "$sid FETCH $id BODY[$ent_id]\r\n");
198 $cnt = 0;
199 $continue = true;
1d142b8d 200 $read = fgets ($imap_stream,8192);
201
202
451f74a2 203 // This could be bad -- if the section has sqimap_session_id() . ' OK'
204 // or similar, it will kill the download.
1d142b8d 205 while (!ereg("^".$sid_s." (OK|BAD|NO)(.*)$", $read, $regs)) {
5d9c6f73 206 if (trim($read) == ')==') {
207 $read1 = $read;
208 $read = fgets ($imap_stream,4096);
209 if (ereg("^".$sid." (OK|BAD|NO)(.*)$", $read, $regs)) {
210 return;
211 } else {
212 echo decodeBody($read1, $encoding) .
213 decodeBody($read, $encoding);
214 }
215 } else if ($cnt) {
216 echo decodeBody($read, $encoding);
217 }
218 $read = fgets ($imap_stream,4096);
219 $cnt++;
1d142b8d 220// break;
451f74a2 221 }
5d9c6f73 222*/
451f74a2 223}
beb9e459 224
451f74a2 225/* -[ END MIME DECODING ]----------------------------------------------------------- */
d4467150 226
3d8371be 227/* This is here for debugging purposes. It will print out a list
228 * of all the entity IDs that are in the $message object.
229 */
451f74a2 230function listEntities ($message) {
3d8371be 231 if ($message) {
232 echo "<tt>" . $message->entity_id . ' : ' . $message->type0 . '/' . $message->type1 . ' parent = '. $message->parent->entity_id. '<br>';
233 for ($i = 0; isset($message->entities[$i]); $i++) {
234 echo "$i : ";
235 $msg = listEntities($message->entities[$i]);
236
237 if ($msg) {
238 echo "return: ";
239 return $msg;
240 }
241 }
a4a70693 242 }
451f74a2 243}
f0c4dc12 244
f792c641 245function getPriorityStr($priority) {
3d8371be 246 $priority_level = substr($priority,0,1);
247
248 switch($priority_level) {
249 /* Check for a higher then normal priority. */
250 case '1':
251 case '2':
252 $priority_string = _("High");
253 break;
254
255 /* Check for a lower then normal priority. */
256 case '4':
257 case '5':
258 $priority_string = _("Low");
259 break;
260
261 /* Check for a normal priority. */
262 case '3':
263 default:
264 $priority_level = '3';
265 $priority_string = _("Normal");
266 break;
267
268 }
269 return $priority_string;
f792c641 270}
271
451f74a2 272/* returns a $message object for a particular entity id */
273function getEntity ($message, $ent_id) {
a4a70693 274 return $message->getEntity($ent_id);
451f74a2 275}
8beafbbc 276
3d8371be 277/* translateText
da4c66e8 278 * Extracted from strings.php 23/03/2002
279 */
280
281function translateText(&$body, $wrap_at, $charset) {
3d8371be 282 global $where, $what; /* from searching */
283 global $color; /* color theme */
da4c66e8 284
b68edc75 285 require_once(SM_PATH . 'functions/url_parser.php');
da4c66e8 286
287 $body_ary = explode("\n", $body);
da4c66e8 288 for ($i=0; $i < count($body_ary); $i++) {
289 $line = $body_ary[$i];
290 if (strlen($line) - 2 >= $wrap_at) {
291 sqWordWrap($line, $wrap_at);
292 }
293 $line = charset_decode($charset, $line);
294 $line = str_replace("\t", ' ', $line);
295
296 parseUrl ($line);
297
3d8371be 298 $quotes = 0;
da4c66e8 299 $pos = 0;
3d8371be 300 $j = strlen($line);
da4c66e8 301
3d8371be 302 while ($pos < $j) {
da4c66e8 303 if ($line[$pos] == ' ') {
3d8371be 304 $pos++;
da4c66e8 305 } else if (strpos($line, '&gt;', $pos) === $pos) {
306 $pos += 4;
3d8371be 307 $quotes++;
da4c66e8 308 } else {
309 break;
310 }
311 }
3d8371be 312
83c94382 313 if ($quotes % 2) {
3d8371be 314 if (!isset($color[13])) {
da4c66e8 315 $color[13] = '#800000';
316 }
4c25967c 317 $line = '<font color="' . $color[13] . '">' . $line . '</font>';
318 } elseif ($quotes) {
319 if (!isset($color[14])) {
320 $color[14] = '#FF0000';
321 }
322 $line = '<font color="' . $color[14] . '">' . $line . '</font>';
da4c66e8 323 }
3d8371be 324
da4c66e8 325 $body_ary[$i] = $line;
326 }
327 $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
328}
329
451f74a2 330/* This returns a parsed string called $body. That string can then
3d8371be 331 * be displayed as the actual message in the HTML. It contains
332 * everything needed, including HTML Tags, Attachments at the
333 * bottom, etc.
334 */
b3af12ef 335function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num, $id, $mailbox='INBOX') {
3d8371be 336 /* This if statement checks for the entity to show as the
337 * primary message. To add more of them, just put them in the
338 * order that is their priority.
339 */
008989da 340 global $startMessage, $username, $key, $imapServerAddress, $imapPort,
23f617b8 341 $show_html_default, $sort, $has_unsafe_images, $passed_ent_id;
08b7f7cc 342 global $languages, $squirrelmail_language;
77bfbd2e 343
5262d9a6 344 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
345 $view_unsafe_images = false;
77bfbd2e 346 }
d03c24f4 347
cc34b00d 348 $body = '';
23bcec6f 349 $urlmailbox = urlencode($mailbox);
451f74a2 350 $body_message = getEntity($message, $ent_num);
351 if (($body_message->header->type0 == 'text') ||
352 ($body_message->header->type0 == 'rfc822')) {
3d8371be 353 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
451f74a2 354 $body = decodeBody($body, $body_message->header->encoding);
e842b215 355
356 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
357 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
358 if (mb_detect_encoding($body) != 'ASCII') {
359 $body = $languages[$squirrelmail_language]['XTRA_CODE']('decode', $body);
360 }
361 }
451f74a2 362 $hookResults = do_hook("message_body", $body);
363 $body = $hookResults[1];
23bcec6f 364
3d8371be 365 /* If there are other types that shouldn't be formatted, add
366 * them here.
367 */
368
451f74a2 369 if ($body_message->header->type1 == 'html') {
3d8371be 370 if ($show_html_default <> 1) {
85015544 371 $entity_conv = array('&nbsp;' => ' ',
3d8371be 372 '<p>' => "\n",
373 '<br>' => "\n",
374 '<P>' => "\n",
375 '<BR>' => "\n",
85015544 376 '&gt;' => '>',
377 '&lt;' => '<');
85015544 378 $body = strtr($body, $entity_conv);
3d8371be 379 $body = strip_tags($body);
85015544 380 $body = trim($body);
381 translateText($body, $wrap_at,
807e884a 382 $body_message->header->getParameter('charset'));
a3daaaf3 383 } else {
3d8371be 384 $body = magicHTML($body, $id, $message, $mailbox);
a3daaaf3 385 }
451f74a2 386 } else {
3d8371be 387 translateText($body, $wrap_at,
388 $body_message->header->getParameter('charset'));
451f74a2 389 }
08b7f7cc 390 $link = 'read_body.php?passed_id=' . $id . '&amp;ent_id='.$ent_num.
391 '&amp;mailbox=' . $urlmailbox .'&amp;sort=' . $sort .
392 '&amp;startMessage=' . $startMessage . '&amp;show_more=0';
393 if (isset($passed_ent_id)) {
394 $link .= '&amp;passed_ent_id='.$passed_ent_id;
395 }
7aad7b77 396 if ($view_unsafe_images) {
23f617b8 397 $text = _("Hide Unsafe Images");
7aad7b77 398 } else {
08b7f7cc 399 if (isset($has_unsafe_images) && $has_unsafe_images) {
400 $link .= '&amp;view_unsafe_images=1';
401 $text = _("View Unsafe Images");
402 } else {
403 $text = '';
404 }
3d8371be 405 }
23f617b8 406 $body .= '<center><small><a href="'.$link.'">'.$text.
08b7f7cc 407 '</a></small></center><br>' . "\n";
3d8371be 408 }
409 return $body;
451f74a2 410}
b74ba498 411
23bcec6f 412
413function formatAttachments($message, $exclude_id, $mailbox, $id) {
b583c3e8 414 global $where, $what, $startMessage, $color;
77b88425 415 static $ShownHTML = 0;
451f74a2 416
23bcec6f 417 $att_ar = $message->getAttachments($exclude_id);
451f74a2 418
23bcec6f 419 if (!count($att_ar)) return '';
2e25760a 420
8f5425ec 421 $attachments = '';
2e25760a 422
23bcec6f 423 $urlMailbox = urlencode($mailbox);
424
425 foreach ($att_ar as $att) {
fdc9d9b5 426 $ent = $att->entity_id;
2e25760a 427 $header = $att->header;
f0c4dc12 428 $type0 = strtolower($header->type0);
429 $type1 = strtolower($header->type1);
2e25760a 430 $name = '';
3d8371be 431 $links['download link']['text'] = _("download");
6b04287c 432 $links['download link']['href'] = SM_PATH .
433 "src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;ent_id=$ent";
2e25760a 434 $ImageURL = '';
435 if ($type0 =='message' && $type1 == 'rfc822') {
6b04287c 436 $default_page = SM_PATH . 'src/read_body.php';
2e25760a 437 $rfc822_header = $att->rfc822_header;
098ea084 438 $filename = $rfc822_header->subject;
6cc08d8b 439 if (trim( $filename ) == '') {
440 $filename = 'untitled-[' . $ent . ']' ;
08b7f7cc 441 }
2e25760a 442 $from_o = $rfc822_header->from;
443 if (is_object($from_o)) {
444 $from_name = $from_o->getAddress(false);
445 } else {
446 $from_name = _("Unknown sender");
f0c4dc12 447 }
098ea084 448 $from_name = decodeHeader(($from_name));
3d8371be 449 $description = $from_name;
23bcec6f 450 } else {
6b04287c 451 $default_page = SM_PATH . 'src/download.php';
3d8371be 452 if (is_object($header->disposition)) {
098ea084 453 $filename = $header->disposition->getProperty('filename');
3d8371be 454 if (trim($filename) == '') {
455 $name = decodeHeader($header->disposition->getProperty('name'));
456 if (trim($name) == '') {
098ea084 457 $name = $header->getParameter('name');
1035e159 458 if(trim($name) == '') {
459 if (trim( $header->id ) == '') {
460 $filename = 'untitled-[' . $ent . ']' ;
461 } else {
462 $filename = 'cid: ' . $header->id;
08b7f7cc 463 }
3d8371be 464 } else {
08b7f7cc 465 $filename = $name;
3d8371be 466 }
467 } else {
468 $filename = $name;
469 }
470 }
471 } else {
08b7f7cc 472 $filename = $header->getParameter('name');
473 if (!trim($filename)) {
474 if (trim( $header->id ) == '') {
475 $filename = 'untitled-[' . $ent . ']' ;
476 } else {
477 $filename = 'cid: ' . $header->id;
478 }
479 }
480 }
f810c0b2 481 if ($header->description) {
098ea084 482 $description = decodeHeader($header->description);
f810c0b2 483 } else {
3d8371be 484 $description = '';
485 }
2e25760a 486 }
487
488 $display_filename = $filename;
3d8371be 489 if (isset($passed_ent_id)) {
490 $passed_ent_id_link = '&amp;passed_ent_id='.$passed_ent_id;
491 } else {
492 $passed_ent_id_link = '';
493 }
494 $defaultlink = $default_page . "?startMessage=$startMessage"
2e25760a 495 . "&amp;passed_id=$id&amp;mailbox=$urlMailbox"
6b04287c 496 . '&amp;ent_id='.$ent.$passed_ent_id_link;
2e25760a 497 if ($where && $what) {
09f4707e 498 $defaultlink .= '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
2e25760a 499 }
3d8371be 500 /* This executes the attachment hook with a specific MIME-type.
501 * If that doesn't have results, it tries if there's a rule
502 * for a more generic type.
503 */
504 $hookresults = do_hook("attachment $type0/$type1", $links,
505 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
506 $display_filename, $where, $what);
507 if(count($hookresults[1]) <= 1) {
508 $hookresults = do_hook("attachment $type0/*", $links,
509 $startMessage, $id, $urlMailbox, $ent, $defaultlink,
510 $display_filename, $where, $what);
2e25760a 511 }
451f74a2 512
3d8371be 513 $links = $hookresults[1];
514 $defaultlink = $hookresults[6];
77b88425 515
2e25760a 516 $attachments .= '<TR><TD>' .
098ea084 517 '<A HREF="'.$defaultlink.'">'.decodeHeader($display_filename).'</A>&nbsp;</TD>' .
23bcec6f 518 '<TD><SMALL><b>' . show_readable_size($header->size) .
77b88425 519 '</b>&nbsp;&nbsp;</small></TD>' .
520 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
521 '<TD><SMALL>';
f810c0b2 522 $attachments .= '<b>' . $description . '</b>';
2e25760a 523 $attachments .= '</SMALL></TD><TD><SMALL>&nbsp;';
b74ba498 524
3d8371be 525 $skipspaces = 1;
526 foreach ($links as $val) {
527 if ($skipspaces) {
528 $skipspaces = 0;
2e25760a 529 } else {
530 $attachments .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
77b88425 531 }
3d8371be 532 $attachments .= '<a href="' . $val['href'] . '">' . $val['text'] . '</a>';
2e25760a 533 }
3d8371be 534 unset($links);
2e25760a 535 $attachments .= "</TD></TR>\n";
536 }
537 return $attachments;
451f74a2 538}
b74ba498 539
7c7b74b3 540function sqimap_base64_decode(&$string) {
325978ac 541 $string = str_replace("\r\n", "\n", $string);
7c7b74b3 542 $string = base64_decode($string);
543}
544
3d8371be 545/* This function decodes the body depending on the encoding type. */
451f74a2 546function decodeBody($body, $encoding) {
3d8371be 547 global $show_html_default;
83be314a 548
b583c3e8 549 $body = str_replace("\r\n", "\n", $body);
550 $encoding = strtolower($encoding);
3d8371be 551
b583c3e8 552 if ($encoding == 'quoted-printable' ||
3d8371be 553 $encoding == 'quoted_printable') {
b583c3e8 554 $body = quoted_printable_decode($body);
3d8371be 555
b583c3e8 556 while (ereg("=\n", $body)) {
557 $body = ereg_replace ("=\n", '', $body);
558 }
3d8371be 559
b583c3e8 560 } else if ($encoding == 'base64') {
561 $body = base64_decode($body);
562 }
3d8371be 563
b583c3e8 564 // All other encodings are returned raw.
3d8371be 565 return $body;
451f74a2 566}
567
568/*
569 * This functions decode strings that is encoded according to
570 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
79e07c7e 571 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
451f74a2 572 */
098ea084 573function decodeHeader ($string, $utfencode=true,$htmlsave=true) {
d7448126 574 global $languages, $squirrelmail_language;
79e07c7e 575 if (is_array($string)) {
576 $string = implode("\n", $string);
577 }
c96c32f4 578
10dec454 579 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
580 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
6fbd125b 581 $string = $languages[$squirrelmail_language]['XTRA_CODE']('decodeheader', $string);
08b7f7cc 582 // Do we need to return at this point?
583 // return $string;
83be314a 584 }
79e07c7e 585 $i = 0;
08b7f7cc 586 $iLastMatch = -2;
587 $encoded = false;
0a06275a 588
098ea084 589 $aString = explode(' ',$string);
08b7f7cc 590 $ret = '';
098ea084 591 foreach ($aString as $chunk) {
08b7f7cc 592 if ($encoded && !$chunk) {
593 continue;
594 } elseif (!$chunk) {
595 $ret .= ' ';
596 continue;
597 }
098ea084 598 $encoded = false;
08b7f7cc 599 /* if encoded words are not separated by a linear-space-white we still catch them */
600 $j = $i-1;
325978ac 601// if ($chunk{0} === '=') { /* performance, saves an unnessecarry preg call */
08b7f7cc 602 while ($match = preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=(.*)$/Ui',$chunk,$res)) {
603 /* if the last chunk isn't an encoded string then put back the space, otherwise don't */
604 if ($iLastMatch !== $j) {
605 if ($htmlsave) {
606 $ret .= '&nbsp;';
607 } else {
608 $ret .= ' ';
609 }
610 }
611 $iLastMatch = $i;
612 $j = $i;
613 $ret .= $res[1];
098ea084 614 $encoding = ucfirst($res[3]);
615 switch ($encoding)
616 {
617 case 'B':
618 $replace = base64_decode($res[4]);
08b7f7cc 619 $ret .= charset_decode($res[2],$replace);
098ea084 620 break;
621 case 'Q':
098ea084 622 $replace = str_replace('_', ' ', $res[4]);
623 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
79e07c7e 624 $replace);
098ea084 625 /* Only encode into entities by default. Some places
626 * don't need the encoding, like the compose form.
627 */
628 if ($utfencode) {
629 $replace = charset_decode($res[2], $replace);
630 } else {
631 if ($htmlsave) {
c96c32f4 632 $replace = htmlspecialchars($replace);
098ea084 633 }
634 }
08b7f7cc 635 $ret .= $replace;
098ea084 636 break;
637 default:
638 break;
79e07c7e 639 }
098ea084 640 $chunk = $res[5];
641 $encoded = true;
08b7f7cc 642 }
325978ac 643// }
08b7f7cc 644 if (!$encoded) {
645 if ($htmlsave) {
646 $ret .= '&nbsp;';
647 } else {
648 $ret .= ' ';
649 }
650 }
651
098ea084 652 if (!$encoded && $htmlsave) {
08b7f7cc 653 $ret .= htmlspecialchars($chunk);
098ea084 654 } else {
08b7f7cc 655 $ret .= $chunk;
18aa168e 656 }
098ea084 657 ++$i;
658 }
0a06275a 659 /* remove the first added space */
660 if ($ret) {
661 if ($htmlsave) {
662 $ret = substr($ret,6);
663 } else {
664 $ret = substr($ret,1);
665 }
666 }
667
08b7f7cc 668 return $ret;
451f74a2 669}
670
671/*
672 * Encode a string according to RFC 1522 for use in headers if it
673 * contains 8-bit characters or anything that looks like it should
674 * be encoded.
675 */
676function encodeHeader ($string) {
6fbd125b 677 global $default_charset, $languages, $squirrelmail_language;
83be314a 678
10dec454 679 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
680 function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
6fbd125b 681 return $languages[$squirrelmail_language]['XTRA_CODE']('encodeheader', $string);
83be314a 682 }
c96c32f4 683 if (strtolower($default_charset) == 'iso-8859-1') {
684 $string = str_replace("\240",' ',$string);
685 }
793cc001 686
451f74a2 687 // Encode only if the string contains 8-bit characters or =?
3d8371be 688 $j = strlen($string);
098ea084 689 $max_l = 75 - strlen($default_charset) - 7;
690 $aRet = array();
451f74a2 691 $ret = '';
c96c32f4 692 $iEncStart = $enc_init = false;
0d53f0f9 693 $cur_l = $iOffset = 0;
3d8371be 694 for($i = 0; $i < $j; ++$i) {
c96c32f4 695 switch($string{$i})
696 {
697 case '=':
698 case '<':
699 case '>':
700 case ',':
701 case '?':
702 case '_':
703 if ($iEncStart === false) {
704 $iEncStart = $i;
705 }
706 $cur_l+=3;
707 if ($cur_l > ($max_l-2)) {
08b7f7cc 708 /* if there is an stringpart that doesn't need encoding, add it */
c96c32f4 709 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
710 $aRet[] = "=?$default_charset?Q?$ret?=";
711 $iOffset = $i;
712 $cur_l = 0;
713 $ret = '';
714 $iEncStart = false;
715 } else {
716 $ret .= sprintf("=%02X",ord($string{$i}));
717 }
718 break;
719 case '(':
720 case ')':
721 if ($iEncStart !== false) {
08b7f7cc 722 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
c96c32f4 723 $aRet[] = "=?$default_charset?Q?$ret?=";
724 $iOffset = $i;
725 $cur_l = 0;
726 $ret = '';
727 $iEncStart = false;
728 }
729 break;
730 case ' ':
731 if ($iEncStart !== false) {
098ea084 732 $cur_l++;
733 if ($cur_l > $max_l) {
08b7f7cc 734 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
c96c32f4 735 $aRet[] = "=?$default_charset?Q?$ret?=";
736 $iOffset = $i;
737 $cur_l = 0;
738 $ret = '';
739 $iEncStart = false;
08b7f7cc 740 } else {
c96c32f4 741 $ret .= '_';
742 }
743 }
744 break;
745 default:
746 $k = ord($string{$i});
747 if ($k > 126) {
748 if ($iEncStart === false) {
325978ac 749 // do not start encoding in the middle of a string, also take the rest of the word.
750 $sLeadString = substr($string,0,$i);
751 $aLeadString = explode(' ',$sLeadString);
752 $sToBeEncoded = array_pop($aLeadString);
753 $iEncStart = $i - strlen($sToBeEncoded);
754 $ret .= $sToBeEncoded;
755 $cur_l += strlen($sToBeEncoded);
c96c32f4 756 }
757 $cur_l += 3;
08b7f7cc 758 /* first we add the encoded string that reached it's max size */
c96c32f4 759 if ($cur_l > ($max_l-2)) {
08b7f7cc 760 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
761 $aRet[] = "=?$default_charset?Q?$ret?= "; /* the next part is also encoded => separate by space */
c96c32f4 762 $cur_l = 3;
763 $ret = '';
764 $iOffset = $i;
08b7f7cc 765 $iEncStart = $i;
c96c32f4 766 }
08b7f7cc 767 $enc_init = true;
c96c32f4 768 $ret .= sprintf("=%02X", $k);
769 } else {
770 if ($iEncStart !== false) {
098ea084 771 $cur_l++;
772 if ($cur_l > $max_l) {
08b7f7cc 773 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
c96c32f4 774 $aRet[] = "=?$default_charset?Q?$ret?=";
775 $iEncStart = false;
776 $iOffset = $i;
777 $cur_l = 0;
098ea084 778 $ret = '';
08b7f7cc 779 } else {
c96c32f4 780 $ret .= $string{$i};
781 }
3d8371be 782 }
c96c32f4 783 }
784 break;
f7b3ba37 785 }
451f74a2 786 }
793cc001 787
c96c32f4 788 if ($enc_init) {
789 if ($iEncStart !== false) {
790 $aRet[] = substr($string,$iOffset,$iEncStart-$iOffset);
791 $aRet[] = "=?$default_charset?Q?$ret?=";
792 } else {
793 $aRet[] = substr($string,$iOffset);
794 }
795 $string = implode('',$aRet);
451f74a2 796 }
3d8371be 797 return $string;
451f74a2 798}
b74ba498 799
691a2d25 800/* This function trys to locate the entity_id of a specific mime element */
3d8371be 801function find_ent_id($id, $message) {
a171b359 802 for ($i = 0, $ret = ''; $ret == '' && $i < count($message->entities); $i++) {
803 if ($message->entities[$i]->header->type0 == 'multipart') {
3d8371be 804 $ret = find_ent_id($id, $message->entities[$i]);
451f74a2 805 } else {
3d8371be 806 if (strcasecmp($message->entities[$i]->header->id, $id) == 0) {
d8cffbab 807// if (sq_check_save_extension($message->entities[$i])) {
a171b359 808 return $message->entities[$i]->entity_id;
d8cffbab 809// }
3d8371be 810 }
a3daaaf3 811 }
451f74a2 812 }
3d8371be 813 return $ret;
451f74a2 814}
a3daaaf3 815
e5e9381a 816function sq_check_save_extension($message) {
817 $filename = $message->getFilename();
818 $ext = substr($filename, strrpos($filename,'.')+1);
819 $save_extensions = array('jpg','jpeg','gif','png','bmp');
3d8371be 820 return in_array($ext, $save_extensions);
e5e9381a 821}
822
823
691a2d25 824/**
825 ** HTMLFILTER ROUTINES
826 */
451f74a2 827
691a2d25 828/**
829 * This function returns the final tag out of the tag name, an array
830 * of attributes, and the type of the tag. This function is called by
831 * sq_sanitize internally.
832 *
833 * @param $tagname the name of the tag.
834 * @param $attary the array of attributes and their values
835 * @param $tagtype The type of the tag (see in comments).
836 * @return a string with the final tag representation.
837 */
838function sq_tagprint($tagname, $attary, $tagtype){
b583c3e8 839 $me = 'sq_tagprint';
3d8371be 840
691a2d25 841 if ($tagtype == 2){
842 $fulltag = '</' . $tagname . '>';
843 } else {
844 $fulltag = '<' . $tagname;
845 if (is_array($attary) && sizeof($attary)){
846 $atts = Array();
847 while (list($attname, $attvalue) = each($attary)){
848 array_push($atts, "$attname=$attvalue");
849 }
850 $fulltag .= ' ' . join(" ", $atts);
851 }
852 if ($tagtype == 3){
b583c3e8 853 $fulltag .= ' /';
691a2d25 854 }
b583c3e8 855 $fulltag .= '>';
451f74a2 856 }
691a2d25 857 return $fulltag;
451f74a2 858}
a3daaaf3 859
691a2d25 860/**
861 * A small helper function to use with array_walk. Modifies a by-ref
862 * value and makes it lowercase.
863 *
864 * @param $val a value passed by-ref.
865 * @return void since it modifies a by-ref value.
866 */
867function sq_casenormalize(&$val){
868 $val = strtolower($val);
869}
451f74a2 870
691a2d25 871/**
872 * This function skips any whitespace from the current position within
873 * a string and to the next non-whitespace value.
874 *
875 * @param $body the string
876 * @param $offset the offset within the string where we should start
877 * looking for the next non-whitespace character.
878 * @return the location within the $body where the next
879 * non-whitespace char is located.
880 */
881function sq_skipspace($body, $offset){
b583c3e8 882 $me = 'sq_skipspace';
3d8371be 883 preg_match('/^(\s*)/s', substr($body, $offset), $matches);
691a2d25 884 if (sizeof($matches{1})){
885 $count = strlen($matches{1});
886 $offset += $count;
451f74a2 887 }
691a2d25 888 return $offset;
451f74a2 889}
a3daaaf3 890
691a2d25 891/**
892 * This function looks for the next character within a string. It's
893 * really just a glorified "strpos", except it catches if failures
894 * nicely.
895 *
896 * @param $body The string to look for needle in.
897 * @param $offset Start looking from this position.
898 * @param $needle The character/string to look for.
899 * @return location of the next occurance of the needle, or
900 * strlen($body) if needle wasn't found.
901 */
902function sq_findnxstr($body, $offset, $needle){
3d8371be 903 $me = 'sq_findnxstr';
691a2d25 904 $pos = strpos($body, $needle, $offset);
905 if ($pos === FALSE){
906 $pos = strlen($body);
451f74a2 907 }
691a2d25 908 return $pos;
451f74a2 909}
a3daaaf3 910
691a2d25 911/**
912 * This function takes a PCRE-style regexp and tries to match it
913 * within the string.
914 *
915 * @param $body The string to look for needle in.
916 * @param $offset Start looking from here.
917 * @param $reg A PCRE-style regex to match.
918 * @return Returns a false if no matches found, or an array
919 * with the following members:
920 * - integer with the location of the match within $body
921 * - string with whatever content between offset and the match
922 * - string with whatever it is we matched
923 */
924function sq_findnxreg($body, $offset, $reg){
b583c3e8 925 $me = 'sq_findnxreg';
691a2d25 926 $matches = Array();
927 $retarr = Array();
7d06541f 928 preg_match("%^(.*?)($reg)%si", substr($body, $offset), $matches);
929 if (!isset($matches{0}) || !$matches{0}){
691a2d25 930 $retarr = false;
931 } else {
932 $retarr{0} = $offset + strlen($matches{1});
933 $retarr{1} = $matches{1};
934 $retarr{2} = $matches{2};
935 }
936 return $retarr;
937}
a3daaaf3 938
691a2d25 939/**
940 * This function looks for the next tag.
941 *
942 * @param $body String where to look for the next tag.
943 * @param $offset Start looking from here.
944 * @return false if no more tags exist in the body, or
945 * an array with the following members:
946 * - string with the name of the tag
947 * - array with attributes and their values
948 * - integer with tag type (1, 2, or 3)
949 * - integer where the tag starts (starting "<")
950 * - integer where the tag ends (ending ">")
951 * first three members will be false, if the tag is invalid.
952 */
953function sq_getnxtag($body, $offset){
b583c3e8 954 $me = 'sq_getnxtag';
691a2d25 955 if ($offset > strlen($body)){
956 return false;
957 }
958 $lt = sq_findnxstr($body, $offset, "<");
959 if ($lt == strlen($body)){
960 return false;
961 }
962 /**
963 * We are here:
964 * blah blah <tag attribute="value">
965 * \---------^
966 */
967 $pos = sq_skipspace($body, $lt+1);
968 if ($pos >= strlen($body)){
969 return Array(false, false, false, $lt, strlen($body));
970 }
971 /**
972 * There are 3 kinds of tags:
973 * 1. Opening tag, e.g.:
974 * <a href="blah">
975 * 2. Closing tag, e.g.:
976 * </a>
977 * 3. XHTML-style content-less tag, e.g.:
978 * <img src="blah"/>
979 */
980 $tagtype = false;
981 switch (substr($body, $pos, 1)){
3d8371be 982 case '/':
983 $tagtype = 2;
984 $pos++;
985 break;
986 case '!':
987 /**
988 * A comment or an SGML declaration.
989 */
990 if (substr($body, $pos+1, 2) == "--"){
991 $gt = strpos($body, "-->", $pos);
992 if ($gt === false){
993 $gt = strlen($body);
994 } else {
995 $gt += 2;
996 }
997 return Array(false, false, false, $lt, $gt);
bb8d0799 998 } else {
3d8371be 999 $gt = sq_findnxstr($body, $pos, ">");
1000 return Array(false, false, false, $lt, $gt);
1001 }
1002 break;
1003 default:
1004 /**
1005 * Assume tagtype 1 for now. If it's type 3, we'll switch values
1006 * later.
1007 */
1008 $tagtype = 1;
1009 break;
691a2d25 1010 }
a3daaaf3 1011
691a2d25 1012 $tag_start = $pos;
1013 $tagname = '';
1014 /**
1015 * Look for next [\W-_], which will indicate the end of the tag name.
1016 */
1017 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1018 if ($regary == false){
1019 return Array(false, false, false, $lt, strlen($body));
1020 }
1021 list($pos, $tagname, $match) = $regary;
1022 $tagname = strtolower($tagname);
1023
1024 /**
1025 * $match can be either of these:
1026 * '>' indicating the end of the tag entirely.
1027 * '\s' indicating the end of the tag name.
1028 * '/' indicating that this is type-3 xhtml tag.
1029 *
1030 * Whatever else we find there indicates an invalid tag.
1031 */
1032 switch ($match){
3d8371be 1033 case '/':
691a2d25 1034 /**
3d8371be 1035 * This is an xhtml-style tag with a closing / at the
1036 * end, like so: <img src="blah"/>. Check if it's followed
1037 * by the closing bracket. If not, then this tag is invalid
691a2d25 1038 */
3d8371be 1039 if (substr($body, $pos, 2) == "/>"){
1040 $pos++;
1041 $tagtype = 3;
1042 } else {
1043 $gt = sq_findnxstr($body, $pos, ">");
1044 $retary = Array(false, false, false, $lt, $gt);
1045 return $retary;
1046 }
1047 case '>':
1048 return Array($tagname, false, $tagtype, $lt, $pos);
1049 break;
1050 default:
1051 /**
1052 * Check if it's whitespace
1053 */
1054 if (!preg_match('/\s/', $match)){
1055 /**
1056 * This is an invalid tag! Look for the next closing ">".
1057 */
7d06541f 1058 $gt = sq_findnxstr($body, $lt, ">");
3d8371be 1059 return Array(false, false, false, $lt, $gt);
1060 }
1061 break;
691a2d25 1062 }
3d8371be 1063
691a2d25 1064 /**
1065 * At this point we're here:
1066 * <tagname attribute='blah'>
1067 * \-------^
1068 *
1069 * At this point we loop in order to find all attributes.
1070 */
1071 $attname = '';
1072 $atttype = false;
1073 $attary = Array();
1074
1075 while ($pos <= strlen($body)){
1076 $pos = sq_skipspace($body, $pos);
1077 if ($pos == strlen($body)){
1078 /**
1079 * Non-closed tag.
1080 */
1081 return Array(false, false, false, $lt, $pos);
1082 }
1083 /**
1084 * See if we arrived at a ">" or "/>", which means that we reached
1085 * the end of the tag.
1086 */
1087 $matches = Array();
164800ad 1088 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
c828931c 1089 /**
1090 * Yep. So we did.
1091 */
1092 $pos += strlen($matches{1});
1093 if ($matches{2} == "/>"){
1094 $tagtype = 3;
1095 $pos++;
1096 }
1097 return Array($tagname, $attary, $tagtype, $lt, $pos);
1098 }
a3daaaf3 1099
cca46357 1100 /**
691a2d25 1101 * There are several types of attributes, with optional
1102 * [:space:] between members.
1103 * Type 1:
1104 * attrname[:space:]=[:space:]'CDATA'
1105 * Type 2:
1106 * attrname[:space:]=[:space:]"CDATA"
1107 * Type 3:
1108 * attr[:space:]=[:space:]CDATA
1109 * Type 4:
1110 * attrname
cca46357 1111 *
691a2d25 1112 * We leave types 1 and 2 the same, type 3 we check for
1113 * '"' and convert to "&quot" if needed, then wrap in
1114 * double quotes. Type 4 we convert into:
1115 * attrname="yes".
cca46357 1116 */
691a2d25 1117 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1118 if ($regary == false){
1119 /**
1120 * Looks like body ended before the end of tag.
1121 */
1122 return Array(false, false, false, $lt, strlen($body));
cca46357 1123 }
691a2d25 1124 list($pos, $attname, $match) = $regary;
1125 $attname = strtolower($attname);
1126 /**
1127 * We arrived at the end of attribute name. Several things possible
1128 * here:
1129 * '>' means the end of the tag and this is attribute type 4
1130 * '/' if followed by '>' means the same thing as above
1131 * '\s' means a lot of things -- look what it's followed by.
1132 * anything else means the attribute is invalid.
1133 */
1134 switch($match){
3d8371be 1135 case '/':
691a2d25 1136 /**
3d8371be 1137 * This is an xhtml-style tag with a closing / at the
1138 * end, like so: <img src="blah"/>. Check if it's followed
1139 * by the closing bracket. If not, then this tag is invalid
691a2d25 1140 */
3d8371be 1141 if (substr($body, $pos, 2) == "/>"){
691a2d25 1142 $pos++;
3d8371be 1143 $tagtype = 3;
691a2d25 1144 } else {
3d8371be 1145 $gt = sq_findnxstr($body, $pos, ">");
1146 $retary = Array(false, false, false, $lt, $gt);
1147 return $retary;
1148 }
1149 case '>':
1150 $attary{$attname} = '"yes"';
1151 return Array($tagname, $attary, $tagtype, $lt, $pos);
1152 break;
1153 default:
1154 /**
1155 * Skip whitespace and see what we arrive at.
1156 */
1157 $pos = sq_skipspace($body, $pos);
1158 $char = substr($body, $pos, 1);
1159 /**
1160 * Two things are valid here:
1161 * '=' means this is attribute type 1 2 or 3.
1162 * \w means this was attribute type 4.
1163 * anything else we ignore and re-loop. End of tag and
1164 * invalid stuff will be caught by our checks at the beginning
1165 * of the loop.
1166 */
1167 if ($char == "="){
1168 $pos++;
1169 $pos = sq_skipspace($body, $pos);
691a2d25 1170 /**
3d8371be 1171 * Here are 3 possibilities:
1172 * "'" attribute type 1
1173 * '"' attribute type 2
1174 * everything else is the content of tag type 3
691a2d25 1175 */
3d8371be 1176 $quot = substr($body, $pos, 1);
1177 if ($quot == "'"){
1178 $regary = sq_findnxreg($body, $pos+1, "\'");
1179 if ($regary == false){
1180 return Array(false, false, false, $lt, strlen($body));
1181 }
1182 list($pos, $attval, $match) = $regary;
1183 $pos++;
1184 $attary{$attname} = "'" . $attval . "'";
1185 } else if ($quot == '"'){
1186 $regary = sq_findnxreg($body, $pos+1, '\"');
1187 if ($regary == false){
1188 return Array(false, false, false, $lt, strlen($body));
1189 }
1190 list($pos, $attval, $match) = $regary;
1191 $pos++;
1192 $attary{$attname} = '"' . $attval . '"';
1193 } else {
1194 /**
1195 * These are hateful. Look for \s, or >.
1196 */
1197 $regary = sq_findnxreg($body, $pos, "[\s>]");
1198 if ($regary == false){
1199 return Array(false, false, false, $lt, strlen($body));
1200 }
1201 list($pos, $attval, $match) = $regary;
1202 /**
1203 * If it's ">" it will be caught at the top.
1204 */
1205 $attval = preg_replace("/\"/s", "&quot;", $attval);
1206 $attary{$attname} = '"' . $attval . '"';
7e235a1a 1207 }
3d8371be 1208 } else if (preg_match("|[\w/>]|", $char)) {
691a2d25 1209 /**
3d8371be 1210 * That was attribute type 4.
691a2d25 1211 */
3d8371be 1212 $attary{$attname} = '"yes"';
1213 } else {
1214 /**
1215 * An illegal character. Find next '>' and return.
1216 */
1217 $gt = sq_findnxstr($body, $pos, ">");
1218 return Array(false, false, false, $lt, $gt);
451f74a2 1219 }
3d8371be 1220 break;
691a2d25 1221 }
1222 }
1223 /**
1224 * The fact that we got here indicates that the tag end was never
1225 * found. Return invalid tag indication so it gets stripped.
1226 */
1227 return Array(false, false, false, $lt, strlen($body));
1228}
1229
1230/**
1231 * This function checks attribute values for entity-encoded values
1232 * and returns them translated into 8-bit strings so we can run
1233 * checks on them.
1234 *
1235 * @param $attvalue A string to run entity check against.
1236 * @return Translated value.
1237 */
1238function sq_deent($attvalue){
b583c3e8 1239 $me = 'sq_deent';
691a2d25 1240 /**
1241 * See if we have to run the checks first. All entities must start
1242 * with "&".
1243 */
1244 if (strpos($attvalue, "&") === false){
1245 return $attvalue;
1246 }
1247 /**
1248 * Check named entities first.
1249 */
1250 $trans = get_html_translation_table(HTML_ENTITIES);
1251 /**
1252 * Leave &quot; in, as it can mess us up.
1253 */
1254 $trans = array_flip($trans);
1255 unset($trans{"&quot;"});
1256 while (list($ent, $val) = each($trans)){
1257 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1258 }
1259 /**
1260 * Now translate numbered entities from 1 to 255 if needed.
1261 */
1262 if (strpos($attvalue, "#") !== false){
1263 $omit = Array(34, 39);
1264 for ($asc=1; $asc<256; $asc++){
1265 if (!in_array($asc, $omit)){
1266 $chr = chr($asc);
1267 $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
1268 $attvalue);
1269 $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
1270 "$chr\\1", $attvalue);
a3daaaf3 1271 }
691a2d25 1272 }
1273 }
1274 return $attvalue;
1275}
1276
1277/**
1278 * This function runs various checks against the attributes.
1279 *
1280 * @param $tagname String with the name of the tag.
1281 * @param $attary Array with all tag attributes.
1282 * @param $rm_attnames See description for sq_sanitize
1283 * @param $bad_attvals See description for sq_sanitize
1284 * @param $add_attr_to_tag See description for sq_sanitize
1285 * @param $message message object
1286 * @param $id message id
1287 * @return Array with modified attributes.
1288 */
1289function sq_fixatts($tagname,
1290 $attary,
1291 $rm_attnames,
1292 $bad_attvals,
1293 $add_attr_to_tag,
1294 $message,
b3af12ef 1295 $id,
3d8371be 1296 $mailbox
691a2d25 1297 ){
b583c3e8 1298 $me = 'sq_fixatts';
691a2d25 1299 while (list($attname, $attvalue) = each($attary)){
1300 /**
1301 * See if this attribute should be removed.
1302 */
1303 foreach ($rm_attnames as $matchtag=>$matchattrs){
1304 if (preg_match($matchtag, $tagname)){
1305 foreach ($matchattrs as $matchattr){
1306 if (preg_match($matchattr, $attname)){
1307 unset($attary{$attname});
1308 continue;
1309 }
451f74a2 1310 }
451f74a2 1311 }
691a2d25 1312 }
1313 /**
1314 * Remove any entities.
1315 */
1316 $attvalue = sq_deent($attvalue);
1317
1318 /**
1319 * Now let's run checks on the attvalues.
1320 * I don't expect anyone to comprehend this. If you do,
1321 * get in touch with me so I can drive to where you live and
1322 * shake your hand personally. :)
1323 */
1324 foreach ($bad_attvals as $matchtag=>$matchattrs){
1325 if (preg_match($matchtag, $tagname)){
1326 foreach ($matchattrs as $matchattr=>$valary){
1327 if (preg_match($matchattr, $attname)){
1328 /**
1329 * There are two arrays in valary.
1330 * First is matches.
1331 * Second one is replacements
1332 */
1333 list($valmatch, $valrepl) = $valary;
1334 $newvalue =
1335 preg_replace($valmatch, $valrepl, $attvalue);
1336 if ($newvalue != $attvalue){
1337 $attary{$attname} = $newvalue;
1338 }
1339 }
1340 }
451f74a2 1341 }
a3daaaf3 1342 }
691a2d25 1343 /**
1344 * Turn cid: urls into http-friendly ones.
1345 */
1346 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
b3af12ef 1347 $attary{$attname} = sq_cid2http($message, $id, $attvalue, $mailbox);
691a2d25 1348 }
a3daaaf3 1349 }
691a2d25 1350 /**
1351 * See if we need to append any attributes to this tag.
1352 */
1353 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1354 if (preg_match($matchtag, $tagname)){
1355 $attary = array_merge($attary, $addattary);
1356 }
1357 }
1358 return $attary;
451f74a2 1359}
a3daaaf3 1360
691a2d25 1361/**
1362 * This function edits the style definition to make them friendly and
1363 * usable in squirrelmail.
1364 *
1365 * @param $message the message object
1366 * @param $id the message id
1367 * @param $content a string with whatever is between <style> and </style>
1368 * @return a string with edited content.
1369 */
7d06541f 1370function sq_fixstyle($body, $pos, $message, $id){
691a2d25 1371 global $view_unsafe_images;
b583c3e8 1372 $me = 'sq_fixstyle';
7d06541f 1373 $ret = sq_findnxreg($body, $pos, '</\s*style\s*>');
1374 if ($ret == FALSE){
1375 return array(FALSE, strlen($body));
1376 }
1377 $newpos = $ret[0] + strlen($ret[2]);
1378 $content = $ret[1];
691a2d25 1379 /**
1380 * First look for general BODY style declaration, which would be
1381 * like so:
1382 * body {background: blah-blah}
1383 * and change it to .bodyclass so we can just assign it to a <div>
1384 */
1385 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
3d8371be 1386 $secremoveimg = '../images/' . _("sec_remove_eng.png");
691a2d25 1387 /**
1388 * Fix url('blah') declarations.
1389 */
7d06541f 1390 $content = preg_replace("|url\s*\(\s*([\'\"])\s*\S+script\s*:.*?([\'\"])\s*\)|si",
691a2d25 1391 "url(\\1$secremoveimg\\2)", $content);
1392 /**
1393 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1394 * is false.
1395 */
1396 if (!$view_unsafe_images){
7d06541f 1397 $content = preg_replace("|url\s*\(\s*([\'\"])\s*https*:.*?([\'\"])\s*\)|si",
691a2d25 1398 "url(\\1$secremoveimg\\2)", $content);
1399 }
098ea084 1400
691a2d25 1401 /**
1402 * Fix urls that refer to cid:
1403 */
7d06541f 1404 while (preg_match("|url\s*\(\s*([\'\"]\s*cid:.*?[\'\"])\s*\)|si",
1405 $content, $matches)){
691a2d25 1406 $cidurl = $matches{1};
1407 $httpurl = sq_cid2http($message, $id, $cidurl);
7d06541f 1408 $content = preg_replace("|url\s*\(\s*$cidurl\s*\)|si",
691a2d25 1409 "url($httpurl)", $content);
1410 }
a3daaaf3 1411
691a2d25 1412 /**
bb8d0799 1413 * Fix stupid css declarations which lead to vulnerabilities
691a2d25 1414 * in IE.
1415 */
f83c60a2 1416 $match = Array('/expression/i',
1417 '/behaviou*r/i',
1418 '/binding/i');
bb8d0799 1419 $replace = Array('idiocy', 'idiocy', 'idiocy');
1420 $content = preg_replace($match, $replace, $content);
7d06541f 1421 return array($content, $newpos);
691a2d25 1422}
a3daaaf3 1423
691a2d25 1424/**
1425 * This function converts cid: url's into the ones that can be viewed in
1426 * the browser.
1427 *
1428 * @param $message the message object
1429 * @param $id the message id
1430 * @param $cidurl the cid: url.
1431 * @return a string with a http-friendly url
1432 */
b3af12ef 1433function sq_cid2http($message, $id, $cidurl, $mailbox){
691a2d25 1434 /**
1435 * Get rid of quotes.
1436 */
1437 $quotchar = substr($cidurl, 0, 1);
1438 $cidurl = str_replace($quotchar, "", $cidurl);
1439 $cidurl = substr(trim($cidurl), 4);
e5e9381a 1440 $linkurl = find_ent_id($cidurl, $message);
1441 /* in case of non-save cid links $httpurl should be replaced by a sort of
1442 unsave link image */
1443 $httpurl = '';
1444 if ($linkurl) {
6b04287c 1445 $httpurl = $quotchar . SM_PATH . 'src/download.php?absolute_dl=true&amp;' .
e5e9381a 1446 "passed_id=$id&amp;mailbox=" . urlencode($mailbox) .
3d8371be 1447 '&amp;ent_id=' . $linkurl . $quotchar;
e5e9381a 1448 }
691a2d25 1449 return $httpurl;
1450}
1451
1452/**
1453 * This function changes the <body> tag into a <div> tag since we
1454 * can't really have a body-within-body.
1455 *
1456 * @param $attary an array of attributes and values of <body>
1457 * @return a modified array of attributes to be set for <div>
1458 */
1459function sq_body2div($attary){
b583c3e8 1460 $me = 'sq_body2div';
3d8371be 1461 $divattary = Array('class' => "'bodyclass'");
b583c3e8 1462 $bgcolor = '#ffffff';
1463 $text = '#000000';
1464 $styledef = '';
691a2d25 1465 if (is_array($attary) && sizeof($attary) > 0){
1466 foreach ($attary as $attname=>$attvalue){
1467 $quotchar = substr($attvalue, 0, 1);
1468 $attvalue = str_replace($quotchar, "", $attvalue);
1469 switch ($attname){
3d8371be 1470 case 'background':
1471 $styledef .= "background-image: url('$attvalue'); ";
1472 break;
1473 case 'bgcolor':
1474 $styledef .= "background-color: $attvalue; ";
1475 break;
1476 case 'text':
1477 $styledef .= "color: $attvalue; ";
1478 break;
691a2d25 1479 }
a3daaaf3 1480 }
691a2d25 1481 if (strlen($styledef) > 0){
1482 $divattary{"style"} = "\"$styledef\"";
1483 }
1484 }
1485 return $divattary;
1486}
a3daaaf3 1487
691a2d25 1488/**
1489 * This is the main function and the one you should actually be calling.
1490 * There are several variables you should be aware of an which need
1491 * special description.
1492 *
1493 * Since the description is quite lengthy, see it here:
1494 * http://www.mricon.com/html/phpfilter.html
1495 *
1496 * @param $body the string with HTML you wish to filter
1497 * @param $tag_list see description above
1498 * @param $rm_tags_with_content see description above
1499 * @param $self_closing_tags see description above
1500 * @param $force_tag_closing see description above
1501 * @param $rm_attnames see description above
1502 * @param $bad_attvals see description above
1503 * @param $add_attr_to_tag see description above
1504 * @param $message message object
1505 * @param $id message id
1506 * @return sanitized html safe to show on your pages.
1507 */
1508function sq_sanitize($body,
1509 $tag_list,
1510 $rm_tags_with_content,
1511 $self_closing_tags,
1512 $force_tag_closing,
1513 $rm_attnames,
1514 $bad_attvals,
1515 $add_attr_to_tag,
1516 $message,
b3af12ef 1517 $id,
3d8371be 1518 $mailbox
691a2d25 1519 ){
b583c3e8 1520 $me = 'sq_sanitize';
7d06541f 1521 $rm_tags = array_shift($tag_list);
691a2d25 1522 /**
1523 * Normalize rm_tags and rm_tags_with_content.
1524 */
7d06541f 1525 @array_walk($tag_list, 'sq_casenormalize');
691a2d25 1526 @array_walk($rm_tags_with_content, 'sq_casenormalize');
1527 @array_walk($self_closing_tags, 'sq_casenormalize');
1528 /**
1529 * See if tag_list is of tags to remove or tags to allow.
1530 * false means remove these tags
1531 * true means allow these tags
1532 */
691a2d25 1533 $curpos = 0;
1534 $open_tags = Array();
1535 $trusted = "<!-- begin sanitized html -->\n";
1536 $skip_content = false;
bb8d0799 1537 /**
1538 * Take care of netscape's stupid javascript entities like
1539 * &{alert('boo')};
1540 */
1541 $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
691a2d25 1542
7d06541f 1543 while (($curtag = sq_getnxtag($body, $curpos)) != FALSE){
691a2d25 1544 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1545 $free_content = substr($body, $curpos, $lt-$curpos);
1546 /**
1547 * Take care of <style>
1548 */
7d06541f 1549 if ($tagname == "style" && $tagtype == 1){
1550 list($free_content, $curpos) =
1551 sq_fixstyle($body, $gt+1, $message, $id);
1552 if ($free_content != FALSE){
1553 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1554 $trusted .= $free_content;
1555 $trusted .= sq_tagprint($tagname, false, 2);
1556 }
1557 continue;
691a2d25 1558 }
1559 if ($skip_content == false){
1560 $trusted .= $free_content;
691a2d25 1561 }
1562 if ($tagname != FALSE){
1563 if ($tagtype == 2){
1564 if ($skip_content == $tagname){
1565 /**
1566 * Got to the end of tag we needed to remove.
1567 */
1568 $tagname = false;
1569 $skip_content = false;
1570 } else {
1571 if ($skip_content == false){
c828931c 1572 if ($tagname == "body"){
1573 $tagname = "div";
691a2d25 1574 } else {
c828931c 1575 if (isset($open_tags{$tagname}) &&
1576 $open_tags{$tagname} > 0){
1577 $open_tags{$tagname}--;
1578 } else {
1579 $tagname = false;
1580 }
691a2d25 1581 }
691a2d25 1582 }
1583 }
1584 } else {
1585 /**
1586 * $rm_tags_with_content
1587 */
1588 if ($skip_content == false){
1589 /**
1590 * See if this is a self-closing type and change
1591 * tagtype appropriately.
1592 */
1593 if ($tagtype == 1
1594 && in_array($tagname, $self_closing_tags)){
1595 $tagtype=3;
1596 }
1597 /**
1598 * See if we should skip this tag and any content
1599 * inside it.
1600 */
1601 if ($tagtype == 1 &&
1602 in_array($tagname, $rm_tags_with_content)){
1603 $skip_content = $tagname;
1604 } else {
1605 if (($rm_tags == false
1606 && in_array($tagname, $tag_list)) ||
1607 ($rm_tags == true &&
1608 !in_array($tagname, $tag_list))){
1609 $tagname = false;
1610 } else {
1611 if ($tagtype == 1){
1612 if (isset($open_tags{$tagname})){
1613 $open_tags{$tagname}++;
1614 } else {
1615 $open_tags{$tagname}=1;
1616 }
1617 }
1618 /**
1619 * This is where we run other checks.
1620 */
1621 if (is_array($attary) && sizeof($attary) > 0){
1622 $attary = sq_fixatts($tagname,
1623 $attary,
1624 $rm_attnames,
1625 $bad_attvals,
1626 $add_attr_to_tag,
1627 $message,
b3af12ef 1628 $id,
3d8371be 1629 $mailbox
691a2d25 1630 );
1631 }
c828931c 1632 /**
1633 * Convert body into div.
1634 */
1635 if ($tagname == "body"){
1636 $tagname = "div";
1637 $attary = sq_body2div($attary, $message, $id);
1638 }
691a2d25 1639 }
1640 }
691a2d25 1641 }
1642 }
1643 if ($tagname != false && $skip_content == false){
1644 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1645 }
691a2d25 1646 }
1647 $curpos = $gt+1;
a3daaaf3 1648 }
691a2d25 1649 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1650 if ($force_tag_closing == true){
1651 foreach ($open_tags as $tagname=>$opentimes){
1652 while ($opentimes > 0){
1653 $trusted .= '</' . $tagname . '>';
1654 $opentimes--;
1655 }
1656 }
1657 $trusted .= "\n";
1658 }
1659 $trusted .= "<!-- end sanitized html -->\n";
1660 return $trusted;
1661}
451f74a2 1662
691a2d25 1663/**
1664 * This is a wrapper function to call html sanitizing routines.
1665 *
1666 * @param $body the body of the message
1667 * @param $id the id of the message
1668 * @return a string with html safe to display in the browser.
1669 */
7aad7b77 1670function magicHTML($body, $id, $message, $mailbox = 'INBOX') {
691a2d25 1671 global $attachment_common_show_images, $view_unsafe_images,
3d8371be 1672 $has_unsafe_images;
691a2d25 1673 /**
1674 * Don't display attached images in HTML mode.
1675 */
1676 $attachment_common_show_images = false;
1677 $tag_list = Array(
1678 false,
1679 "object",
1680 "meta",
1681 "html",
1682 "head",
cc34b00d 1683 "base",
e18cb31b 1684 "link",
45071bd6 1685 "frame",
1686 "iframe"
691a2d25 1687 );
1688
1689 $rm_tags_with_content = Array(
1690 "script",
1691 "applet",
1692 "embed",
1693 "title"
1694 );
1695
1696 $self_closing_tags = Array(
1697 "img",
1698 "br",
1699 "hr",
1700 "input"
1701 );
1702
1703 $force_tag_closing = false;
1704
1705 $rm_attnames = Array(
1706 "/.*/" =>
1707 Array(
3a50c8d2 1708 "/target/i",
1709 "/^on.*/i",
1710 "/^dynsrc/i",
1711 "/^data.*/i",
1712 "/^lowsrc.*/i"
691a2d25 1713 )
1714 );
1715
1716 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1717 $bad_attvals = Array(
1718 "/.*/" =>
1719 Array(
0a6ec9b5 1720 "/^src|background/i" =>
691a2d25 1721 Array(
1722 Array(
f83c60a2 1723 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1724 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1725 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1726 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
691a2d25 1727 ),
1728 Array(
1729 "\\1$secremoveimg\\2",
bb8d0799 1730 "\\1$secremoveimg\\2",
3d8371be 1731 "\\1$secremoveimg\\2",
1732 "\\1$secremoveimg\\2"
691a2d25 1733 )
1734 ),
0a6ec9b5 1735 "/^href|action/i" =>
1736 Array(
1737 Array(
f83c60a2 1738 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1739 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1740 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1741 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
0a6ec9b5 1742 ),
1743 Array(
1744 "\\1#\\2",
1745 "\\1#\\2",
3d8371be 1746 "\\1#\\2",
1747 "\\1#\\2"
0a6ec9b5 1748 )
1749 ),
f83c60a2 1750 "/^style/i" =>
691a2d25 1751 Array(
1752 Array(
f83c60a2 1753 "/expression/i",
1754 "/binding/i",
1755 "/behaviou*r/i",
7d06541f 1756 "|url\s*\(\s*([\'\"])\s*\.\./.*([\'\"])\s*\)|si",
1757 "/url\s*\(\s*([\'\"])\s*\S+script\s*:.*([\'\"])\s*\)/si",
1758 "/url\s*\(\s*([\'\"])\s*mocha\s*:.*([\'\"])\s*\)/si",
1759 "/url\s*\(\s*([\'\"])\s*about\s*:.*([\'\"])\s*\)/si"
691a2d25 1760 ),
1761 Array(
bb8d0799 1762 "idiocy",
3d8371be 1763 "idiocy",
1764 "idiocy",
1765 "url(\\1#\\2)",
0a6ec9b5 1766 "url(\\1#\\2)",
1767 "url(\\1#\\2)",
3d8371be 1768 "url(\\1#\\2)"
691a2d25 1769 )
1770 )
1771 )
1772 );
5262d9a6 1773 if( !sqgetGlobalVar('view_unsafe_images', $view_unsafe_images, SQ_GET) ) {
7aad7b77 1774 $view_unsafe_images = false;
45071bd6 1775 }
691a2d25 1776 if (!$view_unsafe_images){
1777 /**
1778 * Remove any references to http/https if view_unsafe_images set
1779 * to false.
1780 */
0a6ec9b5 1781 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[0],
f83c60a2 1782 '/^([\'\"])\s*https*:.*([\'\"])/si');
0a6ec9b5 1783 array_push($bad_attvals{'/.*/'}{'/^src|background/i'}[1],
43d678b6 1784 "\\1$secremoveimg\\2");
3a50c8d2 1785 array_push($bad_attvals{'/.*/'}{'/^style/i'}[0],
43d678b6 1786 '/url\(([\'\"])\s*https*:.*([\'\"])\)/si');
3a50c8d2 1787 array_push($bad_attvals{'/.*/'}{'/^style/i'}[1],
43d678b6 1788 "url(\\1$secremoveimg\\2)");
691a2d25 1789 }
451f74a2 1790
691a2d25 1791 $add_attr_to_tag = Array(
f83c60a2 1792 "/^a$/i" => Array('target'=>'"_new"')
691a2d25 1793 );
1794 $trusted = sq_sanitize($body,
1795 $tag_list,
1796 $rm_tags_with_content,
1797 $self_closing_tags,
1798 $force_tag_closing,
1799 $rm_attnames,
1800 $bad_attvals,
1801 $add_attr_to_tag,
1802 $message,
b3af12ef 1803 $id,
3d8371be 1804 $mailbox
691a2d25 1805 );
f83c60a2 1806 if (preg_match("|$secremoveimg|i", $trusted)){
691a2d25 1807 $has_unsafe_images = true;
23bcec6f 1808 }
691a2d25 1809 return $trusted;
451f74a2 1810}
a4a70693 1811
3a50c8d2 1812?>