c29221e3eb4123c031f6fe1140b70be31d2358c3
2 /********************************************************************************
3 * banana/mimepart.inc.php : class for MIME parts
4 * ------------------------
6 * This file is part of the banana distribution
7 * Copyright: See COPYING files that comes with this distribution
8 ********************************************************************************/
12 public $headers = null
; /* Should be protected */
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();
25 private $multipart = null
;
27 protected function __construct($data = null
)
29 if ($data instanceof BananaMimePart
) {
30 foreach ($this as $key=>$value) {
31 $this->$key = $data->$key;
33 } elseif (!is_null($data)) {
34 $this->fromRaw($data);
38 protected function makeTextPart($body, $content_type, $encoding, $charset = null
, $format = 'fixed')
41 $this->charset
= $charset;
42 $this->encoding
= $encoding;
43 $this->content_type
= $content_type;
44 $this->format
= strtolower($format);
48 protected function makeDataPart($body, $content_type, $encoding, $filename, $disposition, $id = null
)
51 $this->content_type
= $content_type;
52 $this->encoding
= $encoding;
53 $this->filename
= $filename;
54 $this->disposition
= $disposition;
56 if (is_null($content_type) ||
$content_type == 'application/octet-stream') {
57 $this->decodeContent();
58 $this->content_type
= BananaMimePart
::getMimeType($this->body
, false
);
62 protected function makeFilePart(array $file, $content_type = null
, $disposition = 'attachment')
64 $body = file_get_contents($file['tmp_name']);
65 if ($body === false ||
strlen($body) != $file['size']) {
68 if (is_null($content_type) ||
$content_type == 'application/octet-stream') {
69 $content_type = BananaMimePart
::getMimeType($file['tmp_name']);
71 if (substr($content_type, 0, 5) == 'text/') {
75 $body = chunk_split(base64_encode($body));
77 $this->filename
= $file['name'];
78 $this->content_type
= $content_type;
79 $this->disposition
= $disposition;
81 $this->encoding
= $encoding;
85 protected function makeMultiPart($body, $content_type, $encoding, $boundary, $sign_protocole)
88 $this->content_type
= $content_type;
89 $this->encoding
= $encoding;
90 $this->boundary
= $boundary;
91 $this->signature
['protocole'] = $sign_protocole;
95 protected function convertToMultiPart()
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
;
108 $this->format
= null
;
113 public function addAttachment(array $file, $content_type = null
, $disposition = 'attachment')
115 if (!is_uploaded_file($file['tmp_name'])) {
118 $newpart = new BananaMimePart
;
119 if ($newpart->makeFilePart($file, $content_type, $disposition)) {
120 $this->convertToMultiPart();
121 $this->multipart
[] = $newpart;
127 public function getHeader($title, $filter = null
)
129 if (!isset($this->headers
[$title])) {
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]);
141 protected function fromRaw($data)
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));
151 $lines = explode("\n", $data);
153 $headers = BananaMimePart
::parseHeaders($lines);
154 $this->headers
=& $headers;
155 if (empty($headers) ||
empty($lines)) {
158 $content = join("\n", $lines);
160 $test = trim($content);
166 $content_type = strtolower($this->getHeader('content-type', '/^\s*([^ ;]+?)(;|$)/'));
167 if (empty($content_type)) {
170 $content_type = 'text/plain';
171 $format = strtolower($this->getHeader('x-rfc2646', '/format="?([^ w@"]+?)"?\s*(;|$)/i'));
173 $encoding = strtolower($this->getHeader('content-transfer-encoding'));
174 $disposition = $this->getHeader('content-disposition', '/(inline|attachment)/i');
175 $boundary = $this->getHeader('content-type', '/boundary="?([^ "]+?)"?\s*(;|$)/i');
176 $charset = strtolower($this->getHeader('content-type', '/charset="?([^ "]+?)"?\s*(;|$)/i'));
177 $filename = $this->getHeader('content-disposition', '/filename="?([^ "]+?)"?\s*(;|$)/i');
178 $format = strtolower($this->getHeader('content-type', '/format="?([^ "]+?)"?\s*(;|$)/i'));
179 $id = $this->getHeader('content-id', '/<(.*?)>/');
180 $sign_protocole = strtolower($this->getHeader('content-type', '/protocol="?([^ "]+?)"?\s*(;|$)/i'));
181 if (empty($filename)) {
182 $filename = $this->getHeader('content-type', '/name="?([^"]+)"?/');
185 list($type, $subtype) = explode('/', $content_type);
186 if ($disposition == 'attachment') {
187 $this->makeDataPart($content, $content_type, $encoding, $filename, $disposition, $id);
191 case 'text': case 'message':
192 $this->makeTextPart($content, $content_type, $encoding, $charset, $format);
195 $this->makeMultiPart($content, $content_type, $encoding, $boundary, $sign_protocole);
198 $this->makeDataPart($content, $content_type, $encoding, $filename, $disposition, $id);
202 private function parse()
204 if ($this->isType('multipart')) {
205 $this->splitMultipart();
207 $parts = $this->findUUEncoded();
209 $this->convertToMultiPart();
210 $this->multipart
= array_merge($this->multipart
, $parts);
211 // Restore "message" headers to the previous level"
212 $this->headers
= array();
213 foreach (Banana
::$msgshow_headers as $hdr) {
214 if (isset($this->multipart
[0]->headers
[$hdr])) {
215 $this->headers
[$hdr] = $this->multipart
[0]->headers
[$hdr];
222 private function splitMultipart()
224 $this->decodeContent();
225 if (is_null($this->multipart
)) {
226 $this->multipart
= array();
228 $boundary =& $this->boundary
;
229 $parts = preg_split("/(^|\n)--" . preg_quote($boundary, '/') . "(--|\n)/", $this->body
, -1, PREG_SPLIT_NO_EMPTY
);
230 $signed = $this->isType('multipart', 'signed');
232 $signed_message = null
;
233 foreach ($parts as &$part) {
234 $newpart = new BananaMimePart($part);
235 if (!is_null($newpart->content_type
)) {
236 if ($signed && $newpart->content_type
== $this->signature
['protocole']) {
237 $signature = $newpart->body
;
239 $signed_message = $part;
241 $this->multipart
[] = $newpart;
245 $this->checkPGPSignature($signature, $signed_message);
250 public static function getMimeType($data, $is_filename = true
)
253 $type = mime_content_type($data);
254 if ($type == 'text/plain') { // XXX Workaround a bug of php 5.2.0+etch10 (fallback for mime_content_type is text/plain)
255 $type = preg_replace('/;.*/', '', trim(shell_exec('file -bi ' . escapeshellarg($data))));
258 $arg = escapeshellarg($data);
259 $type = preg_replace('/;.*/', '', trim(shell_exec("echo $arg | file -bi -")));
261 return empty($type) ?
'application/octet-stream' : $type;
264 private function findUUEncoded()
266 $this->decodeContent();
268 if (preg_match_all("/\n(begin \d+ ([^\r\n]+)\r?(?:\n(?!end)[^\n]*)*\nend)/",
269 $this->body
, $matches, PREG_SET_ORDER
)) {
270 foreach ($matches as &$match) {
271 $data = convert_uudecode($match[1]);
272 $mime = BananaMimePart
::getMimeType($data, false
);
273 if ($mime != 'application/x-empty') {
274 $this->body
= trim(str_replace($match[0], '', $this->body
));
275 $newpart = new BananaMimePart
;
276 self
::decodeHeader($match[2]);
277 $newpart->makeDataPart($data, $mime, '8bit', $match[2], 'attachment');
285 static private function _decodeHeader($charset, $c, $str)
287 $s = ($c == 'Q' ||
$c == 'q') ?
quoted_printable_decode($str) : base64_decode($str);
288 $s = @iconv
($charset, 'UTF-8', $s);
289 return str_replace('_', ' ', $s);
292 static public function decodeHeader(&$val, $key = null
)
294 if (preg_match('/[\x80-\xff]/', $val)) {
295 if (!is_utf8($val)) {
296 $val = utf8_encode($val);
298 } elseif (strpos($val, '=') !== false
) {
299 $val = preg_replace('/(=\?.*?\?[bq]\?.*?\?=) (=\?.*?\?[bq]\?.*?\?=)/i', '\1\2', $val);
300 $val = preg_replace('/=\?(.*?)\?([bq])\?(.*?)\?=/ie', 'BananaMimePart::_decodeHeader("\1", "\2", "\3")', $val);
304 static public function &parseHeaders(array &$lines)
308 $line = array_shift($lines);
309 if (isset($hdr) && $line && ctype_space($line{0})) {
310 $headers[$hdr] .= ' ' . trim($line);
311 } elseif (!empty($line)) {
312 if (strpos($line, ':') !== false
) {
313 list($hdr, $val) = explode(":", $line, 2);
314 $hdr = strtolower($hdr);
315 if (in_array($hdr, Banana
::$msgparse_headers)) {
316 $headers[$hdr] = ltrim($val);
325 array_walk($headers, array('BananaMimePart', 'decodeHeader'));
329 static public function encodeHeader($value, $trim = 0)
332 if (strlen($value) > $trim) {
333 $value = substr($value, 0, $trim);
336 $value = preg_replace('/([\x80-\xff]+)/e', '"=?UTF-8?B?" . base64_encode("\1") . "?="', $value);
340 private function decodeContent()
342 $encodings = Array('quoted-printable' => 'quoted_printable_decode',
343 'base64' => 'base64_decode',
344 'x-uuencode' => 'convert_uudecode');
345 foreach ($encodings as $encoding => $callback) {
346 if ($this->encoding
== $encoding) {
347 $this->body
= $callback($this->body
);
348 $this->encoding
= '8bit';
352 if (!$this->isType('text')) {
356 if (!is_null($this->charset
)) {
357 $body = @iconv
($this->charset
, 'UTF-8//IGNORE', $this->body
);
363 $this->body
= utf8_encode($this->body
);
365 $this->charset
= 'utf-8';
368 public function send($force_inline = false
)
370 $this->decodeContent();
372 $dispostion = $this->disposition
;
373 $this->disposition
= 'inline';
375 $headers = $this->getHeaders();
376 foreach ($headers as $key => $value) {
377 header("$key: $value");
380 $this->disposition
= $disposition;
386 private function setBoundary()
388 if ($this->isType('multipart') && is_null($this->boundary
)) {
389 $this->boundary
= '--banana-bound-' . time() . rand(0, 255) . '-';
393 public function getHeaders()
396 $this->setBoundary();
397 $headers['Content-Type'] = $this->content_type
. ";"
398 . ($this->filename ?
" name=\"{$this->filename}\";" : '')
399 . ($this->charset ?
" charset=\"{$this->charset}\";" : '')
400 . ($this->boundary ?
" boundary=\"{$this->boundary}\";" : "")
401 . ($this->format ?
" format={$this->format}" : "");
402 if ($this->encoding
) {
403 $headers['Content-Transfer-Encoding'] = $this->encoding
;
405 if ($this->disposition
) {
406 $headers['Content-Disposition'] = $this->disposition
407 . ($this->filename ?
"; filename=\"{$this->filename}\"" : '');
409 return array_map(array($this, 'encodeHeader'), $headers);
412 public function hasBody()
414 if (is_null($this->content
) && !$this->isType('multipart')) {
420 public function get($with_headers = false
)
424 foreach ($this->getHeaders() as $key => $value) {
425 $line = "$key: $value";
426 $line = explode("\n", wordwrap($line, Banana
::$msgshow_wrap));
427 for ($i = 1 ; $i < count($line) ; $i++
) {
428 $line[$i] = "\t" . $line[$i];
430 $content .= implode("\n", $line) . "\n";
434 if ($this->isType('multipart')) {
435 $this->setBoundary();
436 foreach ($this->multipart
as &$part) {
437 $content .= "\n--{$this->boundary}\n" . $part->get(true
);
439 $content .= "\n--{$this->boundary}--";
440 } elseif ($this->isType('text', 'plain')) {
441 $content .= banana_flow($this->body
);
443 $content .= banana_wordwrap($this->body
);
448 public function getText()
450 $signed =& $this->getSignedPart();
451 if ($signed !== $this) {
452 return $signed->getText();
454 $this->decodeContent();
458 public function toHtml()
460 $signed =& $this->getSignedPart();
461 if ($signed !== $this) {
462 return $signed->toHtml();
464 @list
($type, $subtype) = $this->getType();
465 if ($type == 'image') {
466 $part = $this->id ?
$this->id
: $this->filename
;
467 return '<img class="multipart" src="'
468 . banana_htmlentities(Banana
::$page->makeUrl(array('group' => Banana
::$group,
469 'artid' => Banana
::$artid,
471 . '" alt="' . banana_htmlentities($this->filename
) . '" />';
472 } else if ($type == 'multipart' && $subtype == 'alternative') {
473 $types =& Banana
::$msgshow_mimeparts;
474 foreach ($types as $type) {
475 @list
($type, $subtype) = explode('/', $type);
476 $part = $this->getParts($type, $subtype);
477 if (count($part) > 0) {
478 return $part[0]->toHtml();
481 } elseif ((!in_array($type, Banana
::$msgshow_mimeparts)
482 && !in_array($this->content_type
, Banana
::$msgshow_mimeparts))
483 ||
$this->disposition
== 'attachment') {
484 $part = $this->id ?
$this->id
: $this->filename
;
486 $part = $this->content_type
;
488 return '<span>[' . Banana
::$page->makeImgLink(array('group' => Banana
::$group,
489 'artid' => Banana
::$artid,
491 'text' => $this->filename ?
$this->filename
: $this->content_type
,
492 'img' => 'save')) . ']</span>';
493 } elseif ($type == 'multipart' && ($subtype == 'mixed' ||
$subtype == 'report')) {
495 foreach ($this->multipart
as &$part) {
496 $text .= $part->toHtml();
501 case 'html': return banana_formatHtml($this);
502 case 'enriched': case 'richtext': return banana_formatRichText($this);
504 if ($type == 'message') { // we have a raw source of data (no specific pre-formatting)
505 return '<hr />' . utf8_encode(banana_formatPlainText($this));
507 return banana_formatPlainText($this);
513 public function quote()
515 $signed =& $this->getSignedPart();
516 if ($signed !== $this) {
517 return $signed->quote();
519 list($type, $subtype) = $this->getType();
520 if (in_array($type, Banana
::$msgedit_mimeparts) ||
in_array($this->content_type
, Banana
::$msgedit_mimeparts)) {
521 if ($type == 'multipart' && ($subtype == 'mixed' ||
$subtype == 'report')) {
523 foreach ($this->multipart
as &$part) {
524 $qt = $part->quote();
527 $text .= "\n" . banana_quote("", 1) . "\n";
534 case 'html': return banana_quoteHtml($this);
535 case 'enriched': case 'richtext': return banana_quoteRichText($this);
536 default: return banana_quotePlainText($this);
541 protected function getType()
543 return explode('/', $this->content_type
);
546 protected function isType($type, $subtype = null
)
548 list($mytype, $mysub) = $this->getType();
549 return ($mytype == $type) && (is_null($subtype) ||
$mysub == $subtype);
552 public function isFlowed()
554 return $this->format
== 'flowed';
557 public function getFilename()
559 return $this->filename
;
562 protected function getParts($type, $subtype = null
)
565 if ($this->isType($type, $subtype)) {
567 } elseif ($this->isType('multipart')) {
568 foreach ($this->multipart
as &$part) {
569 $parts = array_merge($parts, $part->getParts($type, $subtype));
575 public function getFile($filename)
577 if ($this->filename
== $filename) {
579 } elseif ($this->isType('multipart')) {
580 foreach ($this->multipart
as &$part) {
581 $file = $part->getFile($filename);
582 if (!is_null($file)) {
590 public function getAttachments()
592 if (!is_null($this->filename
)) {
594 } elseif ($this->isType('multipart')) {
596 foreach ($this->multipart
as &$part) {
597 $parts = array_merge($parts, $part->getAttachments());
604 public function getAlternatives()
606 $types =& Banana
::$msgshow_mimeparts;
607 $names =& Banana
::$mimeparts;
609 if (in_array('source', $types)) {
610 $source = @$names['source'] ?
$names['source'] : 'source';
612 if ($this->isType('multipart', 'signed')) {
613 $parts = array($this->getSignedPart());
614 } else if (!$this->isType('multipart', 'alternative') && !$this->isType('multipart', 'related')) {
616 $parts = array($this);
621 $parts =& $this->multipart
;
624 foreach ($parts as &$part) {
625 list($type, $subtype) = $part->getType();
626 $ct = $type . '/' . $subtype;
627 if (in_array($ct, $types) ||
in_array($type, $types)) {
628 if (isset($names[$ct])) {
629 $alt[$ct] = $names[$ct];
630 } elseif (isset($names[$type])) {
631 $alt[$ct] = $names[$type];
638 $alt['source'] = $source;
643 public function getPartById($id)
645 if ($this->id
== $id) {
647 } elseif ($this->isType('multipart')) {
648 foreach ($this->multipart
as &$part) {
649 $res = $part->getPartById($id);
650 if (!is_null($res)) {
658 protected function &getSignedPart()
660 if ($this->isType('multipart', 'signed')) {
661 foreach ($this->multipart
as &$part) {
662 if ($part->content_type
!= $this->signature
['protocole']) {
670 private function checkPGPSignature($signature, $message = null
)
672 if (!Banana
::$msgshow_pgpcheck) {
675 $signname = tempnam(Banana
::$spool_root, 'banana_pgp_');
676 $gpg = 'LC_ALL="en_US" ' . Banana
::$msgshow_pgppath . ' ' . Banana
::$msgshow_pgpoptions . ' --verify '
677 . $signname . '.asc ';
678 file_put_contents($signname. '.asc', $signature);
679 $gpg_check = array();
680 if (!is_null($message)) {
681 file_put_contents($signname, str_replace(array("\r\n", "\n"), array("\n", "\r\n"), $message));
682 exec($gpg . $signname . ' 2>&1', $gpg_check, $result);
685 exec($gpg . '2&>1', $gpg_check, $result);
687 unlink("$signname.asc");
688 if (preg_match('/Signature made (.+) using (.+) key ID (.+)/', array_shift($gpg_check), $matches)) {
689 $this->signature
['date'] = strtotime($matches[1]);
690 $this->signature
['key'] = array('format' => $matches[2],
691 'id' => $matches[3]);
695 $signature = array_shift($gpg_check);
696 if (preg_match('/Good signature from "(.+)"/', $signature, $matches)) {
697 $this->signature
['verify'] = true
;
698 $this->signature
['identity'] = array($matches[1]);
699 $this->signature
['certified'] = true
;
700 } elseif (preg_match('/BAD signature from "(.+)"/', $signature, $matches)) {
701 $this->signature
['verify'] = false
;
702 $this->signature
['identity'] = array($matches[1]);
703 $this->signature
['certified'] = false
;
707 foreach ($gpg_check as $aka) {
708 if (preg_match('/aka "(.+)"/', $aka, $matches)) {
709 $this->signature
['identity'][] = $matches[1];
711 if (preg_match('/This key is not certified with a trusted signature!/', $aka)) {
712 $this->signature
['certified'] = false
;
713 $this->signature
['certification_error'] = _b_("identité non confirmée");
719 public function getSignature()
721 return $this->signature
;
725 // vim:set et sw=4 sts=4 ts=4 enc=utf-8: