Workaround a bug of php 5.2.0+etch10 which has a fallback to text/plain
[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(array($textpart), $parts);
205 }
206 }
207 }
208
209 private function splitMultipart()
210 {
211 $this->decodeContent();
212 if (is_null($this->multipart)) {
213 $this->multipart = array();
214 }
215 $boundary =& $this->boundary;
216 $parts = preg_split("/(^|\n)--" . preg_quote($boundary, '/') . "(--|\n)/", $this->body, -1, PREG_SPLIT_NO_EMPTY);
217 $signed = $this->isType('multipart', 'signed');
218 $signature = null;
219 $signed_message = null;
220 foreach ($parts as &$part) {
221 $newpart = new BananaMimePart($part);
222 if (!is_null($newpart->content_type)) {
223 if ($signed && $newpart->content_type == $this->signature['protocole']) {
224 $signature = $newpart->body;
225 } elseif ($signed) {
226 $signed_message = $part;
227 }
228 $this->multipart[] = $newpart;
229 }
230 }
231 if ($signed) {
232 $this->checkPGPSignature($signature, $signed_message);
233 }
234 $this->body = null;
235 }
236
237 public static function getMimeType($data, $is_filename = true)
238 {
239 if ($is_filename) {
240 $type = mime_content_type($data);
241 if ($type == 'text/plain') { // XXX Workaround a bug of php 5.2.0+etch10 (fallback for mime_content_type is text/plain)
242 $type = preg_replace('/;.*/', '', trim(shell_exec('file -bi ' . escapeshellarg($data))));
243 }
244 } else {
245 $arg = escapeshellarg($data);
246 $type = preg_replace('/;.*/', '', trim(shell_exec("echo $arg | file -bi -")));
247 }
248 return empty($type) ? 'application/octet-stream' : $type;
249 }
250
251 private function findUUEncoded()
252 {
253 $this->decodeContent();
254 $parts = array();
255 if (preg_match_all("/\n(begin \d+ ([^\r\n]+)\r?(?:\n(?!end)[^\n]*)*\nend)/",
256 $this->body, $matches, PREG_SET_ORDER)) {
257 foreach ($matches as &$match) {
258 $data = convert_uudecode($match[1]);
259 $mime = BananaMimePart::getMimeType($data, false);
260 if ($mime != 'application/x-empty') {
261 $this->body = trim(str_replace($match[0], '', $this->body));
262 $newpart = new BananaMimePart;
263 $newpart->makeDataPart($data, $mime, '8bit', $match[2], 'attachment');
264 $parts[] = $newpart;
265 }
266 }
267 }
268 return $parts;
269 }
270
271 static private function _decodeHeader($charset, $c, $str)
272 {
273 $s = ($c == 'Q' || $c == 'q') ? quoted_printable_decode($str) : base64_decode($str);
274 $s = @iconv($charset, 'UTF-8', $s);
275 return str_replace('_', ' ', $s);
276 }
277
278 static public function decodeHeader(&$val, $key)
279 {
280 if (preg_match('/[\x80-\xff]/', $val)) {
281 if (!is_utf8($val)) {
282 $val = utf8_encode($val);
283 }
284 } elseif (strpos($val, '=') !== false) {
285 $val = preg_replace('/(=\?.*?\?[bq]\?.*?\?=) (=\?.*?\?[bq]\?.*?\?=)/i', '\1\2', $val);
286 $val = preg_replace('/=\?(.*?)\?([bq])\?(.*?)\?=/ie', 'BananaMimePart::_decodeHeader("\1", "\2", "\3")', $val);
287 }
288 }
289
290 static public function &parseHeaders(array &$lines)
291 {
292 $headers = array();
293 while ($lines) {
294 $line = array_shift($lines);
295 if (isset($hdr) && $line && ctype_space($line{0})) {
296 $headers[$hdr] .= ' ' . trim($line);
297 } elseif (!empty($line)) {
298 if (strpos($line, ':') !== false) {
299 list($hdr, $val) = explode(":", $line, 2);
300 $hdr = strtolower($hdr);
301 if (in_array($hdr, Banana::$msgparse_headers)) {
302 $headers[$hdr] = ltrim($val);
303 } else {
304 unset($hdr);
305 }
306 }
307 } else {
308 break;
309 }
310 }
311 array_walk($headers, array('BananaMimePart', 'decodeHeader'));
312 return $headers;
313 }
314
315 static public function encodeHeader($value, $trim = 0)
316 {
317 if ($trim) {
318 if (strlen($value) > $trim) {
319 $value = substr($value, 0, $trim);
320 }
321 }
322 $value = preg_replace('/([\x80-\xff]+)/e', '"=?UTF-8?B?" . base64_encode("\1") . "?="', $value);
323 return $value;
324 }
325
326 private function decodeContent()
327 {
328 $encodings = Array('quoted-printable' => 'quoted_printable_decode',
329 'base64' => 'base64_decode',
330 'x-uuencode' => 'convert_uudecode');
331 foreach ($encodings as $encoding => $callback) {
332 if ($this->encoding == $encoding) {
333 $this->body = $callback($this->body);
334 $this->encoding = '8bit';
335 break;
336 }
337 }
338 if (!$this->isType('text')) {
339 return;
340 }
341
342 if (!is_null($this->charset)) {
343 $body = @iconv($this->charset, 'UTF-8//IGNORE', $this->body);
344 if (empty($body)) {
345 return;
346 }
347 $this->body = $body;
348 } else {
349 $this->body = utf8_encode($this->body);
350 }
351 $this->charset = 'utf-8';
352 }
353
354 public function send($force_inline = false)
355 {
356 $this->decodeContent();
357 if ($force_inline) {
358 $dispostion = $this->disposition;
359 $this->disposition = 'inline';
360 }
361 $headers = $this->getHeaders();
362 foreach ($headers as $key => $value) {
363 header("$key: $value");
364 }
365 if ($force_inline) {
366 $this->disposition = $disposition;
367 }
368 echo $this->body;
369 exit;
370 }
371
372 private function setBoundary()
373 {
374 if ($this->isType('multipart') && is_null($this->boundary)) {
375 $this->boundary = '--banana-bound-' . time() . rand(0, 255) . '-';
376 }
377 }
378
379 public function getHeaders()
380 {
381 $headers = array();
382 $this->setBoundary();
383 $headers['Content-Type'] = $this->content_type . ";"
384 . ($this->filename ? " name=\"{$this->filename}\";" : '')
385 . ($this->charset ? " charset=\"{$this->charset}\";" : '')
386 . ($this->boundary ? " boundary=\"{$this->boundary}\";" : "")
387 . ($this->format ? " format={$this->format}" : "");
388 if ($this->encoding) {
389 $headers['Content-Transfer-Encoding'] = $this->encoding;
390 }
391 if ($this->disposition) {
392 $headers['Content-Disposition'] = $this->disposition
393 . ($this->filename ? "; filename=\"{$this->filename}\"" : '');
394 }
395 return array_map(array($this, 'encodeHeader'), $headers);
396 }
397
398 public function hasBody()
399 {
400 if (is_null($this->content) && !$this->isType('multipart')) {
401 return false;
402 }
403 return true;
404 }
405
406 public function get($with_headers = false)
407 {
408 $content = "";
409 if ($with_headers) {
410 foreach ($this->getHeaders() as $key => $value) {
411 $line = "$key: $value";
412 $line = explode("\n", wordwrap($line, Banana::$msgshow_wrap));
413 for ($i = 1 ; $i < count($line) ; $i++) {
414 $line[$i] = "\t" . $line[$i];
415 }
416 $content .= implode("\n", $line) . "\n";
417 }
418 $content .= "\n";
419 }
420 if ($this->isType('multipart')) {
421 $this->setBoundary();
422 foreach ($this->multipart as &$part) {
423 $content .= "\n--{$this->boundary}\n" . $part->get(true);
424 }
425 $content .= "\n--{$this->boundary}--";
426 } elseif ($this->isType('text', 'plain')) {
427 $content .= banana_flow($this->body);
428 } else {
429 $content .= banana_wordwrap($this->body);
430 }
431 return $content;
432 }
433
434 public function getText()
435 {
436 $signed =& $this->getSignedPart();
437 if ($signed !== $this) {
438 return $signed->getText();
439 }
440 $this->decodeContent();
441 return $this->body;
442 }
443
444 public function toHtml()
445 {
446 $signed =& $this->getSignedPart();
447 if ($signed !== $this) {
448 return $signed->toHtml();
449 }
450 @list($type, $subtype) = $this->getType();
451 if ($type == 'image') {
452 $part = $this->id ? $this->id : $this->filename;
453 return '<img class="multipart" src="'
454 . banana_htmlentities(Banana::$page->makeUrl(array('group' => Banana::$group,
455 'artid' => Banana::$artid,
456 'part' => $part)))
457 . '" alt="' . banana_htmlentities($this->filename) . '" />';
458 } else if ($type == 'multipart' && $subtype == 'alternative') {
459 $types =& Banana::$msgshow_mimeparts;
460 foreach ($types as $type) {
461 @list($type, $subtype) = explode('/', $type);
462 $part = $this->getParts($type, $subtype);
463 if (count($part) > 0) {
464 return $part[0]->toHtml();
465 }
466 }
467 } elseif ((!in_array($type, Banana::$msgshow_mimeparts)
468 && !in_array($this->content_type, Banana::$msgshow_mimeparts))
469 || $this->disposition == 'attachment') {
470 $part = $this->id ? $this->id : $this->filename;
471 if (!$part) {
472 $part = $this->content_type;
473 }
474 return '[' . Banana::$page->makeImgLink(array('group' => Banana::$group,
475 'artid' => Banana::$artid,
476 'part' => $part,
477 'text' => $this->filename ? $this->filename : $this->content_type,
478 'img' => 'save')) . ']';
479 } elseif ($type == 'multipart' && ($subtype == 'mixed' || $subtype == 'report')) {
480 $text = '';
481 foreach ($this->multipart as &$part) {
482 $text .= $part->toHtml();
483 }
484 return $text;
485 } else {
486 switch ($subtype) {
487 case 'html': return banana_formatHtml($this);
488 case 'enriched': case 'richtext': return banana_formatRichText($this);
489 default:
490 if ($type == 'message') { // we have a raw source of data (no specific pre-formatting)
491 return '<hr />' . utf8_encode(banana_formatPlainText($this));
492 }
493 return banana_formatPlainText($this);
494 }
495 }
496 return null;
497 }
498
499 public function quote()
500 {
501 $signed =& $this->getSignedPart();
502 if ($signed !== $this) {
503 return $signed->quote();
504 }
505 list($type, $subtype) = $this->getType();
506 if (in_array($type, Banana::$msgedit_mimeparts) || in_array($this->content_type, Banana::$msgedit_mimeparts)) {
507 if ($type == 'multipart' && ($subtype == 'mixed' || $subtype == 'report')) {
508 $text = '';
509 foreach ($this->multipart as &$part) {
510 $qt = $part->quote();
511 $qt = rtrim($qt);
512 if (!empty($text)) {
513 $text .= "\n" . banana_quote("", 1) . "\n";
514 }
515 $text .= $qt;
516 }
517 return $text;
518 }
519 switch ($subtype) {
520 case 'html': return banana_quoteHtml($this);
521 case 'enriched': case 'richtext': return banana_quoteRichText($this);
522 default: return banana_quotePlainText($this);
523 }
524 }
525 }
526
527 protected function getType()
528 {
529 return explode('/', $this->content_type);
530 }
531
532 protected function isType($type, $subtype = null)
533 {
534 list($mytype, $mysub) = $this->getType();
535 return ($mytype == $type) && (is_null($subtype) || $mysub == $subtype);
536 }
537
538 public function isFlowed()
539 {
540 return $this->format == 'flowed';
541 }
542
543 public function getFilename()
544 {
545 return $this->filename;
546 }
547
548 protected function getParts($type, $subtype = null)
549 {
550 $parts = array();
551 if ($this->isType($type, $subtype)) {
552 return array($this);
553 } elseif ($this->isType('multipart')) {
554 foreach ($this->multipart as &$part) {
555 $parts = array_merge($parts, $part->getParts($type, $subtype));
556 }
557 }
558 return $parts;
559 }
560
561 public function getFile($filename)
562 {
563 if ($this->filename == $filename) {
564 return $this;
565 } elseif ($this->isType('multipart')) {
566 foreach ($this->multipart as &$part) {
567 $file = $part->getFile($filename);
568 if (!is_null($file)) {
569 return $file;
570 }
571 }
572 }
573 return null;
574 }
575
576 public function getAttachments()
577 {
578 if (!is_null($this->filename)) {
579 return array($this);
580 } elseif ($this->isType('multipart')) {
581 $parts = array();
582 foreach ($this->multipart as &$part) {
583 $parts = array_merge($parts, $part->getAttachments());
584 }
585 return $parts;
586 }
587 return array();
588 }
589
590 public function getAlternatives()
591 {
592 $types =& Banana::$msgshow_mimeparts;
593 $names =& Banana::$mimeparts;
594 $source = null;
595 if (in_array('source', $types)) {
596 $source = @$names['source'] ? $names['source'] : 'source';
597 }
598 if ($this->isType('multipart', 'signed')) {
599 $parts = array($this->getSignedPart());
600 } else if (!$this->isType('multipart', 'alternative') && !$this->isType('multipart', 'related')) {
601 if ($source) {
602 $parts = array($this);
603 } else {
604 return array();
605 }
606 } else {
607 $parts =& $this->multipart;
608 }
609 $alt = array();
610 foreach ($parts as &$part) {
611 list($type, $subtype) = $part->getType();
612 $ct = $type . '/' . $subtype;
613 if (in_array($ct, $types) || in_array($type, $types)) {
614 if (isset($names[$ct])) {
615 $alt[$ct] = $names[$ct];
616 } elseif (isset($names[$type])) {
617 $alt[$ct] = $names[$type];
618 } else {
619 $alt[$ct] = $ct;
620 }
621 }
622 }
623 if ($source) {
624 $alt['source'] = $source;
625 }
626 return $alt;
627 }
628
629 public function getPartById($id)
630 {
631 if ($this->id == $id) {
632 return $this;
633 } elseif ($this->isType('multipart')) {
634 foreach ($this->multipart as &$part) {
635 $res = $part->getPartById($id);
636 if (!is_null($res)) {
637 return $res;
638 }
639 }
640 }
641 return null;
642 }
643
644 protected function &getSignedPart()
645 {
646 if ($this->isType('multipart', 'signed')) {
647 foreach ($this->multipart as &$part) {
648 if ($part->content_type != $this->signature['protocole']) {
649 return $part;
650 }
651 }
652 }
653 return $this;
654 }
655
656 private function checkPGPSignature($signature, $message = null)
657 {
658 if (!Banana::$msgshow_pgpcheck) {
659 return true;
660 }
661 $signname = tempnam(Banana::$spool_root, 'banana_pgp_');
662 $gpg = 'LC_ALL="en_US" ' . Banana::$msgshow_pgppath . ' ' . Banana::$msgshow_pgpoptions . ' --verify '
663 . $signname . '.asc ';
664 file_put_contents($signname. '.asc', $signature);
665 $gpg_check = array();
666 if (!is_null($message)) {
667 file_put_contents($signname, str_replace(array("\r\n", "\n"), array("\n", "\r\n"), $message));
668 exec($gpg . $signname . ' 2>&1', $gpg_check, $result);
669 unlink($signname);
670 } else {
671 exec($gpg . '2&>1', $gpg_check, $result);
672 }
673 unlink("$signname.asc");
674 if (preg_match('/Signature made (.+) using (.+) key ID (.+)/', array_shift($gpg_check), $matches)) {
675 $this->signature['date'] = strtotime($matches[1]);
676 $this->signature['key'] = array('format' => $matches[2],
677 'id' => $matches[3]);
678 } else {
679 return false;
680 }
681 $signature = array_shift($gpg_check);
682 if (preg_match('/Good signature from "(.+)"/', $signature, $matches)) {
683 $this->signature['verify'] = true;
684 $this->signature['identity'] = array($matches[1]);
685 $this->signature['certified'] = true;
686 } elseif (preg_match('/BAD signature from "(.+)"/', $signature, $matches)) {
687 $this->signature['verify'] = false;
688 $this->signature['identity'] = array($matches[1]);
689 $this->signature['certified'] = false;
690 } else {
691 return false;
692 }
693 foreach ($gpg_check as $aka) {
694 if (preg_match('/aka "(.+)"/', $aka, $matches)) {
695 $this->signature['identity'][] = $matches[1];
696 }
697 if (preg_match('/This key is not certified with a trusted signature!/', $aka)) {
698 $this->signature['certified'] = false;
699 $this->signature['certification_error'] = _b_("identité non confirmée");
700 }
701 }
702 return true;
703 }
704
705 public function getSignature()
706 {
707 return $this->signature;
708 }
709 }
710
711 // vim:set et sw=4 sts=4 ts=4 enc=utf-8:
712 ?>