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