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 protected 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);
159 $test = trim($content);
164 $content_type = strtolower($this->getHeader('content-type', '/^\s*([^ ;]+?)(;|$)/'));
165 if (empty($content_type)) {
168 $content_type = 'text/plain';
169 $format = strtolower($this->getHeader('x-rfc2646', '/format="?([^ w@"]+?)"?\s*(;|$)/i'));
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="?([^"]+)"?/');
183 list($type, $subtype) = explode('/', $content_type);
185 case 'text': case 'message':
186 $this->makeTextPart($content, $content_type, $encoding, $charset, $format);
189 $this->makeMultiPart($content, $content_type, $encoding, $boundary, $sign_protocole);
192 $this->makeDataPart($content, $content_type, $encoding, $filename, $disposition, $id);
196 private function parse()
198 if ($this->isType('multipart')) {
199 $this->splitMultipart();
201 $parts = $this->findUUEncoded();
203 $this->convertToMultiPart();
204 $this->multipart
= array_merge(array($textpart), $parts);
209 private function splitMultipart()
211 $this->decodeContent();
212 if (is_null($this->multipart
)) {
213 $this->multipart
= array();
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');
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
;
226 $signed_message = $part;
228 $this->multipart
[] = $newpart;
232 $this->checkPGPSignature($signature, $signed_message);
237 public static function getMimeType($data, $is_filename = true
)
240 $type = mime_content_type($data);
242 $arg = escapeshellarg($data);
243 $type = preg_replace('/;.*/', '', trim(shell_exec("echo $arg | file -bi -")));
245 return empty($type) ?
'application/octet-stream' : $type;
248 private function findUUEncoded()
250 $this->decodeContent();
252 if (preg_match_all("/\n(begin \d+ ([^\r\n]+)\r?(?:\n(?!end)[^\n]*)*\nend)/",
253 $this->body
, $matches, PREG_SET_ORDER
)) {
254 foreach ($matches as &$match) {
255 $data = convert_uudecode($match[1]);
256 $mime = BananaMimePart
::getMimeType($data, false
);
257 if ($mime != 'application/x-empty') {
258 $this->body
= trim(str_replace($match[0], '', $this->body
));
259 $newpart = new BananaMimePart
;
260 $newpart->makeDataPart($data, $mime, '8bit', $match[2], 'attachment');
268 static private function _decodeHeader($charset, $c, $str)
270 $s = ($c == 'Q' ||
$c == 'q') ?
quoted_printable_decode($str) : base64_decode($str);
271 $s = @iconv
($charset, 'UTF-8', $s);
272 return str_replace('_', ' ', $s);
275 static public function decodeHeader(&$val, $key)
277 if (preg_match('/[\x80-\xff]/', $val)) {
278 if (!is_utf8($val)) {
279 $val = utf8_encode($val);
281 } elseif (strpos($val, '=') !== false
) {
282 $val = preg_replace('/(=\?.*?\?[bq]\?.*?\?=) (=\?.*?\?[bq]\?.*?\?=)/i', '\1\2', $val);
283 $val = preg_replace('/=\?(.*?)\?([bq])\?(.*?)\?=/ie', 'BananaMimePart::_decodeHeader("\1", "\2", "\3")', $val);
287 static public function &parseHeaders(array &$lines)
291 $line = array_shift($lines);
292 if (isset($hdr) && $line && ctype_space($line{0})) {
293 $headers[$hdr] .= ' ' . trim($line);
294 } elseif (!empty($line)) {
295 if (strpos($line, ':') !== false
) {
296 list($hdr, $val) = explode(":", $line, 2);
297 $hdr = strtolower($hdr);
298 if (in_array($hdr, Banana
::$msgparse_headers)) {
299 $headers[$hdr] = ltrim($val);
308 array_walk($headers, array('BananaMimePart', 'decodeHeader'));
312 static public function encodeHeader($value, $trim = 0)
315 if (strlen($value) > $trim) {
316 $value = substr($value, 0, $trim);
319 $value = preg_replace('/([\x80-\xff]+)/e', '"=?UTF-8?B?" . base64_encode("\1") . "?="', $value);
323 private function decodeContent()
325 $encodings = Array('quoted-printable' => 'quoted_printable_decode',
326 'base64' => 'base64_decode',
327 'x-uuencode' => 'convert_uudecode');
328 foreach ($encodings as $encoding => $callback) {
329 if ($this->encoding
== $encoding) {
330 $this->body
= $callback($this->body
);
331 $this->encoding
= '8bit';
335 if (!$this->isType('text')) {
339 if (!is_null($this->charset
)) {
340 $body = iconv($this->charset
, 'UTF-8//IGNORE', $this->body
);
346 $this->body
= utf8_encode($this->body
);
348 $this->charset
= 'utf-8';
351 public function send($force_inline = false
)
353 $this->decodeContent();
355 $dispostion = $this->disposition
;
356 $this->disposition
= 'inline';
358 $headers = $this->getHeaders();
359 foreach ($headers as $key => $value) {
360 header("$key: $value");
363 $this->disposition
= $disposition;
369 private function setBoundary()
371 if ($this->isType('multipart') && is_null($this->boundary
)) {
372 $this->boundary
= '--banana-bound-' . time() . rand(0, 255) . '-';
376 public function getHeaders()
379 $this->setBoundary();
380 $headers['Content-Type'] = $this->content_type
. ";"
381 . ($this->filename ?
" name=\"{$this->filename}\";" : '')
382 . ($this->charset ?
" charset=\"{$this->charset}\";" : '')
383 . ($this->boundary ?
" boundary=\"{$this->boundary}\";" : "")
384 . ($this->format ?
" format={$this->format}" : "");
385 if ($this->encoding
) {
386 $headers['Content-Transfer-Encoding'] = $this->encoding
;
388 if ($this->disposition
) {
389 $headers['Content-Disposition'] = $this->disposition
390 . ($this->filename ?
"; filename=\"{$this->filename}\"" : '');
392 return array_map(array($this, 'encodeHeader'), $headers);
395 public function hasBody()
397 if (is_null($this->content
) && !$this->isType('multipart')) {
403 public function get($with_headers = false
)
407 foreach ($this->getHeaders() as $key => $value) {
408 $line = "$key: $value";
409 $line = explode("\n", wordwrap($line, Banana
::$msgshow_wrap));
410 for ($i = 1 ; $i < count($line) ; $i++
) {
411 $line[$i] = "\t" . $line[$i];
413 $content .= implode("\n", $line) . "\n";
417 if ($this->isType('multipart')) {
418 $this->setBoundary();
419 foreach ($this->multipart
as &$part) {
420 $content .= "\n--{$this->boundary}\n" . $part->get(true
);
422 $content .= "\n--{$this->boundary}--";
423 } elseif ($this->isType('text', 'plain')) {
424 $content .= banana_flow($this->body
);
426 $content .= banana_wordwrap($this->body
);
431 public function getText()
433 $signed =& $this->getSignedPart();
434 if ($signed !== $this) {
435 return $signed->getText();
437 $this->decodeContent();
441 public function toHtml()
443 $signed =& $this->getSignedPart();
444 if ($signed !== $this) {
445 return $signed->toHtml();
447 @list
($type, $subtype) = $this->getType();
448 if ($type == 'image') {
449 $part = $this->id ?
$this->id
: $this->filename
;
450 return '<img class="multipart" src="'
451 . banana_htmlentities(Banana
::$page->makeUrl(array('group' => Banana
::$group,
452 'artid' => Banana
::$artid,
454 . '" alt="' . banana_htmlentities($this->filename
) . '" />';
455 } else if ($type == 'multipart' && $subtype == 'alternative') {
456 $types =& Banana
::$msgshow_mimeparts;
457 foreach ($types as $type) {
458 @list
($type, $subtype) = explode('/', $type);
459 $part = $this->getParts($type, $subtype);
460 if (count($part) > 0) {
461 return $part[0]->toHtml();
464 } elseif ((!in_array($type, Banana
::$msgshow_mimeparts)
465 && !in_array($this->content_type
, Banana
::$msgshow_mimeparts))
466 ||
$this->disposition
== 'attachment') {
467 $part = $this->id ?
$this->id
: $this->filename
;
469 $part = $this->content_type
;
471 return '[' . Banana
::$page->makeImgLink(array('group' => Banana
::$group,
472 'artid' => Banana
::$artid,
474 'text' => $this->filename ?
$this->filename
: $this->content_type
,
475 'img' => 'save')) . ']';
476 } elseif ($type == 'multipart' && ($subtype == 'mixed' ||
$subtype == 'report')) {
478 foreach ($this->multipart
as &$part) {
479 $text .= $part->toHtml();
484 case 'html': return banana_formatHtml($this);
485 case 'enriched': case 'richtext': return banana_formatRichText($this);
487 if ($type == 'message') { // we have a raw source of data (no specific pre-formatting)
488 return '<hr />' . utf8_encode(banana_formatPlainText($this));
490 return banana_formatPlainText($this);
496 public function quote()
498 $signed =& $this->getSignedPart();
499 if ($signed !== $this) {
500 return $signed->quote();
502 list($type, $subtype) = $this->getType();
503 if (in_array($type, Banana
::$msgedit_mimeparts) ||
in_array($this->content_type
, Banana
::$msgedit_mimeparts)) {
504 if ($type == 'multipart' && ($subtype == 'mixed' ||
$subtype == 'report')) {
506 foreach ($this->multipart
as &$part) {
507 $qt = $part->quote();
510 $text .= "\n" . banana_quote("", 1) . "\n";
517 case 'html': return banana_quoteHtml($this);
518 case 'enriched': case 'richtext': return banana_quoteRichText($this);
519 default: return banana_quotePlainText($this);
524 protected function getType()
526 return explode('/', $this->content_type
);
529 protected function isType($type, $subtype = null
)
531 list($mytype, $mysub) = $this->getType();
532 return ($mytype == $type) && (is_null($subtype) ||
$mysub == $subtype);
535 public function isFlowed()
537 return $this->format
== 'flowed';
540 public function getFilename()
542 return $this->filename
;
545 protected function getParts($type, $subtype = null
)
548 if ($this->isType($type, $subtype)) {
550 } elseif ($this->isType('multipart')) {
551 foreach ($this->multipart
as &$part) {
552 $parts = array_merge($parts, $part->getParts($type, $subtype));
558 public function getFile($filename)
560 if ($this->filename
== $filename) {
562 } elseif ($this->isType('multipart')) {
563 foreach ($this->multipart
as &$part) {
564 $file = $part->getFile($filename);
565 if (!is_null($file)) {
573 public function getAttachments()
575 if (!is_null($this->filename
)) {
577 } elseif ($this->isType('multipart')) {
579 foreach ($this->multipart
as &$part) {
580 $parts = array_merge($parts, $part->getAttachments());
587 public function getAlternatives()
589 $types =& Banana
::$msgshow_mimeparts;
590 $names =& Banana
::$mimeparts;
592 if (in_array('source', $types)) {
593 $source = @$names['source'] ?
$names['source'] : 'source';
595 if ($this->isType('multipart', 'signed')) {
596 $parts = array($this->getSignedPart());
597 } else if (!$this->isType('multipart', 'alternative') && !$this->isType('multipart', 'related')) {
599 $parts = array($this);
604 $parts =& $this->multipart
;
607 foreach ($parts as &$part) {
608 list($type, $subtype) = $part->getType();
609 $ct = $type . '/' . $subtype;
610 if (in_array($ct, $types) ||
in_array($type, $types)) {
611 if (isset($names[$ct])) {
612 $alt[$ct] = $names[$ct];
613 } elseif (isset($names[$type])) {
614 $alt[$ct] = $names[$type];
621 $alt['source'] = $source;
626 public function getPartById($id)
628 if ($this->id
== $id) {
630 } elseif ($this->isType('multipart')) {
631 foreach ($this->multipart
as &$part) {
632 $res = $part->getPartById($id);
633 if (!is_null($res)) {
641 protected function &getSignedPart()
643 if ($this->isType('multipart', 'signed')) {
644 foreach ($this->multipart
as &$part) {
645 if ($part->content_type
!= $this->signature
['protocole']) {
653 private function checkPGPSignature($signature, $message = null
)
655 if (!Banana
::$msgshow_pgpcheck) {
658 $signname = tempnam(Banana
::$spool_root, 'banana_pgp_');
659 $gpg = 'LC_ALL="en_US" ' . Banana
::$msgshow_pgppath . ' ' . Banana
::$msgshow_pgpoptions . ' --verify '
660 . $signname . '.asc ';
661 file_put_contents($signname. '.asc', $signature);
662 $gpg_check = array();
663 if (!is_null($message)) {
664 file_put_contents($signname, str_replace(array("\r\n", "\n"), array("\n", "\r\n"), $message));
665 exec($gpg . $signname . ' 2>&1', $gpg_check, $result);
668 exec($gpg . '2&>1', $gpg_check, $result);
670 unlink("$signname.asc");
671 if (preg_match('/Signature made (.+) using (.+) key ID (.+)/', array_shift($gpg_check), $matches)) {
672 $this->signature
['date'] = strtotime($matches[1]);
673 $this->signature
['key'] = array('format' => $matches[2],
674 'id' => $matches[3]);
678 $signature = array_shift($gpg_check);
679 if (preg_match('/Good signature from "(.+)"/', $signature, $matches)) {
680 $this->signature
['verify'] = true
;
681 $this->signature
['identity'] = array($matches[1]);
682 $this->signature
['certified'] = true
;
683 } elseif (preg_match('/BAD signature from "(.+)"/', $signature, $matches)) {
684 $this->signature
['verify'] = false
;
685 $this->signature
['identity'] = array($matches[1]);
686 $this->signature
['certified'] = false
;
690 foreach ($gpg_check as $aka) {
691 if (preg_match('/aka "(.+)"/', $aka, $matches)) {
692 $this->signature
['identity'][] = $matches[1];
694 if (preg_match('/This key is not certified with a trusted signature!/', $aka)) {
695 $this->signature
['certified'] = false
;
696 $this->signature
['certification_error'] = _b_("identité non confirmée");
702 public function getSignature()
704 return $this->signature
;
708 // vim:set et sw=4 sts=4 ts=4 enc=utf-8: