fix. (I'm getting tired of explaining the changes)
[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*/
93f92f03 411function formatBody($imap_stream, $message, $color, $wrap_at, $ent_num) {
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
a4a70693 420 $id = $message->id;
93f92f03 421
1d142b8d 422 if ($message->type0 == 'message' && $message->type1 == 'rfc822') {
423 $message = $message->entities[0];
424 }
a4a70693 425 $urlmailbox = urlencode($message->mailbox);
451f74a2 426 $body_message = getEntity($message, $ent_num);
427 if (($body_message->header->type0 == 'text') ||
428 ($body_message->header->type0 == 'rfc822')) {
93f92f03 429 $body = mime_fetch_body ($imap_stream, $id, $ent_num);
430
451f74a2 431 $body = decodeBody($body, $body_message->header->encoding);
432 $hookResults = do_hook("message_body", $body);
433 $body = $hookResults[1];
451f74a2 434 // If there are other types that shouldn't be formatted, add
435 // them here
436 if ($body_message->header->type1 == 'html') {
437 if ( $show_html_default <> 1 ) {
a3daaaf3 438 $body = strip_tags( $body );
439 translateText($body, $wrap_at, $body_message->header->charset);
440 } else {
93f92f03 441 $body = magicHTML( $body, $id, $message );
a3daaaf3 442 }
451f74a2 443 } else {
9eea179c 444 translateText($body, $wrap_at, $body_message->header->charset);
451f74a2 445 }
e5ea9327 446 $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 447 if ($has_unsafe_images) {
448 if ($view_unsafe_images) {
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\">". _("Hide Unsafe Images") ."</A></SMALL></CENTER><BR>\n";
d03c24f4 450 } else {
3d1c7564 451 $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 452 }
7e235a1a 453 }
77b88425 454
451f74a2 455 /** Display the ATTACHMENTS: message if there's more than one part **/
a4a70693 456 if ($message->type0 == 'message') {
457 $id = $message->id;
458 $mailbox = $message->mailbox;
459// $message->header->setVar('message_id',$id);
460// $message->header->setVar('mailbox',$mailbox);
461 }
164800ad 462 if (isset($message->entities[1])) {
e22815be 463 /* Header-type alternative means we choose the best one to display
464 so don't show the alternatives as attachment. Header-type related
465 means that the attachments are already part of the related message.
466 */
467 if ($message->header->type1 !='related' && $message->header->type1 !='alternative') {
a4a70693 468 $body .= formatAttachments ($message, $ent_num, $message->mailbox, $id);
e22815be 469 }
451f74a2 470 }
451f74a2 471 } else {
a4a70693 472 $body = formatAttachments ($message, -1, $message->mailbox, $id);
451f74a2 473 }
474 return ($body);
475}
b74ba498 476
451f74a2 477/*
478 * A recursive function that returns a list of attachments with links
479 * to where to download these attachments
480 */
77b88425 481function formatAttachments($message, $ent_id, $mailbox, $id) {
482 global $where, $what;
483 global $startMessage, $color;
484 static $ShownHTML = 0;
451f74a2 485
77b88425 486 $body = '';
487 if ($ShownHTML == 0) {
451f74a2 488
77b88425 489 $ShownHTML = 1;
451f74a2 490 $body .= "<TABLE WIDTH=\"100%\" CELLSPACING=0 CELLPADDING=2 BORDER=0 BGCOLOR=\"$color[0]\"><TR>\n" .
77b88425 491 "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n" .
492 _("Attachments") . ':' .
493 "</B></TH></TR><TR><TD>\n" .
494 "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n" .
495 formatAttachments($message, $ent_id, $mailbox, $id) .
496 "</TABLE></TD></TR></TABLE>";
497
498 } else if ($message) {
f0c4dc12 499 $header = $message->header;
500 $type0 = strtolower($header->type0);
501 $type1 = strtolower($header->type1);
2d0476d6 502 $name = '';
503 if (isset($header->name)) {
504 $name = decodeHeader($header->name);
505 }
1fbbe1d4 506 if ($type0 =='message' && $type1 == 'rfc822') {
f0c4dc12 507
a4a70693 508 $filename = decodeHeader($message->header->subject);
509 $display_filename = $filename;
510
f0c4dc12 511 $urlMailbox = urlencode($mailbox);
a4a70693 512 $ent = urlencode($message->entity_id);
f0c4dc12 513
514 $DefaultLink =
a4a70693 515 "../src/read_body.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
f0c4dc12 516 if ($where && $what) {
517 $DefaultLink .= '&amp;where=' . urlencode($where) . '&amp;what=' . urlencode($what);
518 }
519 $Links['download link']['text'] = _("download");
520 $Links['download link']['href'] =
521 "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
522 $ImageURL = '';
523
524 /* this executes the attachment hook with a specific MIME-type.
525 * if that doens't have results, it tries if there's a rule
526 * for a more generic type. */
527 $HookResults = do_hook("attachment $type0/$type1", $Links,
528 $startMessage, $id, $urlMailbox, $ent, $DefaultLink, $display_filename, $where, $what);
529 if(count($HookResults[1]) <= 1) {
530 $HookResults = do_hook("attachment $type0/*", $Links,
531 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
532 $display_filename, $where, $what);
533 }
534
535 $Links = $HookResults[1];
536 $DefaultLink = $HookResults[6];
537
538 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
539 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
540 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
541 '</b>&nbsp;&nbsp;</small></TD>' .
542 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
543 '<TD><SMALL>';
a4a70693 544 $from_o = $message->header->from;
545 if (isset($from_o)) {
546 $from_name = $from_o->getAddress(false);
547 } else {
548 $from_name = _("Unknown sender");
549 }
550 $from_name = decodeHeader(htmlspecialchars($from_name));
551 $body .= '<b>' . $from_name . '</b>';
f0c4dc12 552 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
553
f0c4dc12 554 $SkipSpaces = 1;
555 foreach ($Links as $Val) {
556 if ($SkipSpaces) {
557 $SkipSpaces = 0;
558 } else {
559 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
560 }
561 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
562 }
563
564 unset($Links);
77b88425 565
f0c4dc12 566 $body .= "</SMALL></TD></TR>\n";
567
568 return( $body );
569
570 } elseif (!$message->entities) {
77b88425 571
572 $type0 = strtolower($message->header->type0);
573 $type1 = strtolower($message->header->type1);
574 $name = decodeHeader($message->header->name);
575
a4a70693 576 if ($message->entity_id != $ent_id) {
77b88425 577 $filename = decodeHeader($message->header->filename);
578 if (trim($filename) == '') {
579 if (trim($name) == '') {
580 if ( trim( $message->header->id ) == '' )
a4a70693 581 $display_filename = 'untitled-[' . $message->entity_id . ']' ;
77b88425 582 else
583 $display_filename = 'cid: ' . $message->header->id;
a4a70693 584 // $display_filename = 'untitled-[' . $message->entity_id . ']' ;
77b88425 585 } else {
586 $display_filename = $name;
587 $filename = $name;
588 }
589 } else {
590 $display_filename = $filename;
591 }
451f74a2 592
77b88425 593 $urlMailbox = urlencode($mailbox);
a4a70693 594 $ent = urlencode($message->entity_id);
451f74a2 595
77b88425 596 $DefaultLink =
e5ea9327 597 "../src/download.php?startMessage=$startMessage&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
77b88425 598 if ($where && $what) {
ed268948 599 $DefaultLink = '&amp;where='. urlencode($where).'&amp;what='.urlencode($what);
77b88425 600 }
601 $Links['download link']['text'] = _("download");
602 $Links['download link']['href'] =
e5ea9327 603 "../src/download.php?absolute_dl=true&amp;passed_id=$id&amp;mailbox=$urlMailbox&amp;passed_ent_id=$ent";
77b88425 604 $ImageURL = '';
605
606 /* this executes the attachment hook with a specific MIME-type.
607 * if that doens't have results, it tries if there's a rule
608 * for a more generic type. */
609 $HookResults = do_hook("attachment $type0/$type1", $Links,
610 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
611 $display_filename, $where, $what);
612 if(count($HookResults[1]) <= 1) {
613 $HookResults = do_hook("attachment $type0/*", $Links,
614 $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
615 $display_filename, $where, $what);
616 }
451f74a2 617
77b88425 618 $Links = $HookResults[1];
619 $DefaultLink = $HookResults[6];
620
621 $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>' .
622 "<A HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>" .
623 '<TD><SMALL><b>' . show_readable_size($message->header->size) .
624 '</b>&nbsp;&nbsp;</small></TD>' .
625 "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>" .
626 '<TD><SMALL>';
627 if ($message->header->description) {
628 $body .= '<b>' . htmlspecialchars(_($message->header->description)) . '</b>';
629 }
630 $body .= '</SMALL></TD><TD><SMALL>&nbsp;';
b74ba498 631
b74ba498 632
77b88425 633 $SkipSpaces = 1;
634 foreach ($Links as $Val) {
635 if ($SkipSpaces) {
636 $SkipSpaces = 0;
637 } else {
638 $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
639 }
640 $body .= '<a href="' . $Val['href'] . '">' . $Val['text'] . '</a>';
641 }
642
643 unset($Links);
644
645 $body .= "</SMALL></TD></TR>\n";
646 }
647 } else {
648 for ($i = 0; $i < count($message->entities); $i++) {
649 $body .= formatAttachments($message->entities[$i], $ent_id, $mailbox, $id);
650 }
451f74a2 651 }
77b88425 652 }
653 return( $body );
451f74a2 654}
b74ba498 655
b74ba498 656
451f74a2 657/** this function decodes the body depending on the encoding type. **/
658function decodeBody($body, $encoding) {
659 $body = str_replace("\r\n", "\n", $body);
660 $encoding = strtolower($encoding);
b74ba498 661
451f74a2 662 global $show_html_default;
4809f489 663
56c094f5 664 if ($encoding == 'quoted-printable' ||
665 $encoding == 'quoted_printable') {
451f74a2 666 $body = quoted_printable_decode($body);
4809f489 667
451f74a2 668 while (ereg("=\n", $body))
669 $body = ereg_replace ("=\n", "", $body);
358f007e 670
451f74a2 671 } else if ($encoding == 'base64') {
672 $body = base64_decode($body);
673 }
b74ba498 674
451f74a2 675 // All other encodings are returned raw.
676 return $body;
677}
678
679/*
680 * This functions decode strings that is encoded according to
681 * RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
79e07c7e 682 * Patched by Christian Schmidt <christian@ostenfeld.dk> 23/03/2002
451f74a2 683 */
684function decodeHeader ($string, $utfencode=true) {
79e07c7e 685 if (is_array($string)) {
686 $string = implode("\n", $string);
687 }
688 $i = 0;
689 while (preg_match('/^(.{' . $i . '})(.*)=\?([^?]*)\?(Q|B)\?([^?]*)\?=/Ui',
690 $string, $res)) {
691 $prefix = $res[1];
692 // Ignore white-space between consecutive encoded-words
693 if (strspn($res[2], " \t") != strlen($res[2])) {
694 $prefix .= $res[2];
695 }
18aa168e 696
79e07c7e 697 if (ucfirst($res[4]) == 'B') {
698 $replace = base64_decode($res[5]);
699 } else {
700 $replace = str_replace('_', ' ', $res[5]);
701 $replace = preg_replace('/=([0-9a-f]{2})/ie', 'chr(hexdec("\1"))',
702 $replace);
703 /* Only encode into entities by default. Some places
704 don't need the encoding, like the compose form. */
705 if ($utfencode) {
706 $replace = charset_decode($res[3], $replace);
707 }
18aa168e 708 }
79e07c7e 709 $string = $prefix . $replace . substr($string, strlen($res[0]));
710 $i = strlen($prefix) + strlen($replace);
18aa168e 711 }
79e07c7e 712 return( $string );
451f74a2 713}
714
715/*
716 * Encode a string according to RFC 1522 for use in headers if it
717 * contains 8-bit characters or anything that looks like it should
718 * be encoded.
719 */
720function encodeHeader ($string) {
721 global $default_charset;
793cc001 722
451f74a2 723 // Encode only if the string contains 8-bit characters or =?
724 $j = strlen( $string );
725 $l = strstr($string, '=?'); // Must be encoded ?
726 $ret = '';
727 for( $i=0; $i < $j; ++$i) {
f7b3ba37 728 switch( $string{$i} ) {
729 case '=':
b74ba498 730 $ret .= '=3D';
731 break;
451f74a2 732 case '?':
b74ba498 733 $ret .= '=3F';
734 break;
451f74a2 735 case '_':
b74ba498 736 $ret .= '=5F';
737 break;
451f74a2 738 case ' ':
b74ba498 739 $ret .= '_';
740 break;
451f74a2 741 default:
b74ba498 742 $k = ord( $string{$i} );
451f74a2 743 if ( $k > 126 ) {
b74ba498 744 $ret .= sprintf("=%02X", $k);
745 $l = TRUE;
746 } else
747 $ret .= $string{$i};
f7b3ba37 748 }
451f74a2 749 }
793cc001 750
451f74a2 751 if ( $l ) {
f7b3ba37 752 $string = "=?$default_charset?Q?$ret?=";
451f74a2 753 }
346817d4 754
451f74a2 755 return( $string );
756}
b74ba498 757
691a2d25 758/* This function trys to locate the entity_id of a specific mime element */
451f74a2 759
691a2d25 760function find_ent_id( $id, $message ) {
761 $ret = '';
762 for ($i=0; $ret == '' && $i < count($message->entities); $i++) {
a4a70693 763 if ( $message->entities[$i]->header->type0 == 'multipart') {
164800ad 764 $ret = find_ent_id( $id, $message->entities[$i] );
451f74a2 765 } else {
691a2d25 766 if ( strcasecmp( $message->entities[$i]->header->id, $id ) == 0 )
a4a70693 767 $ret = $message->entities[$i]->entity_id;
a3daaaf3 768 }
451f74a2 769 }
691a2d25 770 return( $ret );
451f74a2 771}
a3daaaf3 772
691a2d25 773/**
774 ** HTMLFILTER ROUTINES
775 */
451f74a2 776
691a2d25 777/**
778 * This function returns the final tag out of the tag name, an array
779 * of attributes, and the type of the tag. This function is called by
780 * sq_sanitize internally.
781 *
782 * @param $tagname the name of the tag.
783 * @param $attary the array of attributes and their values
784 * @param $tagtype The type of the tag (see in comments).
785 * @return a string with the final tag representation.
786 */
787function sq_tagprint($tagname, $attary, $tagtype){
788 $me = "sq_tagprint";
789 if ($tagtype == 2){
790 $fulltag = '</' . $tagname . '>';
791 } else {
792 $fulltag = '<' . $tagname;
793 if (is_array($attary) && sizeof($attary)){
794 $atts = Array();
795 while (list($attname, $attvalue) = each($attary)){
796 array_push($atts, "$attname=$attvalue");
797 }
798 $fulltag .= ' ' . join(" ", $atts);
799 }
800 if ($tagtype == 3){
801 $fulltag .= " /";
802 }
803 $fulltag .= ">";
451f74a2 804 }
691a2d25 805 return $fulltag;
451f74a2 806}
a3daaaf3 807
691a2d25 808/**
809 * A small helper function to use with array_walk. Modifies a by-ref
810 * value and makes it lowercase.
811 *
812 * @param $val a value passed by-ref.
813 * @return void since it modifies a by-ref value.
814 */
815function sq_casenormalize(&$val){
816 $val = strtolower($val);
817}
451f74a2 818
691a2d25 819/**
820 * This function skips any whitespace from the current position within
821 * a string and to the next non-whitespace value.
822 *
823 * @param $body the string
824 * @param $offset the offset within the string where we should start
825 * looking for the next non-whitespace character.
826 * @return the location within the $body where the next
827 * non-whitespace char is located.
828 */
829function sq_skipspace($body, $offset){
830 $me = "sq_skipspace";
831 preg_match("/^(\s*)/s", substr($body, $offset), $matches);
832 if (sizeof($matches{1})){
833 $count = strlen($matches{1});
834 $offset += $count;
451f74a2 835 }
691a2d25 836 return $offset;
451f74a2 837}
a3daaaf3 838
691a2d25 839/**
840 * This function looks for the next character within a string. It's
841 * really just a glorified "strpos", except it catches if failures
842 * nicely.
843 *
844 * @param $body The string to look for needle in.
845 * @param $offset Start looking from this position.
846 * @param $needle The character/string to look for.
847 * @return location of the next occurance of the needle, or
848 * strlen($body) if needle wasn't found.
849 */
850function sq_findnxstr($body, $offset, $needle){
851 $me = "sq_findnxstr";
852 $pos = strpos($body, $needle, $offset);
853 if ($pos === FALSE){
854 $pos = strlen($body);
451f74a2 855 }
691a2d25 856 return $pos;
451f74a2 857}
a3daaaf3 858
691a2d25 859/**
860 * This function takes a PCRE-style regexp and tries to match it
861 * within the string.
862 *
863 * @param $body The string to look for needle in.
864 * @param $offset Start looking from here.
865 * @param $reg A PCRE-style regex to match.
866 * @return Returns a false if no matches found, or an array
867 * with the following members:
868 * - integer with the location of the match within $body
869 * - string with whatever content between offset and the match
870 * - string with whatever it is we matched
871 */
872function sq_findnxreg($body, $offset, $reg){
873 $me = "sq_findnxreg";
874 $matches = Array();
875 $retarr = Array();
876 preg_match("%^(.*?)($reg)%s", substr($body, $offset), $matches);
877 if (!$matches{0}){
878 $retarr = false;
879 } else {
880 $retarr{0} = $offset + strlen($matches{1});
881 $retarr{1} = $matches{1};
882 $retarr{2} = $matches{2};
883 }
884 return $retarr;
885}
a3daaaf3 886
691a2d25 887/**
888 * This function looks for the next tag.
889 *
890 * @param $body String where to look for the next tag.
891 * @param $offset Start looking from here.
892 * @return false if no more tags exist in the body, or
893 * an array with the following members:
894 * - string with the name of the tag
895 * - array with attributes and their values
896 * - integer with tag type (1, 2, or 3)
897 * - integer where the tag starts (starting "<")
898 * - integer where the tag ends (ending ">")
899 * first three members will be false, if the tag is invalid.
900 */
901function sq_getnxtag($body, $offset){
902 $me = "sq_getnxtag";
903 if ($offset > strlen($body)){
904 return false;
905 }
906 $lt = sq_findnxstr($body, $offset, "<");
907 if ($lt == strlen($body)){
908 return false;
909 }
910 /**
911 * We are here:
912 * blah blah <tag attribute="value">
913 * \---------^
914 */
915 $pos = sq_skipspace($body, $lt+1);
916 if ($pos >= strlen($body)){
917 return Array(false, false, false, $lt, strlen($body));
918 }
919 /**
920 * There are 3 kinds of tags:
921 * 1. Opening tag, e.g.:
922 * <a href="blah">
923 * 2. Closing tag, e.g.:
924 * </a>
925 * 3. XHTML-style content-less tag, e.g.:
926 * <img src="blah"/>
927 */
928 $tagtype = false;
929 switch (substr($body, $pos, 1)){
930 case "/":
931 $tagtype = 2;
932 $pos++;
933 break;
934 case "!":
935 /**
936 * A comment or an SGML declaration.
937 */
938 if (substr($body, $pos+1, 2) == "--"){
bb8d0799 939 $gt = strpos($body, "-->", $pos);
691a2d25 940 if ($gt === false){
941 $gt = strlen($body);
bb8d0799 942 } else {
943 $gt += 2;
944 }
691a2d25 945 return Array(false, false, false, $lt, $gt);
946 } else {
947 $gt = sq_findnxstr($body, $pos, ">");
948 return Array(false, false, false, $lt, $gt);
949 }
950 break;
951 default:
952 /**
953 * Assume tagtype 1 for now. If it's type 3, we'll switch values
954 * later.
955 */
956 $tagtype = 1;
957 break;
958 }
a3daaaf3 959
691a2d25 960 $tag_start = $pos;
961 $tagname = '';
962 /**
963 * Look for next [\W-_], which will indicate the end of the tag name.
964 */
965 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
966 if ($regary == false){
967 return Array(false, false, false, $lt, strlen($body));
968 }
969 list($pos, $tagname, $match) = $regary;
970 $tagname = strtolower($tagname);
971
972 /**
973 * $match can be either of these:
974 * '>' indicating the end of the tag entirely.
975 * '\s' indicating the end of the tag name.
976 * '/' indicating that this is type-3 xhtml tag.
977 *
978 * Whatever else we find there indicates an invalid tag.
979 */
980 switch ($match){
981 case "/":
982 /**
983 * This is an xhtml-style tag with a closing / at the
984 * end, like so: <img src="blah"/>. Check if it's followed
985 * by the closing bracket. If not, then this tag is invalid
986 */
987 if (substr($body, $pos, 2) == "/>"){
988 $pos++;
989 $tagtype = 3;
990 } else {
991 $gt = sq_findnxstr($body, $pos, ">");
992 $retary = Array(false, false, false, $lt, $gt);
993 return $retary;
994 }
995 case ">":
996 return Array($tagname, false, $tagtype, $lt, $pos);
997 break;
998 default:
999 /**
1000 * Check if it's whitespace
1001 */
1002 if (preg_match("/\s/", $match)){
1003 } else {
1004 /**
1005 * This is an invalid tag! Look for the next closing ">".
1006 */
1007 $gt = sq_findnxstr($body, $offset, ">");
1008 return Array(false, false, false, $lt, $gt);
1009 }
1010 }
1011
1012 /**
1013 * At this point we're here:
1014 * <tagname attribute='blah'>
1015 * \-------^
1016 *
1017 * At this point we loop in order to find all attributes.
1018 */
1019 $attname = '';
1020 $atttype = false;
1021 $attary = Array();
1022
1023 while ($pos <= strlen($body)){
1024 $pos = sq_skipspace($body, $pos);
1025 if ($pos == strlen($body)){
1026 /**
1027 * Non-closed tag.
1028 */
1029 return Array(false, false, false, $lt, $pos);
1030 }
1031 /**
1032 * See if we arrived at a ">" or "/>", which means that we reached
1033 * the end of the tag.
1034 */
1035 $matches = Array();
164800ad 1036 if (preg_match("%^(\s*)(>|/>)%s", substr($body, $pos), $matches)) {
c828931c 1037 /**
1038 * Yep. So we did.
1039 */
1040 $pos += strlen($matches{1});
1041 if ($matches{2} == "/>"){
1042 $tagtype = 3;
1043 $pos++;
1044 }
1045 return Array($tagname, $attary, $tagtype, $lt, $pos);
1046 }
a3daaaf3 1047
cca46357 1048 /**
691a2d25 1049 * There are several types of attributes, with optional
1050 * [:space:] between members.
1051 * Type 1:
1052 * attrname[:space:]=[:space:]'CDATA'
1053 * Type 2:
1054 * attrname[:space:]=[:space:]"CDATA"
1055 * Type 3:
1056 * attr[:space:]=[:space:]CDATA
1057 * Type 4:
1058 * attrname
cca46357 1059 *
691a2d25 1060 * We leave types 1 and 2 the same, type 3 we check for
1061 * '"' and convert to "&quot" if needed, then wrap in
1062 * double quotes. Type 4 we convert into:
1063 * attrname="yes".
cca46357 1064 */
691a2d25 1065 $regary = sq_findnxreg($body, $pos, "[^\w\-_]");
1066 if ($regary == false){
1067 /**
1068 * Looks like body ended before the end of tag.
1069 */
1070 return Array(false, false, false, $lt, strlen($body));
cca46357 1071 }
691a2d25 1072 list($pos, $attname, $match) = $regary;
1073 $attname = strtolower($attname);
1074 /**
1075 * We arrived at the end of attribute name. Several things possible
1076 * here:
1077 * '>' means the end of the tag and this is attribute type 4
1078 * '/' if followed by '>' means the same thing as above
1079 * '\s' means a lot of things -- look what it's followed by.
1080 * anything else means the attribute is invalid.
1081 */
1082 switch($match){
1083 case "/":
1084 /**
1085 * This is an xhtml-style tag with a closing / at the
1086 * end, like so: <img src="blah"/>. Check if it's followed
1087 * by the closing bracket. If not, then this tag is invalid
1088 */
1089 if (substr($body, $pos, 2) == "/>"){
1090 $pos++;
1091 $tagtype = 3;
1092 } else {
50ab7972 1093 $gt = sq_findnxstr($body, $pos, ">");
691a2d25 1094 $retary = Array(false, false, false, $lt, $gt);
1095 return $retary;
451f74a2 1096 }
691a2d25 1097 case ">":
1098 $attary{$attname} = '"yes"';
1099 return Array($tagname, $attary, $tagtype, $lt, $pos);
1100 break;
1101 default:
1102 /**
1103 * Skip whitespace and see what we arrive at.
1104 */
1105 $pos = sq_skipspace($body, $pos);
1106 $char = substr($body, $pos, 1);
1107 /**
1108 * Two things are valid here:
1109 * '=' means this is attribute type 1 2 or 3.
1110 * \w means this was attribute type 4.
1111 * anything else we ignore and re-loop. End of tag and
1112 * invalid stuff will be caught by our checks at the beginning
1113 * of the loop.
1114 */
1115 if ($char == "="){
1116 $pos++;
1117 $pos = sq_skipspace($body, $pos);
1118 /**
1119 * Here are 3 possibilities:
1120 * "'" attribute type 1
1121 * '"' attribute type 2
1122 * everything else is the content of tag type 3
1123 */
1124 $quot = substr($body, $pos, 1);
1125 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 if ($quot == '"'){
1134 $regary = sq_findnxreg($body, $pos+1, '\"');
1135 if ($regary == false){
1136 return Array(false, false, false, $lt, strlen($body));
1137 }
1138 list($pos, $attval, $match) = $regary;
1139 $pos++;
1140 $attary{$attname} = '"' . $attval . '"';
1141 } else {
1142 /**
1143 * These are hateful. Look for \s, or >.
1144 */
1145 $regary = sq_findnxreg($body, $pos, "[\s>]");
1146 if ($regary == false){
1147 return Array(false, false, false, $lt, strlen($body));
7e235a1a 1148 }
691a2d25 1149 list($pos, $attval, $match) = $regary;
1150 /**
1151 * If it's ">" it will be caught at the top.
1152 */
1153 $attval = preg_replace("/\"/s", "&quot;", $attval);
1154 $attary{$attname} = '"' . $attval . '"';
451f74a2 1155 }
691a2d25 1156 } else if (preg_match("|[\w/>]|", $char)) {
1157 /**
1158 * That was attribute type 4.
1159 */
1160 $attary{$attname} = '"yes"';
451f74a2 1161 } else {
691a2d25 1162 /**
1163 * An illegal character. Find next '>' and return.
1164 */
1165 $gt = sq_findnxstr($body, $pos, ">");
1166 return Array(false, false, false, $lt, $gt);
451f74a2 1167 }
691a2d25 1168 }
1169 }
1170 /**
1171 * The fact that we got here indicates that the tag end was never
1172 * found. Return invalid tag indication so it gets stripped.
1173 */
1174 return Array(false, false, false, $lt, strlen($body));
1175}
1176
1177/**
1178 * This function checks attribute values for entity-encoded values
1179 * and returns them translated into 8-bit strings so we can run
1180 * checks on them.
1181 *
1182 * @param $attvalue A string to run entity check against.
1183 * @return Translated value.
1184 */
1185function sq_deent($attvalue){
1186 $me="sq_deent";
1187 /**
1188 * See if we have to run the checks first. All entities must start
1189 * with "&".
1190 */
1191 if (strpos($attvalue, "&") === false){
1192 return $attvalue;
1193 }
1194 /**
1195 * Check named entities first.
1196 */
1197 $trans = get_html_translation_table(HTML_ENTITIES);
1198 /**
1199 * Leave &quot; in, as it can mess us up.
1200 */
1201 $trans = array_flip($trans);
1202 unset($trans{"&quot;"});
1203 while (list($ent, $val) = each($trans)){
1204 $attvalue = preg_replace("/$ent*(\W)/si", "$val\\1", $attvalue);
1205 }
1206 /**
1207 * Now translate numbered entities from 1 to 255 if needed.
1208 */
1209 if (strpos($attvalue, "#") !== false){
1210 $omit = Array(34, 39);
1211 for ($asc=1; $asc<256; $asc++){
1212 if (!in_array($asc, $omit)){
1213 $chr = chr($asc);
1214 $attvalue = preg_replace("/\&#0*$asc;*(\D)/si", "$chr\\1",
1215 $attvalue);
1216 $attvalue = preg_replace("/\&#x0*".dechex($asc).";*(\W)/si",
1217 "$chr\\1", $attvalue);
a3daaaf3 1218 }
691a2d25 1219 }
1220 }
1221 return $attvalue;
1222}
1223
1224/**
1225 * This function runs various checks against the attributes.
1226 *
1227 * @param $tagname String with the name of the tag.
1228 * @param $attary Array with all tag attributes.
1229 * @param $rm_attnames See description for sq_sanitize
1230 * @param $bad_attvals See description for sq_sanitize
1231 * @param $add_attr_to_tag See description for sq_sanitize
1232 * @param $message message object
1233 * @param $id message id
1234 * @return Array with modified attributes.
1235 */
1236function sq_fixatts($tagname,
1237 $attary,
1238 $rm_attnames,
1239 $bad_attvals,
1240 $add_attr_to_tag,
1241 $message,
1242 $id
1243 ){
1244 $me = "sq_fixatts";
1245 while (list($attname, $attvalue) = each($attary)){
1246 /**
1247 * See if this attribute should be removed.
1248 */
1249 foreach ($rm_attnames as $matchtag=>$matchattrs){
1250 if (preg_match($matchtag, $tagname)){
1251 foreach ($matchattrs as $matchattr){
1252 if (preg_match($matchattr, $attname)){
1253 unset($attary{$attname});
1254 continue;
1255 }
451f74a2 1256 }
451f74a2 1257 }
691a2d25 1258 }
1259 /**
1260 * Remove any entities.
1261 */
1262 $attvalue = sq_deent($attvalue);
1263
1264 /**
1265 * Now let's run checks on the attvalues.
1266 * I don't expect anyone to comprehend this. If you do,
1267 * get in touch with me so I can drive to where you live and
1268 * shake your hand personally. :)
1269 */
1270 foreach ($bad_attvals as $matchtag=>$matchattrs){
1271 if (preg_match($matchtag, $tagname)){
1272 foreach ($matchattrs as $matchattr=>$valary){
1273 if (preg_match($matchattr, $attname)){
1274 /**
1275 * There are two arrays in valary.
1276 * First is matches.
1277 * Second one is replacements
1278 */
1279 list($valmatch, $valrepl) = $valary;
1280 $newvalue =
1281 preg_replace($valmatch, $valrepl, $attvalue);
1282 if ($newvalue != $attvalue){
1283 $attary{$attname} = $newvalue;
1284 }
1285 }
1286 }
451f74a2 1287 }
a3daaaf3 1288 }
691a2d25 1289 /**
1290 * Turn cid: urls into http-friendly ones.
1291 */
1292 if (preg_match("/^[\'\"]\s*cid:/si", $attvalue)){
1293 $attary{$attname} = sq_cid2http($message, $id, $attvalue);
1294 }
a3daaaf3 1295 }
691a2d25 1296 /**
1297 * See if we need to append any attributes to this tag.
1298 */
1299 foreach ($add_attr_to_tag as $matchtag=>$addattary){
1300 if (preg_match($matchtag, $tagname)){
1301 $attary = array_merge($attary, $addattary);
1302 }
1303 }
1304 return $attary;
451f74a2 1305}
a3daaaf3 1306
691a2d25 1307/**
1308 * This function edits the style definition to make them friendly and
1309 * usable in squirrelmail.
1310 *
1311 * @param $message the message object
1312 * @param $id the message id
1313 * @param $content a string with whatever is between <style> and </style>
1314 * @return a string with edited content.
1315 */
1316function sq_fixstyle($message, $id, $content){
1317 global $view_unsafe_images;
1318 $me = "sq_fixstyle";
1319 /**
1320 * First look for general BODY style declaration, which would be
1321 * like so:
1322 * body {background: blah-blah}
1323 * and change it to .bodyclass so we can just assign it to a <div>
1324 */
1325 $content = preg_replace("|body(\s*\{.*?\})|si", ".bodyclass\\1", $content);
1326 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1327 /**
1328 * Fix url('blah') declarations.
1329 */
1330 $content = preg_replace("|url\(([\'\"])\s*\S+script\s*:.*?([\'\"])\)|si",
1331 "url(\\1$secremoveimg\\2)", $content);
1332 /**
1333 * Fix url('https*://.*) declarations but only if $view_unsafe_images
1334 * is false.
1335 */
1336 if (!$view_unsafe_images){
1337 $content = preg_replace("|url\(([\'\"])\s*https*:.*?([\'\"])\)|si",
1338 "url(\\1$secremoveimg\\2)", $content);
1339 }
1340
1341 /**
1342 * Fix urls that refer to cid:
1343 */
1344 while (preg_match("|url\(([\'\"]\s*cid:.*?[\'\"])\)|si", $content,
1345 $matches)){
1346 $cidurl = $matches{1};
1347 $httpurl = sq_cid2http($message, $id, $cidurl);
1348 $content = preg_replace("|url\($cidurl\)|si",
1349 "url($httpurl)", $content);
1350 }
a3daaaf3 1351
691a2d25 1352 /**
bb8d0799 1353 * Fix stupid css declarations which lead to vulnerabilities
691a2d25 1354 * in IE.
1355 */
bb8d0799 1356 $match = Array('/expression/si',
1357 '/behaviou*r/si',
1358 '/binding/si');
1359 $replace = Array('idiocy', 'idiocy', 'idiocy');
1360 $content = preg_replace($match, $replace, $content);
691a2d25 1361 return $content;
1362}
a3daaaf3 1363
691a2d25 1364/**
1365 * This function converts cid: url's into the ones that can be viewed in
1366 * the browser.
1367 *
1368 * @param $message the message object
1369 * @param $id the message id
1370 * @param $cidurl the cid: url.
1371 * @return a string with a http-friendly url
1372 */
1373function sq_cid2http($message, $id, $cidurl){
1374 /**
1375 * Get rid of quotes.
1376 */
1377 $quotchar = substr($cidurl, 0, 1);
1378 $cidurl = str_replace($quotchar, "", $cidurl);
1379 $cidurl = substr(trim($cidurl), 4);
1380 $httpurl = $quotchar . "../src/download.php?absolute_dl=true&amp;" .
1d142b8d 1381 "passed_id=$id&amp;mailbox=" . urlencode($message->mailbox) .
691a2d25 1382 "&amp;passed_ent_id=" . find_ent_id($cidurl, $message) . $quotchar;
1383 return $httpurl;
1384}
1385
1386/**
1387 * This function changes the <body> tag into a <div> tag since we
1388 * can't really have a body-within-body.
1389 *
1390 * @param $attary an array of attributes and values of <body>
1391 * @return a modified array of attributes to be set for <div>
1392 */
1393function sq_body2div($attary){
1394 $me = "sq_body2div";
1395 $divattary = Array("class"=>"'bodyclass'");
1396 $bgcolor="#ffffff";
1397 $text="#000000";
1398 $styledef="";
1399 if (is_array($attary) && sizeof($attary) > 0){
1400 foreach ($attary as $attname=>$attvalue){
1401 $quotchar = substr($attvalue, 0, 1);
1402 $attvalue = str_replace($quotchar, "", $attvalue);
1403 switch ($attname){
1404 case "background":
1405 $styledef .= "background-image: url('$attvalue'); ";
1406 break;
1407 case "bgcolor":
1408 $styledef .= "background-color: $attvalue; ";
1409 break;
1410 case "text":
1411 $styledef .= "color: $attvalue; ";
1412 }
a3daaaf3 1413 }
691a2d25 1414 if (strlen($styledef) > 0){
1415 $divattary{"style"} = "\"$styledef\"";
1416 }
1417 }
1418 return $divattary;
1419}
a3daaaf3 1420
691a2d25 1421/**
1422 * This is the main function and the one you should actually be calling.
1423 * There are several variables you should be aware of an which need
1424 * special description.
1425 *
1426 * Since the description is quite lengthy, see it here:
1427 * http://www.mricon.com/html/phpfilter.html
1428 *
1429 * @param $body the string with HTML you wish to filter
1430 * @param $tag_list see description above
1431 * @param $rm_tags_with_content see description above
1432 * @param $self_closing_tags see description above
1433 * @param $force_tag_closing see description above
1434 * @param $rm_attnames see description above
1435 * @param $bad_attvals see description above
1436 * @param $add_attr_to_tag see description above
1437 * @param $message message object
1438 * @param $id message id
1439 * @return sanitized html safe to show on your pages.
1440 */
1441function sq_sanitize($body,
1442 $tag_list,
1443 $rm_tags_with_content,
1444 $self_closing_tags,
1445 $force_tag_closing,
1446 $rm_attnames,
1447 $bad_attvals,
1448 $add_attr_to_tag,
1449 $message,
1450 $id
1451 ){
1452 $me = "sq_sanitize";
1453 /**
1454 * Normalize rm_tags and rm_tags_with_content.
1455 */
1456 @array_walk($rm_tags, 'sq_casenormalize');
1457 @array_walk($rm_tags_with_content, 'sq_casenormalize');
1458 @array_walk($self_closing_tags, 'sq_casenormalize');
1459 /**
1460 * See if tag_list is of tags to remove or tags to allow.
1461 * false means remove these tags
1462 * true means allow these tags
1463 */
1464 $rm_tags = array_shift($tag_list);
1465 $curpos = 0;
1466 $open_tags = Array();
1467 $trusted = "<!-- begin sanitized html -->\n";
1468 $skip_content = false;
bb8d0799 1469 /**
1470 * Take care of netscape's stupid javascript entities like
1471 * &{alert('boo')};
1472 */
1473 $body = preg_replace("/&(\{.*?\};)/si", "&amp;\\1", $body);
691a2d25 1474
1475 while (($curtag=sq_getnxtag($body, $curpos)) != FALSE){
1476 list($tagname, $attary, $tagtype, $lt, $gt) = $curtag;
1477 $free_content = substr($body, $curpos, $lt-$curpos);
1478 /**
1479 * Take care of <style>
1480 */
1481 if ($tagname == "style" && $tagtype == 2){
1482 /**
1483 * This is a closing </style>. Edit the
1484 * content before we apply it.
1485 */
1486 $free_content = sq_fixstyle($message, $id, $free_content);
691a2d25 1487 }
1488 if ($skip_content == false){
1489 $trusted .= $free_content;
1490 } else {
1491 }
1492 if ($tagname != FALSE){
1493 if ($tagtype == 2){
1494 if ($skip_content == $tagname){
1495 /**
1496 * Got to the end of tag we needed to remove.
1497 */
1498 $tagname = false;
1499 $skip_content = false;
1500 } else {
1501 if ($skip_content == false){
c828931c 1502 if ($tagname == "body"){
1503 $tagname = "div";
691a2d25 1504 } else {
c828931c 1505 if (isset($open_tags{$tagname}) &&
1506 $open_tags{$tagname} > 0){
1507 $open_tags{$tagname}--;
1508 } else {
1509 $tagname = false;
1510 }
691a2d25 1511 }
1512 } else {
1513 }
1514 }
1515 } else {
1516 /**
1517 * $rm_tags_with_content
1518 */
1519 if ($skip_content == false){
1520 /**
1521 * See if this is a self-closing type and change
1522 * tagtype appropriately.
1523 */
1524 if ($tagtype == 1
1525 && in_array($tagname, $self_closing_tags)){
1526 $tagtype=3;
1527 }
1528 /**
1529 * See if we should skip this tag and any content
1530 * inside it.
1531 */
1532 if ($tagtype == 1 &&
1533 in_array($tagname, $rm_tags_with_content)){
1534 $skip_content = $tagname;
1535 } else {
1536 if (($rm_tags == false
1537 && in_array($tagname, $tag_list)) ||
1538 ($rm_tags == true &&
1539 !in_array($tagname, $tag_list))){
1540 $tagname = false;
1541 } else {
1542 if ($tagtype == 1){
1543 if (isset($open_tags{$tagname})){
1544 $open_tags{$tagname}++;
1545 } else {
1546 $open_tags{$tagname}=1;
1547 }
1548 }
1549 /**
1550 * This is where we run other checks.
1551 */
1552 if (is_array($attary) && sizeof($attary) > 0){
1553 $attary = sq_fixatts($tagname,
1554 $attary,
1555 $rm_attnames,
1556 $bad_attvals,
1557 $add_attr_to_tag,
1558 $message,
1559 $id
1560 );
1561 }
c828931c 1562 /**
1563 * Convert body into div.
1564 */
1565 if ($tagname == "body"){
1566 $tagname = "div";
1567 $attary = sq_body2div($attary, $message, $id);
1568 }
691a2d25 1569 }
1570 }
1571 } else {
1572 }
1573 }
1574 if ($tagname != false && $skip_content == false){
1575 $trusted .= sq_tagprint($tagname, $attary, $tagtype);
1576 }
1577 } else {
1578 }
1579 $curpos = $gt+1;
a3daaaf3 1580 }
691a2d25 1581 $trusted .= substr($body, $curpos, strlen($body)-$curpos);
1582 if ($force_tag_closing == true){
1583 foreach ($open_tags as $tagname=>$opentimes){
1584 while ($opentimes > 0){
1585 $trusted .= '</' . $tagname . '>';
1586 $opentimes--;
1587 }
1588 }
1589 $trusted .= "\n";
1590 }
1591 $trusted .= "<!-- end sanitized html -->\n";
1592 return $trusted;
1593}
451f74a2 1594
691a2d25 1595/**
1596 * This is a wrapper function to call html sanitizing routines.
1597 *
1598 * @param $body the body of the message
1599 * @param $id the id of the message
1600 * @return a string with html safe to display in the browser.
1601 */
0b331da5 1602function magicHTML($body, $id, $message){
691a2d25 1603 global $attachment_common_show_images, $view_unsafe_images,
794b2d0a 1604 $has_unsafe_images;
691a2d25 1605 /**
1606 * Don't display attached images in HTML mode.
1607 */
1608 $attachment_common_show_images = false;
1609 $tag_list = Array(
1610 false,
1611 "object",
1612 "meta",
1613 "html",
1614 "head",
1615 "base"
1616 );
1617
1618 $rm_tags_with_content = Array(
1619 "script",
1620 "applet",
1621 "embed",
1622 "title"
1623 );
1624
1625 $self_closing_tags = Array(
1626 "img",
1627 "br",
1628 "hr",
1629 "input"
1630 );
1631
1632 $force_tag_closing = false;
1633
1634 $rm_attnames = Array(
1635 "/.*/" =>
1636 Array(
1637 "/target/si",
bb8d0799 1638 "/^on.*/si",
1639 "/^dynsrc/si",
1640 "/^data.*/si"
691a2d25 1641 )
1642 );
1643
1644 $secremoveimg = "../images/" . _("sec_remove_eng.png");
1645 $bad_attvals = Array(
1646 "/.*/" =>
1647 Array(
0a6ec9b5 1648 "/^src|background/i" =>
691a2d25 1649 Array(
1650 Array(
1651 "|^([\'\"])\s*\.\./.*([\'\"])|si",
bb8d0799 1652 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
b6f2416e 1653 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1654 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
691a2d25 1655 ),
1656 Array(
1657 "\\1$secremoveimg\\2",
bb8d0799 1658 "\\1$secremoveimg\\2",
1659 "\\1$secremoveimg\\2",
1660 "\\1$secremoveimg\\2"
691a2d25 1661 )
1662 ),
0a6ec9b5 1663 "/^href|action/i" =>
1664 Array(
1665 Array(
1666 "|^([\'\"])\s*\.\./.*([\'\"])|si",
1667 "/^([\'\"])\s*\S+script\s*:.*([\'\"])/si",
1668 "/^([\'\"])\s*mocha\s*:*.*([\'\"])/si",
1669 "/^([\'\"])\s*about\s*:.*([\'\"])/si"
1670 ),
1671 Array(
1672 "\\1#\\2",
1673 "\\1#\\2",
1674 "\\1#\\2",
1675 "\\1#\\2"
1676 )
1677 ),
691a2d25 1678 "/^style/si" =>
1679 Array(
1680 Array(
bb8d0799 1681 "/expression/si",
1682 "/binding/si",
1683 "/behaviou*r/si",
691a2d25 1684 "|url\(([\'\"])\s*\.\./.*([\'\"])\)|si",
0a6ec9b5 1685 "/url\(([\'\"])\s*\S+script\s*:.*([\'\"])\)/si",
1686 "/url\(([\'\"])\s*mocha\s*:.*([\'\"])\)/si",
1687 "/url\(([\'\"])\s*about\s*:.*([\'\"])\)/si"
691a2d25 1688 ),
1689 Array(
bb8d0799 1690 "idiocy",
1691 "idiocy",
1692 "idiocy",
0a6ec9b5 1693 "url(\\1#\\2)",
1694 "url(\\1#\\2)",
1695 "url(\\1#\\2)",
1696 "url(\\1#\\2)"
691a2d25 1697 )
1698 )
1699 )
1700 );
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,
1728 $id
1729 );
1730 if (preg_match("|$secremoveimg|si", $trusted)){
1731 $has_unsafe_images = true;
1732 }
1733 return $trusted;
451f74a2 1734}
a4a70693 1735
691a2d25 1736?>