577af46423d6749cce6ed3c47e7a7fb498e3a2ea
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($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];
216 private function splitMultipart()
218 $this->decodeContent();
219 if (is_null($this->multipart
)) {
220 $this->multipart
= array();
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');
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
;
233 $signed_message = $part;
235 $this->multipart
[] = $newpart;
239 $this->checkPGPSignature($signature, $signed_message);
244 public static function getMimeType($data, $is_filename = true
)
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))));
252 $arg = escapeshellarg($data);
253 $type = preg_replace('/;.*/', '', trim(shell_exec("echo $arg | file -bi -")));
255 return empty($type) ?
'application/octet-stream' : $type;
258 private function findUUEncoded()
260 $this->decodeContent();
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');
279 static private function _decodeHeader($charset, $c, $str)
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);
286 static public function decodeHeader(&$val, $key = null
)
288 if (preg_match('/[\x80-\xff]/', $val)) {
289 if (!is_utf8($val)) {
290 $val = utf8_encode($val);
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);
298 static public function &parseHeaders(array &$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);
319 array_walk($headers, array('BananaMimePart', 'decodeHeader'));
323 static public function encodeHeader($value, $trim = 0)
326 if (strlen($value) > $trim) {
327 $value = substr($value, 0, $trim);
330 $value = preg_replace('/([\x80-\xff]+)/e', '"=?UTF-8?B?" . base64_encode("\1") . "?="', $value);
334 private function decodeContent()
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';
346 if (!$this->isType('text')) {
350 if (!is_null($this->charset
)) {
351 $body = @iconv
($this->charset
, 'UTF-8//IGNORE', $this->body
);
357 $this->body
= utf8_encode($this->body
);
359 $this->charset
= 'utf-8';
362 public function send($force_inline = false
)
364 $this->decodeContent();
366 $dispostion = $this->disposition
;
367 $this->disposition
= 'inline';
369 $headers = $this->getHeaders();
370 foreach ($headers as $key => $value) {
371 header("$key: $value");
374 $this->disposition
= $disposition;
380 private function setBoundary()
382 if ($this->isType('multipart') && is_null($this->boundary
)) {
383 $this->boundary
= '--banana-bound-' . time() . rand(0, 255) . '-';
387 public function getHeaders()
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
;
399 if ($this->disposition
) {
400 $headers['Content-Disposition'] = $this->disposition
401 . ($this->filename ?
"; filename=\"{$this->filename}\"" : '');
403 return array_map(array($this, 'encodeHeader'), $headers);
406 public function hasBody()
408 if (is_null($this->content
) && !$this->isType('multipart')) {
414 public function get($with_headers = false
)
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];
424 $content .= implode("\n", $line) . "\n";
428 if ($this->isType('multipart')) {
429 $this->setBoundary();
430 foreach ($this->multipart
as &$part) {
431 $content .= "\n--{$this->boundary}\n" . $part->get(true
);
433 $content .= "\n--{$this->boundary}--";
434 } elseif ($this->isType('text', 'plain')) {
435 $content .= banana_flow($this->body
);
437 $content .= banana_wordwrap($this->body
);
442 public function getText()
444 $signed =& $this->getSignedPart();
445 if ($signed !== $this) {
446 return $signed->getText();
448 $this->decodeContent();
452 public function toHtml()
454 $signed =& $this->getSignedPart();
455 if ($signed !== $this) {
456 return $signed->toHtml();
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,
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();
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
;
480 $part = $this->content_type
;
482 return '[' . Banana
::$page->makeImgLink(array('group' => Banana
::$group,
483 'artid' => Banana
::$artid,
485 'text' => $this->filename ?
$this->filename
: $this->content_type
,
486 'img' => 'save')) . ']';
487 } elseif ($type == 'multipart' && ($subtype == 'mixed' ||
$subtype == 'report')) {
489 foreach ($this->multipart
as &$part) {
490 $text .= $part->toHtml();
495 case 'html': return banana_formatHtml($this);
496 case 'enriched': case 'richtext': return banana_formatRichText($this);
498 if ($type == 'message') { // we have a raw source of data (no specific pre-formatting)
499 return '<hr />' . utf8_encode(banana_formatPlainText($this));
501 return banana_formatPlainText($this);
507 public function quote()
509 $signed =& $this->getSignedPart();
510 if ($signed !== $this) {
511 return $signed->quote();
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')) {
517 foreach ($this->multipart
as &$part) {
518 $qt = $part->quote();
521 $text .= "\n" . banana_quote("", 1) . "\n";
528 case 'html': return banana_quoteHtml($this);
529 case 'enriched': case 'richtext': return banana_quoteRichText($this);
530 default: return banana_quotePlainText($this);
535 protected function getType()
537 return explode('/', $this->content_type
);
540 protected function isType($type, $subtype = null
)
542 list($mytype, $mysub) = $this->getType();
543 return ($mytype == $type) && (is_null($subtype) ||
$mysub == $subtype);
546 public function isFlowed()
548 return $this->format
== 'flowed';
551 public function getFilename()
553 return $this->filename
;
556 protected function getParts($type, $subtype = null
)
559 if ($this->isType($type, $subtype)) {
561 } elseif ($this->isType('multipart')) {
562 foreach ($this->multipart
as &$part) {
563 $parts = array_merge($parts, $part->getParts($type, $subtype));
569 public function getFile($filename)
571 if ($this->filename
== $filename) {
573 } elseif ($this->isType('multipart')) {
574 foreach ($this->multipart
as &$part) {
575 $file = $part->getFile($filename);
576 if (!is_null($file)) {
584 public function getAttachments()
586 if (!is_null($this->filename
)) {
588 } elseif ($this->isType('multipart')) {
590 foreach ($this->multipart
as &$part) {
591 $parts = array_merge($parts, $part->getAttachments());
598 public function getAlternatives()
600 $types =& Banana
::$msgshow_mimeparts;
601 $names =& Banana
::$mimeparts;
603 if (in_array('source', $types)) {
604 $source = @$names['source'] ?
$names['source'] : 'source';
606 if ($this->isType('multipart', 'signed')) {
607 $parts = array($this->getSignedPart());
608 } else if (!$this->isType('multipart', 'alternative') && !$this->isType('multipart', 'related')) {
610 $parts = array($this);
615 $parts =& $this->multipart
;
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];
632 $alt['source'] = $source;
637 public function getPartById($id)
639 if ($this->id
== $id) {
641 } elseif ($this->isType('multipart')) {
642 foreach ($this->multipart
as &$part) {
643 $res = $part->getPartById($id);
644 if (!is_null($res)) {
652 protected function &getSignedPart()
654 if ($this->isType('multipart', 'signed')) {
655 foreach ($this->multipart
as &$part) {
656 if ($part->content_type
!= $this->signature
['protocole']) {
664 private function checkPGPSignature($signature, $message = null
)
666 if (!Banana
::$msgshow_pgpcheck) {
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);
679 exec($gpg . '2&>1', $gpg_check, $result);
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]);
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
;
701 foreach ($gpg_check as $aka) {
702 if (preg_match('/aka "(.+)"/', $aka, $matches)) {
703 $this->signature
['identity'][] = $matches[1];
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");
713 public function getSignature()
715 return $this->signature
;
719 // vim:set et sw=4 sts=4 ts=4 enc=utf-8: