/
IMAPClient.pm
3448 lines (2820 loc) · 98.8 KB
/
IMAPClient.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# _{name} methods are undocumented and meant to be private.
require 5.008_001;
use strict;
use warnings;
package Mail::IMAPClient;
our $VERSION = '3.36_03';
use Mail::IMAPClient::MessageSet;
use IO::Socket qw(:crlf SOL_SOCKET SO_KEEPALIVE);
use IO::Select ();
use Carp qw(carp); #local $SIG{__WARN__} = \&Carp::cluck; #DEBUG
use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);
use Errno qw(EAGAIN EBADF ECONNRESET EPIPE);
use List::Util qw(first min max sum);
use MIME::Base64 qw(encode_base64 decode_base64);
use File::Spec ();
use constant APPEND_BUFFER_SIZE => 1024 * 1024;
use constant {
Unconnected => 0,
Connected => 1, # connected; not logged in
Authenticated => 2, # logged in; no mailbox selected
Selected => 3, # mailbox selected
};
use constant {
INDEX => 0, # Array index for output line number
TYPE => 1, # Array index for line type (OUTPUT, INPUT, or LITERAL)
DATA => 2, # Array index for output line data
};
my %SEARCH_KEYS = map { ( $_ => 1 ) } qw(
ALL ANSWERED BCC BEFORE BODY CC DELETED DRAFT FLAGGED
FROM HEADER KEYWORD LARGER NEW NOT OLD ON OR RECENT
SEEN SENTBEFORE SENTON SENTSINCE SINCE SMALLER SUBJECT
TEXT TO UID UNANSWERED UNDELETED UNDRAFT UNFLAGGED
UNKEYWORD UNSEEN);
# modules require(d) during runtime when applicable
my %Load_Module = (
"Compress-Zlib" => "Compress::Zlib",
"INET" => "IO::Socket::INET",
"SSL" => "IO::Socket::SSL",
"UNIX" => "IO::Socket::UNIX",
"BodyStructure" => "Mail::IMAPClient::BodyStructure",
"Envelope" => "Mail::IMAPClient::BodyStructure::Envelope",
"Thread" => "Mail::IMAPClient::Thread",
);
sub _load_module {
my $self = shift;
my $modkey = shift;
my $module = $Load_Module{$modkey} || $modkey;
my $err = do {
local ($@);
eval "require $module";
$@;
};
if ($err) {
$self->LastError("Unable to load '$module': $err");
return undef;
}
return $module;
}
sub _debug {
my $self = shift;
return unless $self->Debug;
my $text = join '', @_;
$text =~ s/$CRLF/\n /og;
$text =~ s/\s*$/\n/;
#use POSIX (); $text = POSIX::strftime("%F %T ", localtime).$text; #DEBUG
my $fh = $self->{Debug_fh} || \*STDERR;
print $fh $text;
}
BEGIN {
# set-up accessors
foreach my $datum (
qw(Authcallback Authmechanism Authuser Buffer Count Compress
Debug Debug_fh Domain Folder Ignoresizeerrors Keepalive
Maxappendstringlength Maxcommandlength Maxtemperrors
Password Peek Port Prewritemethod Proxy Ranges Readmethod
Readmoremethod Reconnectretry Server Showcredentials
Socketargs Ssl Starttls Supportedflags Timeout Uid User)
)
{
no strict 'refs';
*$datum = sub {
@_ > 1 ? ( $_[0]->{$datum} = $_[1] ) : $_[0]->{$datum};
};
}
}
sub LastError {
my $self = shift;
@_ or return $self->{LastError};
my $err = shift;
# allow LastError to be reset with undef
if ( defined $err ) {
$err =~ s/$CRLF$//og;
local ($!); # old versions of Carp could reset $!
$self->_debug( Carp::longmess("ERROR: $err") );
# hopefully this is rare...
if ( $err eq "NO not connected" ) {
my $lerr = $self->{LastError} || "";
my $emsg = "Trying command when NOT connected!";
$emsg .= " LastError was: $lerr" if $lerr;
Carp::cluck($emsg);
}
}
# 2.x API support requires setting $@
$@ = $self->{LastError} = $err;
}
sub Fast_io(;$) {
my ( $self, $use ) = @_;
defined $use
or return $self->{Fast_io};
my $socket = $self->{Socket}
or return undef;
local ( $@, $! ); # avoid stomping on globals
unless ($use) {
eval { fcntl( $socket, F_SETFL, delete $self->{_fcntl} ) }
if exists $self->{_fcntl};
$self->{Fast_io} = 0;
return undef;
}
my $fcntl = eval { fcntl( $socket, F_GETFL, 0 ) };
if ($@) {
$self->{Fast_io} = 0;
$self->_debug("not using Fast_IO; not available on this platform")
unless $self->{_fastio_warning_}++;
return undef;
}
$self->{Fast_io} = 1;
my $newflags = $self->{_fcntl} = $fcntl;
$newflags |= O_NONBLOCK;
fcntl( $socket, F_SETFL, $newflags );
}
# removed
sub EnableServerResponseInLiteral { undef }
sub Wrap { shift->Clear(@_) }
# The following class method is for creating valid dates in appended msgs:
my @dow = qw(Sun Mon Tue Wed Thu Fri Sat);
my @mnt = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
sub Rfc822_date {
my $class = shift;
my $date = $class =~ /^\d+$/ ? $class : shift; # method or function?
my @date = gmtime($date);
#Date: Fri, 09 Jul 1999 13:10:55 -0000
sprintf(
"%s, %02d %s %04d %02d:%02d:%02d -%04d",
$dow[ $date[6] ],
$date[3],
$mnt[ $date[4] ],
$date[5] + 1900,
$date[2], $date[1], $date[0], $date[8]
);
}
# The following methods create valid dates for use in IMAP search strings
# - provide Rfc2060* methods/functions for backwards compatibility
sub Rfc2060_date {
$_[0] =~ /^\d+$/ ? Rfc3501_date(@_) : shift->Rfc3501_date(@_);
}
sub Rfc3501_date {
my $class = shift;
my $stamp = $class =~ /^\d+$/ ? $class : shift;
my @date = gmtime($stamp);
# 11-Jan-2000
sprintf( "%02d-%s-%04d", $date[3], $mnt[ $date[4] ], $date[5] + 1900 );
}
sub Rfc2060_datetime($;$) {
$_[0] =~ /^\d+$/ ? Rfc3501_datetime(@_) : shift->Rfc3501_datetime(@_);
}
sub Rfc3501_datetime($;$) {
my $class = shift;
my $stamp = $class =~ /^\d+$/ ? $class : shift;
my $zone = shift || '+0000';
my @date = gmtime($stamp);
# 11-Jan-2000 04:04:04 +0000
sprintf(
"%02d-%s-%04d %02d:%02d:%02d %s",
$date[3],
$mnt[ $date[4] ],
$date[5] + 1900,
$date[2], $date[1], $date[0], $zone
);
}
# Change CRLF into \n
sub Strip_cr {
my $class = shift;
if ( !ref $_[0] && @_ == 1 ) {
( my $string = $_[0] ) =~ s/$CRLF/\n/og;
return $string;
}
return wantarray
? map { s/$CRLF/\n/og; $_ } ( ref $_[0] ? @{ $_[0] } : @_ )
: [ map { s/$CRLF/\n/og; $_ } ( ref $_[0] ? @{ $_[0] } : @_ ) ];
}
# The following defines a special method to deal with the Clear parameter:
sub Clear {
my ( $self, $clear ) = @_;
defined $clear or return $self->{Clear};
my $oldclear = $self->{Clear};
$self->{Clear} = $clear;
my @keys = reverse $self->_trans_index;
for ( my $i = $clear ; $i < @keys ; $i++ ) {
delete $self->{History}{ $keys[$i] };
}
return $oldclear;
}
# read-only access to the transaction number
sub Transaction { shift->Count }
# remove doubles from list
sub _remove_doubles(@) {
my %seen;
grep { !$seen{ $_->{name} }++ } @_;
}
# the constructor:
sub new {
my $class = shift;
my $self = {
LastError => "",
Uid => 1,
Count => 0,
Clear => 2,
Keepalive => 0,
Maxappendstringlength => 1024**2,
Maxcommandlength => 1000,
Maxtemperrors => undef,
State => Unconnected,
Authmechanism => 'LOGIN',
Timeout => 600,
History => {},
};
while (@_) {
my $k = ucfirst lc shift;
my $v = shift;
$self->{$k} = $v if defined $v;
}
bless $self, ref($class) || $class;
# Fast_io is enabled by default when not given a socket
unless ( exists $self->{Fast_io} || $self->{Socket} || $self->{Rawsocket} )
{
$self->{Fast_io} = 1;
}
if ( my $sup = $self->{Supportedflags} ) { # unpack into case-less HASH
my %sup = map { m/^\\?(\S+)/ ? lc $1 : () } @$sup;
$self->{Supportedflags} = \%sup;
}
$self->{Debug_fh} ||= \*STDERR;
CORE::select( ( select( $self->{Debug_fh} ), $|++ )[0] );
if ( $self->Debug ) {
$self->_debug( "Started at " . localtime() );
$self->_debug("Using Mail::IMAPClient version $VERSION on perl $]");
}
# BUG? return undef on Socket() failure?
$self->Socket( $self->{Socket} )
if $self->{Socket};
if ( $self->{Rawsocket} ) {
my $sock = delete $self->{Rawsocket};
# Ignore Rawsocket if Socket is set. BUG? should we carp/croak?
$self->RawSocket($sock) unless $self->{Socket};
}
if ( !$self->{Socket} && $self->{Server} ) {
$self->connect or return undef;
}
return $self;
}
sub connect(@) {
my $self = shift;
# BUG? We should restrict which keys can be passed/set here.
%$self = ( %$self, @_ ) if @_;
my @sockargs = $self->Timeout ? ( Timeout => $self->Timeout ) : ();
push( @sockargs, $self->Debug ? ( Debug => $self->Debug ) : () );
# give caller control of IO::Socket::... args to new if desired
if ( $self->Socketargs and ref $self->Socketargs eq "ARRAY" ) {
push( @sockargs, @{ $self->Socketargs } );
}
my $server = $self->Server;
my $port = $self->Port || $self->Port( $self->Ssl ? "993" : "143" );
my ( $ioclass, $sock );
if ( File::Spec->file_name_is_absolute($server) ) {
$ioclass = $self->_load_module("UNIX");
unshift( @sockargs, Peer => $server );
}
else {
unshift(
@sockargs,
PeerAddr => $server,
PeerPort => $port,
Proto => "tcp",
);
# extra control of SSL args is supported
if ( $self->Ssl ) {
$ioclass = $self->_load_module("SSL");
push( @sockargs, @{ $self->Ssl } ) if ref $self->Ssl eq "ARRAY";
}
else {
$ioclass = $self->_load_module("INET");
}
}
if ($ioclass) {
$self->_debug("Connecting with $ioclass @sockargs");
$sock = $ioclass->new(@sockargs);
}
if ($sock) {
$self->_debug( "Connected to $server" . ( $! ? " errno($!)" : "" ) );
return $self->Socket($sock);
}
else {
my $lasterr = $self->LastError || "";
$self->LastError("Unable to connect to $server: $lasterr");
return undef;
}
}
sub RawSocket(;$) {
my ( $self, $sock ) = @_;
defined $sock
or return $self->{Socket};
$self->{Socket} = $sock;
$self->{_select} = IO::Select->new($sock);
delete $self->{_fcntl};
$self->Fast_io( $self->Fast_io );
return $sock;
}
sub Socket($) {
my ( $self, $sock ) = @_;
defined $sock
or return $self->{Socket};
$self->RawSocket($sock);
$self->State(Connected);
setsockopt( $sock, SOL_SOCKET, SO_KEEPALIVE, 1 ) if $self->Keepalive;
# LastError may be set by _read_line via _get_response
# look for "* (OK|BAD|NO|PREAUTH)"
my $code = $self->_get_response( '*', 'PREAUTH' ) or return undef;
if ( $code eq 'BYE' || $code eq 'NO' ) {
$self->State(Unconnected);
return undef;
}
elsif ( $code eq 'PREAUTH' ) {
$self->State(Authenticated);
return $self;
}
if ( $self->Starttls ) {
$self->starttls or return undef;
}
if ( defined $self->User && defined $self->Password ) {
$self->login or return undef;
}
return $self->{Socket};
}
# RFC2595 section 3.1
sub starttls {
my ($self) = @_;
# BUG? RFC requirement checks commented out for now...
#if ( $self->IsUnconnected or $self->IsAuthenticated ) {
# $self->LastError("NO must be connected but not authenticated");
# return undef;
#}
# BUG? strict check on capability commented out for now...
#return undef unless $self->has_capability("STARTTLS");
$self->_imap_command("STARTTLS") or return undef;
# MUST discard cached capability info; should re-issue capability command
delete $self->{CAPABILITY};
my $ioclass = $self->_load_module("SSL") or return undef;
my $sock = $self->RawSocket;
my $blocking = $sock->blocking;
# BUG: force blocking for now
$sock->blocking(1);
# give caller control of args to start_SSL if desired
my @sslargs =
( $self->Starttls and ref( $self->Starttls ) eq "ARRAY" )
? ( @{ $self->Starttls } )
: ( Timeout => 30 );
unless ( $ioclass->start_SSL( $sock, @sslargs ) ) {
$self->LastError( "Unable to start TLS: " . $ioclass->errstr );
return undef;
}
# return blocking to previous setting
$sock->blocking($blocking);
return $self;
}
# RFC4978 COMPRESS
sub compress {
my ($self) = @_;
# BUG? strict check on capability commented out for now...
#my $can = $self->has_capability("COMPRESS")
#return undef unless $can and $can eq "DEFLATE";
$self->_imap_command("COMPRESS DEFLATE") or return undef;
my $zcl = $self->_load_module("Compress-Zlib") or return undef;
# give caller control of args if desired
$self->Compress(
[
-WindowBits => -$zcl->MAX_WBITS(),
-Level => $zcl->Z_BEST_SPEED()
]
) unless ( $self->Compress and ref( $self->Compress ) eq "ARRAY" );
my ( $rc, $do, $io );
( $do, $rc ) = Compress::Zlib::deflateInit( @{ $self->Compress } );
unless ( $rc == $zcl->Z_OK ) {
$self->LastError("deflateInit failed (rc=$rc)");
return undef;
}
( $io, $rc ) =
Compress::Zlib::inflateInit( -WindowBits => -$zcl->MAX_WBITS() );
unless ( $rc == $zcl->Z_OK ) {
$self->LastError("inflateInit failed (rc=$rc)");
return undef;
}
$self->{Prewritemethod} = sub {
my ( $imap, $string ) = @_;
my ( $rc, $out1, $out2 );
( $out1, $rc ) = $do->deflate($string);
( $out2, $rc ) = $do->flush( $zcl->Z_PARTIAL_FLUSH() )
unless ( $rc != $zcl->Z_OK );
unless ( $rc == $zcl->Z_OK ) {
$self->LastError("deflate/flush failed (rc=$rc)");
return undef;
}
return $out1 . $out2;
};
# need to retain some state for Readmoremethod/Readmethod calls
my ( $Zbuf, $Ibuf ) = ( "", "" );
$self->{Readmoremethod} = sub {
my $self = shift;
return 1 if ( length($Zbuf) || length($Ibuf) );
$self->__read_more(@_);
};
$self->{Readmethod} = sub {
my ( $imap, $fh, $buf, $len, $off ) = @_;
# get more data, but empty $Ibuf first if any data is left
my ( $lz, $li ) = ( length $Zbuf, length $Ibuf );
if ( $lz || !$li ) {
my $ret = sysread( $fh, $Zbuf, $len, length $Zbuf );
$lz = length $Zbuf;
return $ret if ( !$ret && !$lz ); # $ret is undef or 0
}
# accumulate inflated data in $Ibuf
if ($lz) {
my ( $tbuf, $rc ) = $io->inflate( \$Zbuf );
unless ( $rc == $zcl->Z_OK ) {
$self->LastError("inflate failed (rc=$rc)");
return undef;
}
$Ibuf .= $tbuf;
}
# pull desired length of data from $Ibuf
my $tbuf = substr( $Ibuf, 0, $len );
substr( $Ibuf, 0, $len ) = "";
substr( $$buf, $off ) = $tbuf;
return length $tbuf;
};
return $self;
}
sub login {
my $self = shift;
my $auth = $self->Authmechanism;
if ( $auth && $auth ne 'LOGIN' ) {
$self->authenticate( $auth, $self->Authcallback )
or return undef;
}
else {
my $user = $self->User;
my $passwd = $self->Password;
return undef unless ( defined($passwd) and defined($user) );
$user = ( $user eq "" ) ? qq("") : $self->Quote($user);
$passwd = ( $passwd eq "" ) ? qq("") : $self->Quote($passwd);
$self->_imap_command("LOGIN $user $passwd")
or return undef;
}
$self->State(Authenticated);
if ( $self->Compress ) {
$self->compress or return undef;
}
return $self;
}
sub noop {
my ($self) = @_;
$self->_imap_command("NOOP") ? $self->Results : undef;
}
sub proxyauth {
my ( $self, $user ) = @_;
$user = ( $user eq "" ) ? qq("") : $self->Quote($user);
$self->_imap_command("PROXYAUTH $user") ? $self->Results : undef;
}
sub separator {
my ( $self, $target ) = @_;
unless ( defined $target ) {
# separator is namespace's 1st thing's 1st thing's 2nd thing:
my $ns = $self->namespace or return undef;
if ($ns) {
my $sep = $ns->[0][0][1];
return $sep if $sep;
}
$target = '';
}
return $self->{separators}{$target}
if exists $self->{separators}{$target};
my $list = $self->list( undef, $target ) or return undef;
foreach my $line (@$list) {
my $rec = $self->_list_or_lsub_response_parse($line);
next unless defined $rec->{name};
$self->{separators}{ $rec->{name} } = $rec->{delim};
}
return $self->{separators}{$target};
}
# BUG? caller gets empty list even if Error
# - returning an array with a single undef value seems even worse though
sub sort {
my ( $self, $crit, @a ) = @_;
$crit =~ /^\(.*\)$/ # wrap criteria in parens
or $crit = "($crit)";
my @hits;
if ( $self->_imap_uid_command( SORT => $crit, @a ) ) {
my @results = $self->History;
foreach (@results) {
chomp;
s/$CR$//;
s/^\*\s+SORT\s+// or next;
push @hits, grep /\d/, split;
}
}
return wantarray ? @hits : \@hits;
}
sub _list_or_lsub {
my ( $self, $cmd, $reference, $target ) = @_;
defined $reference or $reference = '';
defined $target or $target = '*';
length $target or $target = '""';
$target eq '*' || $target eq '""'
or $target = $self->Quote($target);
$self->_imap_command(qq($cmd "$reference" $target))
or return undef;
return wantarray ? $self->Escaped_history : $self->Escaped_results;
}
sub list { shift->_list_or_lsub( "LIST", @_ ) }
sub lsub { shift->_list_or_lsub( "LSUB", @_ ) }
# deprecated 3.34
sub xlist {
my ($self) = @_;
return undef unless $self->has_capability("XLIST");
shift->_list_or_lsub( "XLIST", @_ );
}
sub _folders_or_subscribed {
my ( $self, $method, $what ) = @_;
my @folders;
# do BLOCK allowing use of "last if undef/error" and avoiding dup code
do {
{
my @list;
if ($what) {
my $sep = $self->separator($what) || $self->separator(undef);
last unless defined $sep;
my $whatsub = $what =~ m/\Q${sep}\E$/ ? "$what*" : "$what$sep*";
my $tref = $self->$method( undef, $whatsub ) or last;
shift @$tref; # remove command
push @list, @$tref;
# BUG?: this behavior has been around since 2.x, why?
my $cansel = $self->selectable($what);
last unless defined $cansel;
if ($cansel) {
$tref = $self->$method( undef, $what ) or last;
shift @$tref; # remove command
push @list, @$tref;
}
}
else {
my $tref = $self->$method( undef, undef ) or last;
shift @$tref; # remove command
push @list, @$tref;
}
foreach my $resp (@list) {
my $rec = $self->_list_or_lsub_response_parse($resp);
next unless defined $rec->{name};
push @folders, $rec;
}
}
};
my @clean = _remove_doubles @folders;
return wantarray ? @clean : \@clean;
}
sub folders {
my ( $self, $what ) = @_;
my @folders =
map( $_->{name}, $self->_folders_or_subscribed( "list", $what ) );
return wantarray ? @folders : \@folders;
}
sub folders_hash {
my ( $self, $what ) = @_;
my @folders_hash = $self->_folders_or_subscribed( "list", $what );
return wantarray ? @folders_hash : \@folders_hash;
}
# deprecated 3.34
sub xlist_folders {
my ($self) = @_;
my $xlist = $self->xlist;
return undef unless defined $xlist;
my %xlist;
my $xlist_re = qr/\A\\(Inbox|AllMail|Trash|Drafts|Sent|Spam|Starred)\Z/;
for my $resp (@$xlist) {
my $rec = $self->_list_or_lsub_response_parse($resp);
next unless defined $rec->{name};
for my $attr ( @{ $rec->{attrs} } ) {
$xlist{$1} = $rec->{name} if ( $attr =~ $xlist_re );
}
}
return wantarray ? %xlist : \%xlist;
}
sub subscribed {
my ( $self, $what ) = @_;
my @folders =
map( $_->{name}, $self->_folders_or_subscribed( "lsub", $what ) );
return wantarray ? @folders : \@folders;
}
sub deleteacl {
my ( $self, $target, $user ) = @_;
$target = $self->Quote($target);
$user = ( $user eq "" ) ? qq("") : $self->Quote($user);
$self->_imap_command(qq(DELETEACL $target $user))
or return undef;
return wantarray ? $self->History : $self->Results;
}
sub setacl {
my ( $self, $target, $user, $acl ) = @_;
$target ||= $self->Folder;
$target = $self->Quote($target);
$user ||= $self->User;
$user = ( $user eq "" ) ? qq("") : $self->Quote($user);
$acl = ( $acl eq "" ) ? qq("") : $self->Quote($acl);
$self->_imap_command(qq(SETACL $target $user $acl))
or return undef;
return wantarray ? $self->History : $self->Results;
}
sub getacl {
my ( $self, $target ) = @_;
defined $target or $target = $self->Folder;
my $mtarget = $self->Quote($target);
$self->_imap_command(qq(GETACL $mtarget))
or return undef;
my @history = $self->History;
my $hash;
for ( my $x = 0 ; $x < @history ; $x++ ) {
next if $history[$x] !~ /^\* ACL/;
my $perm =
$history[$x] =~ /^\* ACL $/
? $history[ ++$x ] . $history[ ++$x ]
: $history[$x];
$perm =~ s/\s?$CRLF$//o;
until ( $perm =~ /\Q$target\E"?$/ || !$perm ) {
$perm =~ s/\s([^\s]+)\s?$// or last;
my $p = $1;
$perm =~ s/\s([^\s]+)\s?$// or last;
my $u = $1;
$hash->{$u} = $p;
$self->_debug("Permissions: $u => $p");
}
}
return $hash;
}
sub listrights {
my ( $self, $target, $user ) = @_;
$target ||= $self->Folder;
$target = $self->Quote($target);
$user ||= $self->User;
$user = ( $user eq "" ) ? qq("") : $self->Quote($user);
$self->_imap_command(qq(LISTRIGHTS $target $user))
or return undef;
my $resp = first { /^\* LISTRIGHTS/ } $self->History;
my @rights = split /\s/, $resp;
my $rights = join '', @rights[ 4 .. $#rights ];
$rights =~ s/"//g;
return wantarray ? split( //, $rights ) : $rights;
}
sub select {
my ( $self, $target ) = @_;
defined $target or return undef;
my $qqtarget = $self->Quote($target);
my $old = $self->Folder;
$self->_imap_command("SELECT $qqtarget")
or return undef;
$self->State(Selected);
$self->Folder($target);
return $old || $self; # ??$self??
}
sub message_string {
my ( $self, $msg ) = @_;
return undef unless defined $self->imap4rev1;
my $peek = $self->Peek ? '.PEEK' : '';
my $cmd = $self->imap4rev1 ? "BODY$peek\[]" : "RFC822$peek";
my $string;
$self->message_to_file( \$string, $msg );
unless ( $self->Ignoresizeerrors ) { # Check size with expected size
my $expected_size = $self->size($msg);
return undef unless defined $expected_size;
# RFC822.SIZE may be wrong, see RFC2683 3.4.5 "RFC822.SIZE"
if ( length($string) != $expected_size ) {
$self->LastError( "message_string() "
. "expected $expected_size bytes but received "
. length($string)
. " you may need the IgnoreSizeErrors option" );
return undef;
}
}
return $string;
}
sub bodypart_string {
my ( $self, $msg, $partno, $bytes, $offset ) = @_;
unless ( $self->imap4rev1 ) {
$self->LastError( "Unable to get body part; server "
. $self->Server
. " does not support IMAP4REV1" )
unless $self->LastError;
return undef;
}
$offset ||= 0;
my $cmd = "BODY"
. ( $self->Peek ? '.PEEK' : '' )
. "[$partno]"
. ( $bytes ? "<$offset.$bytes>" : '' );
$self->fetch( $msg, $cmd )
or return undef;
$self->_transaction_literals;
}
# message_to_file( $self, $file, @msgs )
sub message_to_file {
my ( $self, $file, @msgs ) = @_;
# $file can be a name or a scalar reference (for in memory file)
# avoid IO::File bug handling scalar refs in perl <= 5.8.8?
# - buggy: $fh = IO::File->new( $file, 'r' )
my $fh;
if ( ref $file and ref $file ne "SCALAR" ) {
$fh = $file;
}
else {
$$file = "" if ( ref $file eq "SCALAR" and !defined $$file );
local ($!);
open( $fh, ">>", $file );
unless ( defined($fh) ) {
$self->LastError("Unable to open file '$file': $!");
return undef;
}
}
binmode($fh);
unless (@msgs) {
$self->LastError("message_to_file: NO messages specified!");
return undef;
}
my $peek = $self->Peek ? '.PEEK' : '';
$peek = sprintf( $self->imap4rev1 ? "BODY%s\[]" : "RFC822%s", $peek );
my @args = ( join( ",", @msgs ), $peek );
return $self->_imap_uid_command( { outref => $fh }, "FETCH" => @args )
? $self
: undef;
}
sub message_uid {
my ( $self, $msg ) = @_;
my $ref = $self->fetch( $msg, "UID" ) or return undef;
foreach (@$ref) {
return $1 if m/\(UID\s+(\d+)\s*\)$CR?$/o;
}
return undef;
}
# cleaned up and simplified but see TODO in code...
sub migrate {
my ( $self, $peer, $msgs, $folder ) = @_;
unless ( $peer and $peer->IsConnected ) {
$self->LastError( ( $peer ? "Invalid" : "Unconnected" )
. " target "
. ref($self)
. " object in migrate()"
. ( $peer ? ( ": " . $peer->LastError ) : "" ) );
return undef;
}
# sanity check to see if $self is same object as $peer
if ( $self eq $peer ) {
$self->LastError("dest must not be the same object as self");
return undef;
}
$folder = $self->Folder unless ( defined $folder );
unless ($folder) {
$self->LastError("No folder selected on source mailbox.");
return undef;
}
unless ( $peer->exists($folder) or $peer->create($folder) ) {
$self->LastError( "Create folder '$folder' on target host failed: "
. $peer->LastError );
return undef;
}
if ( !defined $msgs or uc($msgs) eq "ALL" ) {
$msgs = $self->search("ALL") or return undef;
}
# message size and (internal) date
my @headers = qw(RFC822.SIZE INTERNALDATE FLAGS);
my $range = $self->Range($msgs);
$self->_debug("Messages to migrate from '$folder': $range");
foreach my $mid ( $range->unfold ) {
# fetch size internaldate and flags of original message
# - TODO: add flags here...
my $minfo = $self->fetch_hash( $mid, @headers )
or return undef;
my ( $size, $date ) = @{ $minfo->{$mid} }{@headers};
return undef unless ( defined $size and defined $date );
$self->_debug("Copy message $mid (sz=$size,dt=$date) from '$folder'");
my @flags = grep !/\\Recent/i, $self->flags($mid);
my $flags = join ' ', $peer->supported_flags(@flags);
# TODO: - use File::Temp tempfile if $msg > bufferSize?
# read message to $msg
my $msg;