Fix parsing of messages containing UUEncoded data.
[banana.git] / banana / mimepart.inc.php
1 <?php
2 /********************************************************************************
3 * banana/mimepart.inc.php : class for MIME parts
4 * ------------------------
5 *
6 * This file is part of the banana distribution
7 * Copyright: See COPYING files that comes with this distribution
8 ********************************************************************************/
9
10 class BananaMimePart
11 {
12 public $headers = null; /* Should be protected */
13
14 private $id = null;
15 private $content_type = null;
16 private $charset = null;
17 private $encoding = null;
18 private $disposition = null;
19 private $boundary = null;
20 private $filename = null;
21 private $format = null;
22 private $signature = array();
23
24 private $body = null;
25 private $multipart = null;
26
27 protected function __construct($data = null)
28 {
29 if ($data instanceof BananaMimePart) {
30 foreach ($this as $key=>$value) {
31 $this->$key = $data->$key;
32 }
33 } elseif (!is_null($data)) {
34 $this->fromRaw($data);
35 }
36 }
37
38 protected function makeTextPart($body, $content_type, $encoding, $charset = null, $format = 'fixed')
39 {
40 $this->body = $body;
41 $this->charset = $charset;
42 $this->encoding = $encoding;
43 $this->content_type = $content_type;
44 $this->format = strtolower($format);
45 $this->parse();
46 }
47
48 protected function makeDataPart($body, $content_type, $encoding, $filename, $disposition, $id = null)
49 {
50 $this->body = $body;
51 $this->content_type = $content_type;
52 $this->encoding = $encoding;
53 $this->filename = $filename;
54 $this->disposition = $disposition;
55 $this->id = $id;
56 if (is_null($content_type) || $content_type == 'application/octet-stream') {
57 $this->decodeContent();
58 $this->content_type = BananaMimePart::getMimeType($this->body, false);
59 }
60 }
61
62 protected function makeFilePart(array $file, $content_type = null, $disposition = 'attachment')
63 {
64 $body = file_get_contents($file['tmp_name']);
65 if ($body === false || strlen($body) != $file['size']) {
66 return false;
67 }
68 if (is_null($content_type) || $content_type == 'application/octet-stream') {
69 $content_type = BananaMimePart::getMimeType($file['tmp_name']);
70 }
71 if (substr($content_type, 0, 5) == 'text/') {
72 $encoding = '8bit';
73 } else {
74 $encoding = 'base64';
75 $body = chunk_split(base64_encode($body));
76 }
77 $this->filename = $file['name'];
78 $this->content_type = $content_type;
79 $this->disposition = $disposition;
80 $this->body = $body;
81 $this->encoding = $encoding;
82 return true;
83 }
84
85 protected function makeMultiPart($body, $content_type, $encoding, $boundary, $sign_protocole)
86 {
87 $this->body = $body;
88 $this->content_type = $content_type;
89 $this->encoding = $encoding;
90 $this->boundary = $boundary;
91 $this->signature['protocole'] = $sign_protocole;
92 $this->parse();
93 }
94
95 protected function convertToMultiPart()
96 {
97 if (!$this->isType('multipart', 'mixed')) {
98 $newpart = new BananaMimePart($this);
99 $this->content_type = 'multipart/mixed';
100 $this->encoding = '8bit';
101 $this->multipart = array($newpart);
102 $this->headers = null;
103 $this->charset = null;
104 $this->disposition = null;
105 $this->filename = null;
106 $this->boundary = null;
107 $this->body = null;
108 $this->format = null;
109 $this->id = null;
110 }
111 }
112
113 public function addAttachment(array $file, $content_type = null, $disposition = 'attachment')
114 {
115 if (!is_uploaded_file($file['tmp_name'])) {
116 return false;
117 }
118 $newpart = new BananaMimePart;
119 if ($newpart->makeFilePart($file, $content_type, $disposition)) {
120 $this->convertToMultiPart();
121 $this->multipart[] = $newpart;
122 return true;
123 }
124 return false;
125 }
126
127 protected function getHeader($title, $filter = null)
128 {
129 if (!isset($this->headers[$title])) {
130 return null;
131 }
132 $header =& $this->headers[$title];
133 if (is_null($filter)) {
134 return trim($header);
135 } elseif (preg_match($filter, $header, $matches)) {
136 return trim($matches[1]);
137 }
138 return null;
139 }
140
141 protected function fromRaw($data)
142 {
143 if (is_array($data)) {
144 if (array_key_exists('From', $data)) {
145 $this->headers = array_map(array($this, 'decodeHeader'), array_change_key_case($data));
146 return;
147 } else {
148 $lines = $data;
149 }
150 } else {
151 $lines = explode("\n", $data);
152 }
153 $headers = BananaMimePart::parseHeaders($lines);
154 $this->headers =& $headers;
155 if (empty($headers) || empty($lines)) {
156 return;
157 }
158 $content = join("\n", $lines);
159 $test = trim($content);
160 if (empty($test)) {
161 return;
162 }
163
164 $content_type = strtolower($this->getHeader('content-type', '/^\s*([^ ;]+?)(;|$)/'));
165 if (empty($content_type)) {
166 $encoding = '8bit';
167 $charset = 'CP1252';
168 $content_type = 'text/plain';
169 $format = strtolower($this->getHeader('x-rfc2646', '/format="?([^ w@"]+?)"?\s*(;|$)/i'));
170 } else {
171 $encoding = strtolower($this->getHeader('content-transfer-encoding'));
172 $disposition = $this->getHeader('content-disposition', '/(inline|attachment)/i');
173 $boundary = $this->getHeader('content-type', '/boundary="?([^ "]+?)"?\s*(;|$)/i');
174 $charset = strtolower($this->getHeader('content-type', '/charset="?([^ "]+?)"?\s*(;|$)/i'));
175 $filename = $this->getHeader('content-disposition', '/filename="?([^ "]+?)"?\s*(;|$)/i');
176 $format = strtolower($this->getHeader('content-type', '/format="?([^ "]+?)"?\s*(;|$)/i'));
177 $id = $this->getHeader('content-id', '/<(.*?)>/');
178 $sign_protocole = strtolower($this->getHeader('content-type', '/protocol="?([^ "]+?)"?\s*(;|$)/i'));
179 if (empty($filename)) {
180 $filename = $this->getHeader('content-type', '/name="?([^"]+)"?/');
181 }
182 }
183 list($type, $subtype) = explode('/', $content_type);
184 switch ($type) {
185 case 'text': case 'message':
186 $this->makeTextPart($content, $content_type, $encoding, $charset, $format);
187 break;
188 case 'multipart':
189 $this->makeMultiPart($content, $content_type, $encoding, $boundary, $sign_protocole);
190 break;
191 default:
192 $this->makeDataPart($content, $content_type, $encoding, $filename, $disposition, $id);
193 }
194 }
195
196 private function parse()
197 {
198 if ($this->isType('multipart')) {
199 $this->splitMultipart();
200 } else {
201 $parts = $this->findUUEncoded();
202 if (count($parts)) {
203 $this->convertToMultiPart();
204 $this->multipart = array_merge($this->multipart, $parts);
205 // Restore "message" headers to the previous level"
206 $this->headers = array();
207 foreach (Banana::$msgshow_headers as $hdr) {
208 if (isset($this->multipart[0]->headers[$hdr])) {
209 $this->headers[$hdr] = $this->multipart[0]->headers[$hdr];
210 }
211 }
212 }
213 }
214 }
215
216 private function splitMultipart()
217 {
218 $this->decodeContent();
219 if (is_null($this->multipart)) {
220 $this->multipart = array();
221 }
222 $boundary =& $this->boundary;
223 $parts = preg_split("/(^|\n)--" . preg_quote($boundary, '/') . "(--|\n)/", $this->body, -1, PREG_SPLIT_NO_EMPTY);
224 $signed = $this->isType('multipart', 'signed');
225 $signature = null;
226 $signed_message = null;
227 foreach ($parts as &$part) {
228 $newpart = new BananaMimePart($part);
229 if (!is_null($newpart->content_type)) {
230 if ($signed && $newpart->content_type == $this->signature['protocole']) {
231 $signature = $newpart->body;
232 } elseif ($signed) {
233 $signed_message = $part;
234 }
235 $this->multipart[] = $newpart;
236 }
237 }
238 if ($signed) {
239 $this->checkPGPSignature($signature, $signed_message);
240 }
241 $this->body = null;
242 }
243
244 public static function getMimeType($data, $is_filename = true)
245 {
246 if ($is_filename) {
247 $type = mime_content_type($data);
248 if ($type == 'text/plain') { // XXX Workaround a bug of php 5.2.0+etch10 (fallback for mime_content_type is text/plain)
249 $type = preg_replace('/;.*/', '', trim(shell_exec('file -bi ' . escapeshellarg($data))));
250 }
251 } else {
252 $arg = escapeshellarg($data);
253 $type = preg_replace('/;.*/', '', trim(shell_exec("echo $arg | file -bi -")));
254 }
255 return empty($type) ? 'application/octet-stream' : $type;
256 }
257
258 private function findUUEncoded()
259 {
260 $this->decodeContent();
261 $parts = array();
262 if (preg_match_all("/\n(begin \d+ ([^\r\n]+)\r?(?:\n(?!end)[^\n]*)*\nend)/",
263 $this->body, $matches, PREG_SET_ORDER)) {
264 foreach ($matches as &$match) {
265 $data = convert_uudecode($match[1]);
266 $mime = BananaMimePart::getMimeType($data, false);
267 if ($mime != 'application/x-empty') {
268 $this->body = trim(str_replace($match[0], '', $this->body));
269 $newpart = new BananaMimePart;
270 self::decodeHeader($match[2]);
271 $newpart->makeDataPart($data, $mime, '8bit', $match[2], 'attachment');
272 $parts[] = $newpart;
273 }
274 }
275 }
276 return $parts;
277 }
278
279 static private function _decodeHeader($charset, $c, $str)
280 {
281 $s = ($c == 'Q' || $c == 'q') ? quoted_printable_decode($str) : base64_decode($str);
282 $s = @iconv($charset, 'UTF-8', $s);
283 return str_replace('_', ' ', $s);
284 }
285
286 static public function decodeHeader(&$val, $key = null)
287 {
288 if (preg_match('/[\x80-\xff]/', $val)) {
289 if (!is_utf8($val)) {
290 $val = utf8_encode($val);
291 }
292 } elseif (strpos($val, '=') !== false) {
293 $val = preg_replace('/(=\?.*?\?[bq]\?.*?\?=) (=\?.*?\?[bq]\?.*?\?=)/i', '\1\2', $val);
294 $val = preg_replace('/=\?(.*?)\?([bq])\?(.*?)\?=/ie', 'BananaMimePart::_decodeHeader("\1", "\2", "\3")', $val);
295 }
296 }
297
298 static public function &parseHeaders(array &$lines)
299 {
300 $headers = array();
301 while ($lines) {
302 $line = array_shift($lines);
303 if (isset($hdr) && $line && ctype_space($line{0})) {
304 $headers[$hdr] .= ' ' . trim($line);
305 } elseif (!empty($line)) {
306 if (strpos($line, ':') !== false) {
307 list($hdr, $val) = explode(":", $line, 2);
308 $hdr = strtolower($hdr);
309 if (in_array($hdr, Banana::$msgparse_headers)) {
310 $headers[$hdr] = ltrim($val);
311 } else {
312 unset($hdr);
313 }
314 }
315 } else {
316 break;
317 }
318 }
319 array_walk($headers, array('BananaMimePart', 'decodeHeader'));
320 return $headers;
321 }
322
323 static public function encodeHeader($value, $trim = 0)
324 {
325 if ($trim) {
326 if (strlen($value) > $trim) {
327 $value = substr($value, 0, $trim);
328 }
329 }
330 $value = preg_replace('/([\x80-\xff]+)/e', '"=?UTF-8?B?" . base64_encode("\1") . "?="', $value);
331 return $value;
332 }
333
334 private function decodeContent()
335 {
336 $encodings = Array('quoted-printable' => 'quoted_printable_decode',
337 'base64' => 'base64_decode',
338 'x-uuencode' => 'convert_uudecode');
339 foreach ($encodings as $encoding => $callback) {
340 if ($this->encoding == $encoding) {
341 $this->body = $callback($this->body);
342 $this->encoding = '8bit';
343 break;
344 }
345 }
346 if (!$this->isType('text')) {
347 return;
348 }
349
350 if (!is_null($this->charset)) {
351 $body = @iconv($this->charset, 'UTF-8//IGNORE', $this->body);
352 if (empty($body)) {
353 return;
354 }
355 $this->body = $body;
356 } else {
357 $this->body = utf8_encode($this->body);
358 }
359 $this->charset = 'utf-8';
360 }
361
362 public function send($force_inline = false)
363 {
364 $this->decodeContent();
365 if ($force_inline) {
366 $dispostion = $this->disposition;
367 $this->disposition = 'inline';
368 }
369 $headers = $this->getHeaders();
370 foreach ($headers as $key => $value) {
371 header("$key: $value");
372 }
373 if ($force_inline) {
374 $this->disposition = $disposition;
375 }
376 echo $this->body;
377 exit;
378 }
379
380 private function setBoundary()
381 {
382 if ($this->isType('multipart') && is_null($this->boundary)) {
383 $this->boundary = '--banana-bound-' . time() . rand(0, 255) . '-';
384 }
385 }
386
387 public function getHeaders()
388 {
389 $headers = array();
390 $this->setBoundary();
391 $headers['Content-Type'] = $this->content_type . ";"
392 . ($this->filename ? " name=\"{$this->filename}\";" : '')
393 . ($this->charset ? " charset=\"{$this->charset}\";" : '')
394 . ($this->boundary ? " boundary=\"{$this->boundary}\";" : "")
395 . ($this->format ? " format={$this->format}" : "");
396 if ($this->encoding) {
397 $headers['Content-Transfer-Encoding'] = $this->encoding;
398 }
399 if ($this->disposition) {
400 $headers['Content-Disposition'] = $this->disposition
401 . ($this->filename ? "; filename=\"{$this->filename}\"" : '');
402 }
403 return array_map(array($this, 'encodeHeader'), $headers);
404 }
405
406 public function hasBody()
407 {
408 if (is_null($this->content) && !$this->isType('multipart')) {
409 return false;
410 }
411 return true;
412 }
413
414 public function get($with_headers = false)
415 {
416 $content = "";
417 if ($with_headers) {
418 foreach ($this->getHeaders() as $key => $value) {
419 $line = "$key: $value";
420 $line = explode("\n", wordwrap($line, Banana::$msgshow_wrap));
421 for ($i = 1 ; $i < count($line) ; $i++) {
422 $line[$i] = "\t" . $line[$i];
423 }
424 $content .= implode("\n", $line) . "\n";
425 }
426 $content .= "\n";
427 }
428 if ($this->isType('multipart')) {
429 $this->setBoundary();
430 foreach ($this->multipart as &$part) {
431 $content .= "\n--{$this->boundary}\n" . $part->get(true);
432 }
433 $content .= "\n--{$this->boundary}--";
434 } elseif ($this->isType('text', 'plain')) {
435 $content .= banana_flow($this->body);
436 } else {
437 $content .= banana_wordwrap($this->body);
438 }
439 return $content;
440 }
441
442 public function getText()
443 {
444 $signed =& $this->getSignedPart();
445 if ($signed !== $this) {
446 return $signed->getText();
447 }
448 $this->decodeContent();
449 return $this->body;
450 }
451
452 public function toHtml()
453 {
454 $signed =& $this->getSignedPart();
455 if ($signed !== $this) {
456 return $signed->toHtml();
457 }
458 @list($type, $subtype) = $this->getType();
459 if ($type == 'image') {
460 $part = $this->id ? $this->id : $this->filename;
461 return '<img class="multipart" src="'
462 . banana_htmlentities(Banana::$page->makeUrl(array('group' => Banana::$group,
463 'artid' => Banana::$artid,
464 'part' => $part)))
465 . '" alt="' . banana_htmlentities($this->filename) . '" />';
466 } else if ($type == 'multipart' && $subtype == 'alternative') {
467 $types =& Banana::$msgshow_mimeparts;
468 foreach ($types as $type) {
469 @list($type, $subtype) = explode('/', $type);
470 $part = $this->getParts($type, $subtype);
471 if (count($part) > 0) {
472 return $part[0]->toHtml();
473 }
474 }
475 } elseif ((!in_array($type, Banana::$msgshow_mimeparts)
476 && !in_array($this->content_type, Banana::$msgshow_mimeparts))
477 || $this->disposition == 'attachment') {
478 $part = $this->id ? $this->id : $this->filename;
479 if (!$part) {
480 $part = $this->content_type;
481 }
482 return '[' . Banana::$page->makeImgLink(array('group' => Banana::$group,
483 'artid' => Banana::$artid,
484 'part' => $part,
485 'text' => $this->filename ? $this->filename : $this->content_type,
486 'img' => 'save')) . ']';
487 } elseif ($type == 'multipart' && ($subtype == 'mixed' || $subtype == 'report')) {
488 $text = '';
489 foreach ($this->multipart as &$part) {
490 $text .= $part->toHtml();
491 }
492 return $text;
493 } else {
494 switch ($subtype) {
495 case 'html': return banana_formatHtml($this);
496 case 'enriched': case 'richtext': return banana_formatRichText($this);
497 default:
498 if ($type == 'message') { // we have a raw source of data (no specific pre-formatting)
499 return '<hr />' . utf8_encode(banana_formatPlainText($this));
500 }
501 return banana_formatPlainText($this);
502 }
503 }
504 return null;
505 }
506
507 public function quote()
508 {
509 $signed =& $this->getSignedPart();
510 if ($signed !== $this) {
511 return $signed->quote();
512 }
513 list($type, $subtype) = $this->getType();
514 if (in_array($type, Banana::$msgedit_mimeparts) || in_array($this->content_type, Banana::$msgedit_mimeparts)) {
515 if ($type == 'multipart' && ($subtype == 'mixed' || $subtype == 'report')) {
516 $text = '';
517 foreach ($this->multipart as &$part) {
518 $qt = $part->quote();
519 $qt = rtrim($qt);
520 if (!empty($text)) {
521 $text .= "\n" . banana_quote("", 1) . "\n";
522 }
523 $text .= $qt;
524 }
525 return $text;
526 }
527 switch ($subtype) {
528 case 'html': return banana_quoteHtml($this);
529 case 'enriched': case 'richtext': return banana_quoteRichText($this);
530 default: return banana_quotePlainText($this);
531 }
532 }
533 }
534
535 protected function getType()
536 {
537 return explode('/', $this->content_type);
538 }
539
540 protected function isType($type, $subtype = null)
541 {
542 list($mytype, $mysub) = $this->getType();
543 return ($mytype == $type) && (is_null($subtype) || $mysub == $subtype);
544 }
545
546 public function isFlowed()
547 {
548 return $this->format == 'flowed';
549 }
550
551 public function getFilename()
552 {
553 return $this->filename;
554 }
555
556 protected function getParts($type, $subtype = null)
557 {
558 $parts = array();
559 if ($this->isType($type, $subtype)) {
560 return array($this);
561 } elseif ($this->isType('multipart')) {
562 foreach ($this->multipart as &$part) {
563 $parts = array_merge($parts, $part->getParts($type, $subtype));
564 }
565 }
566 return $parts;
567 }
568
569 public function getFile($filename)
570 {
571 if ($this->filename == $filename) {
572 return $this;
573 } elseif ($this->isType('multipart')) {
574 foreach ($this->multipart as &$part) {
575 $file = $part->getFile($filename);
576 if (!is_null($file)) {
577 return $file;
578 }
579 }
580 }
581 return null;
582 }
583
584 public function getAttachments()
585 {
586 if (!is_null($this->filename)) {
587 return array($this);
588 } elseif ($this->isType('multipart')) {
589 $parts = array();
590 foreach ($this->multipart as &$part) {
591 $parts = array_merge($parts, $part->getAttachments());
592 }
593 return $parts;
594 }
595 return array();
596 }
597
598 public function getAlternatives()
599 {
600 $types =& Banana::$msgshow_mimeparts;
601 $names =& Banana::$mimeparts;
602 $source = null;
603 if (in_array('source', $types)) {
604 $source = @$names['source'] ? $names['source'] : 'source';
605 }
606 if ($this->isType('multipart', 'signed')) {
607 $parts = array($this->getSignedPart());
608 } else if (!$this->isType('multipart', 'alternative') && !$this->isType('multipart', 'related')) {
609 if ($source) {
610 $parts = array($this);
611 } else {
612 return array();
613 }
614 } else {
615 $parts =& $this->multipart;
616 }
617 $alt = array();
618 foreach ($parts as &$part) {
619 list($type, $subtype) = $part->getType();
620 $ct = $type . '/' . $subtype;
621 if (in_array($ct, $types) || in_array($type, $types)) {
622 if (isset($names[$ct])) {
623 $alt[$ct] = $names[$ct];
624 } elseif (isset($names[$type])) {
625 $alt[$ct] = $names[$type];
626 } else {
627 $alt[$ct] = $ct;
628 }
629 }
630 }
631 if ($source) {
632 $alt['source'] = $source;
633 }
634 return $alt;
635 }
636
637 public function getPartById($id)
638 {
639 if ($this->id == $id) {
640 return $this;
641 } elseif ($this->isType('multipart')) {
642 foreach ($this->multipart as &$part) {
643 $res = $part->getPartById($id);
644 if (!is_null($res)) {
645 return $res;
646 }
647 }
648 }
649 return null;
650 }
651
652 protected function &getSignedPart()
653 {
654 if ($this->isType('multipart', 'signed')) {
655 foreach ($this->multipart as &$part) {
656 if ($part->content_type != $this->signature['protocole']) {
657 return $part;
658 }
659 }
660 }
661 return $this;
662 }
663
664 private function checkPGPSignature($signature, $message = null)
665 {
666 if (!Banana::$msgshow_pgpcheck) {
667 return true;
668 }
669 $signname = tempnam(Banana::$spool_root, 'banana_pgp_');
670 $gpg = 'LC_ALL="en_US" ' . Banana::$msgshow_pgppath . ' ' . Banana::$msgshow_pgpoptions . ' --verify '
671 . $signname . '.asc ';
672 file_put_contents($signname. '.asc', $signature);
673 $gpg_check = array();
674 if (!is_null($message)) {
675 file_put_contents($signname, str_replace(array("\r\n", "\n"), array("\n", "\r\n"), $message));
676 exec($gpg . $signname . ' 2>&1', $gpg_check, $result);
677 unlink($signname);
678 } else {
679 exec($gpg . '2&>1', $gpg_check, $result);
680 }
681 unlink("$signname.asc");
682 if (preg_match('/Signature made (.+) using (.+) key ID (.+)/', array_shift($gpg_check), $matches)) {
683 $this->signature['date'] = strtotime($matches[1]);
684 $this->signature['key'] = array('format' => $matches[2],
685 'id' => $matches[3]);
686 } else {
687 return false;
688 }
689 $signature = array_shift($gpg_check);
690 if (preg_match('/Good signature from "(.+)"/', $signature, $matches)) {
691 $this->signature['verify'] = true;
692 $this->signature['identity'] = array($matches[1]);
693 $this->signature['certified'] = true;
694 } elseif (preg_match('/BAD signature from "(.+)"/', $signature, $matches)) {
695 $this->signature['verify'] = false;
696 $this->signature['identity'] = array($matches[1]);
697 $this->signature['certified'] = false;
698 } else {
699 return false;
700 }
701 foreach ($gpg_check as $aka) {
702 if (preg_match('/aka "(.+)"/', $aka, $matches)) {
703 $this->signature['identity'][] = $matches[1];
704 }
705 if (preg_match('/This key is not certified with a trusted signature!/', $aka)) {
706 $this->signature['certified'] = false;
707 $this->signature['certification_error'] = _b_("identité non confirmée");
708 }
709 }
710 return true;
711 }
712
713 public function getSignature()
714 {
715 return $this->signature;
716 }
717 }
718
719 // vim:set et sw=4 sts=4 ts=4 enc=utf-8:
720 ?>