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