1 # Copyright (C) 2016-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # read-only utilities for Email::MIME
5 package PublicInbox::MsgIter;
9 our @EXPORT = qw(msg_iter msg_part_text);
11 # This becomes PublicInbox::MIME->each_part:
12 # Like Email::MIME::walk_parts, but this is:
14 # * passes depth and indices to the iterator callback
15 sub em_each_part ($$;$$) {
16 my ($mime, $cb, $cb_arg, $do_undef) = @_;
17 my @parts = $mime->subparts;
19 $mime = $_[0] = undef if $do_undef; # saves some memory
21 @parts = map { [ $_, 1, ++$i ] } @parts;
22 while (my $p = shift @parts) {
23 my ($part, $depth, $idx) = @$p;
24 my @sub = $part->subparts;
29 [ $_, $depth, "$idx.".(++$i) ]
31 @parts = (@sub, @parts);
37 $cb->([$mime, 0, 1], $cb_arg);
41 # Use this when we may accept Email::MIME from user scripts
42 # (not just PublicInbox::MIME)
43 sub msg_iter ($$;$$) { # $_[0] = PublicInbox::MIME/Email::MIME-like obj
44 my (undef, $cb, $cb_arg, $once) = @_;
45 if (my $ep = $_[0]->can('each_part')) { # PublicInbox::{MIME,*}
46 $ep->($_[0], $cb, $cb_arg, $once);
47 } else { # for compatibility with existing Email::MIME users:
48 em_each_part($_[0], $cb, $cb_arg, $once);
52 sub msg_part_text ($$) {
55 # TODO: we may offer a separate sub for people who need to index
56 # HTML-only mail, but the majority of HTML mail is multipart/alternative
57 # with a text part which we don't have to waste cycles decoding
58 return if $ct =~ m!\btext/x?html\b!;
60 my $s = eval { $part->body_str };
63 # text/plain is the default, multipart/mixed happened a few
64 # times when it should not have been:
65 # <87llgalspt.fsf@free.fr>
66 # <200308111450.h7BEoOu20077@mail.osdl.org>
67 # But also do not try this with ->{is_submsg} (message/rfc822),
68 # since a broken multipart/mixed inside a message/rfc822 part
69 # has not been seen in the wild, yet...
70 if ($err && ($ct =~ m!\btext/\b!i ||
71 (!$part->{is_submsg} &&
72 $ct =~ m!\bmultipart/mixed\b!i) ) ) {
73 my $cte = $part->header_raw('Content-Transfer-Encoding');
74 if (defined($cte) && $cte =~ /\b7bit\b/i) {
76 $err = undef if $s =~ /\A[[:ascii:]]+\z/s;
78 # Try to assume UTF-8 because Alpine seems to
79 # do wacky things and set charset=X-UNKNOWN
80 $part->charset_set('UTF-8');
81 $s = eval { $part->body_str };
84 # If forcing charset=UTF-8 failed,
85 # caller will warn further down...
86 $s = $part->body if $@;
91 # returns an array of quoted or unquoted sections
93 # Quiet "Complex regular subexpression recursion limit" warning
94 # in case an inconsiderate sender quotes 32K of text at once.
95 # The warning from Perl is harmless for us since our callers can
96 # tolerate less-than-ideal matches which work within Perl limits.
98 split(/((?:^>[^\n]*\n)+)/sm, shift);