blib/lib/Mail/IMAPTalk.pm untested

filter: Statementstmt 0.0% 0 / 1391 Branchbran 0.0% 0 / 656 Conditioncond 0.0% 0 / 505 Subroutinesub 0.0% 0 / 140 Podpod 0.0% 0 / 120 totaltotal 0.0% 0 / 2812 CC 329 SCAR 55.8
CC
329
Cov
0%
_parse_response
1722.0
_send_data
702.0
_next_atom
462.0
CRAP 265.5
1 package Mail::IMAPTalk;
2 $Mail::IMAPTalk::VERSION = '4.04';
3 =head1 NAME
4  
5 Mail::IMAPTalk - IMAP client interface with lots of features
6  
7 =head1 SYNOPSIS
8  
9 use Mail::IMAPTalk;
10  
11 $IMAP = Mail::IMAPTalk->new(
12 Server => $IMAPServer,
13 Username => 'foo',
14 Password => 'bar',
15 ) || die "Failed to connect/login to IMAP server";
16  
17 # Append message to folder
18 open(my $F, 'rfc822msg.txt');
19 $IMAP->append($FolderName, $F) || die $@;
20 close($F);
21  
22 # Select folder and get first unseen message
23 $IMAP->select($FolderName) || die $@;
24 $MsgId = $IMAP->search('not', 'seen')->[0];
25  
26 # Get message envelope and print some details
27 $MsgEV = $IMAP->fetch($MsgId, 'envelope')->{$MsgId}->{envelope};
28 print "From: " . $MsgEv->{From};
29 print "To: " . $MsgEv->{To};
30 print "Subject: " . $MsgEv->{Subject};
31  
32 # Get message body structure
33 $MsgBS = $IMAP->fetch($MsgId, 'bodystructure')->{$MsgId}->{bodystructure};
34  
35 # Find imap part number of text part of message
36 $MsgTxtHash = Mail::IMAPTalk::find_message($MsgBS);
37 $MsgPart = $MsgTxtHash->{text}->{'IMAP-Partnum'};
38  
39 # Retrieve message text body
40 $MsgTxt = $IMAP->fetch($MsgId, "body[$MsgPart]")->{$MsgId}->{body};
41  
42 $IMAP->logout();
43  
44 =head1 DESCRIPTION
45  
46 This module communicates with an IMAP server. Each IMAP server command
47 is mapped to a method of this object.
48  
49 Although other IMAP modules exist on CPAN, this has several advantages
50 over other modules.
51  
52 =over 4
53  
54 =item *
55  
56 It parses the more complex IMAP structures like envelopes and body
57 structures into nice Perl data structures.
58  
59 =item *
60  
61 It correctly supports atoms, quoted strings and literals at any
62 point. Some parsers in other modules aren't fully IMAP compatiable
63 and may break at odd times with certain messages on some servers.
64  
65 =item *
66  
67 It allows large return values (eg. attachments on a message)
68 to be read directly into a file, rather than into memory.
69  
70 =item *
71  
72 It includes some helper functions to find the actual text/plain
73 or text/html part of a message out of a complex MIME structure.
74 It also can find a list of attachements, and CID links for HTML
75 messages with attached images.
76  
77 =item *
78  
79 It supports decoding of MIME headers to Perl utf-8 strings automatically,
80 so you don't have to deal with MIME encoded headers (enabled optionally).
81  
82 =back
83  
84 While the IMAP protocol does allow for asynchronous running of commands, this
85 module is designed to be used in a synchronous manner. That is, you issue a
86 command by calling a method, and the command will block until the appropriate
87 response is returned. The method will then return the parsed results from
88 the given command.
89  
90 =cut
91  
92 # Export {{{
93 require Exporter;
94 @ISA = qw(Exporter);
95 %EXPORT_TAGS = (
96 Default => [ qw(get_body_part find_message build_cid_map generate_cid) ]
97 );
98 Exporter::export_ok_tags('Default');
99  
100 my $AlwaysTrace = 0;
101  
102 sub import {
103 # Test for special case if need UTF8 support
104 our $AlreadyLoadedEncode;
105 my $Class = shift(@_);
106  
107 my %Parameters = map { $_ => 1 } @_;
108  
109 if (delete($Parameters{':utf8support'})) {
110 if (!$AlreadyLoadedEncode) {
111 eval "use Encode qw(decode);";
112 eval "use Encode::Detect::Detector qw(detect);";
113 $AlreadyLoadedEncode = 1;
114 }
115 }
116  
117 if (delete($Parameters{':trace'})) {
118 $AlwaysTrace = 1;
119 }
120  
121 @_ = ($Class, keys(%Parameters));
122  
123 goto &Exporter::import;
124 }
125 # }}}
126  
127 # Use modules {{{
128 use Fcntl qw(:DEFAULT);
129 use Socket;
130 use IO::Select;
131 use IO::Handle;
132 use IO::Socket;
133 use Digest;
134 use Data::Dumper;
135  
136 # Choose the best socket class to use (all of these are sub-classes of IO::Socket)
137 my $DefSocketClass;
138 BEGIN {
139 for (qw(IO::Socket::IP IO::Socket::INET6 IO::Socket::INET)) {
140 if (eval "use $_; 1;") { $DefSocketClass = $_; last; }
141 }
142 }
143  
144 # Use Time::HiRes if available to handle select restarts
145 eval 'use Time::HiRes qw(time);';
146  
147 use strict;
148 use warnings;
149 # }}}
150  
151 =head1 CLASS OVERVIEW
152  
153 The object methods have been broken in several sections.
154  
155 =head2 Sections
156  
157 =over 4
158  
159 =item CONSTANTS
160  
161 Lists the available constants the class uses.
162  
163 =item CONSTRUCTOR
164  
165 Explains all the options available when constructing a new instance of the
166 C<Mail::IMAPTalk> class.
167  
168 =item CONNECTION CONTROL METHODS
169  
170 These are methods which control the overall IMAP connection object, such
171 as logging in and logging out, how results are parsed, how folder names and
172 message id's are treated, etc.
173  
174 =item IMAP FOLDER COMMAND METHODS
175  
176 These are methods to inspect, add, delete and rename IMAP folders on
177 the server.
178  
179 =item IMAP MESSAGE COMMAND METHODS
180  
181 These are methods to retrieve, delete, move and add messages to/from
182 IMAP folders.
183  
184 =item HELPER METHODS
185  
186 These are extra methods that users of this class might find useful. They
187 generally do extra parsing on returned structures to provide higher
188 level functionality.
189  
190 =item INTERNAL METHODS
191  
192 These are methods used internally by the C<Mail::IMAPTalk> object to get work
193 done. They may be useful if you need to extend the class yourself. Note that
194 internal methods will always 'die' if they encounter any errors.
195  
196 =item INTERNAL SOCKET FUNCTIONS
197  
198 These are functions used internally by the C<Mail::IMAPTalk> object
199 to read/write data to/from the IMAP connection socket. The class does
200 its own buffering so if you want to read/write to the IMAP socket, you
201 should use these functions.
202  
203 =item INTERNAL PARSING FUNCTIONS
204  
205 These are functions used to parse the results returned from the IMAP server
206 into Perl style data structures.
207  
208 =back
209  
210 =head2 Method results
211  
212 All methods return undef on failure. There are four main modes of failure:
213  
214 =over 4
215  
216 =item 1. An error occurred reading/writing to a socket. Maybe the server
217 closed it, or you're not connected to any server.
218  
219 =item 2. An error occurred parsing the response of an IMAP command. This is
220 usually only a problem if your IMAP server returns invalid data.
221  
222 =item 3. An IMAP command didn't return an 'OK' response.
223  
224 =item 4. The socket read operation timed out waiting for a response from
225 the server.
226  
227 =back
228  
229 In each case, some readable form of error text is placed in $@, or you
230 can call the C<get_last_error()> method. For commands which return
231 responses (e.g. fetch, getacl, etc), the result is returned. See each
232 command for details of the response result. For commands
233 with no response but which succeed (e.g. setacl, rename, etc) the result
234 'ok' is generally returned.
235  
236 =head2 Method parameters
237  
238 All methods which send data to the IMAP server (e.g. C<fetch()>, C<search()>,
239 etc) have their arguments processed before they are sent. Arguments may be
240 specified in several ways:
241  
242 =over 4
243  
244 =item B<scalar>
245  
246 The value is first checked and quoted if required. Values containing
247 [\000\012\015] are turned into literals, values containing
248 [\000-\040\{\} \%\*\"] are quoted by surrounding with a "..." pair
249 (any " themselves are turned into \"). undef is turned into NIL
250  
251 =item B<file ref>
252  
253 The contents of the file is sent as an IMAP literal. Note that
254 because IMAPTalk has to know the length of the file being sent,
255 this must be a true file reference that can be seeked and not
256 just some stream. The entire file will be sent regardless of the
257 current seek point.
258  
259 =item B<scalar ref>
260  
261 The string/data in the referenced item should be sent as is, no quoting will
262 occur, and the data won't be sent as quoted or as a literal regardless
263 of the contents of the string/data.
264  
265 =item B<array ref>
266  
267 Emits an opening bracket, and then each item in the array separated
268 by a space, and finally a closing bracket. Each item in the array
269 is processed by the same methods, so can be a scalar, file ref,
270 scalar ref, another array ref, etc.
271  
272 =item B<hash ref>
273  
274 The hash reference should contain only 1 item. The key is a text
275 string which specifies what to do with the value item of the hash.
276  
277 =over 4
278  
279 =item * 'Literal'
280  
281 The string/data in the value is sent as an IMAP literal
282 regardless of the actual data in the string/data.
283  
284 =item * 'Quote'
285  
286 The string/data in the value is sent as an IMAP quoted string
287 regardless of the actual data in the string/data.
288  
289 =back
290  
291 Examples:
292  
293 # Password is automatically quoted to "nasty%*\"passwd"
294 $IMAP->login("joe", 'nasty%*"passwd');
295 # Append $MsgTxt as string
296 $IMAP->append("inbox", { Literal => $MsgTxt })
297 # Append MSGFILE contents as new message
298 $IMAP->append("inbox", \*MSGFILE ])
299  
300 =back
301  
302 =cut
303  
304 =head1 CONSTANTS
305  
306 These constants relate to the standard 4 states that an IMAP connection can
307 be in. They are passed and returned from the C<state()> method. See RFC 3501
308 for more details about IMAP connection states.
309  
310 =over 4
311  
312 =item I<Unconnected>
313  
314 Current not connected to any server.
315  
316 =item I<Connected>
317  
318 Connected to a server, but not logged in.
319  
320 =item I<Authenticated>
321  
322 Connected and logged into a server, but not current folder.
323  
324 =item I<Selected>
325  
326 Connected, logged in and have 'select'ed a current folder.
327  
328 =back
329  
330 =cut
331  
332 # Constants for the possible states the connection can be in {{{
333 # Object not connected
334 use constant Unconnected => 0;
335 # connected; not logged in
336 use constant Connected => 1;
337 # logged in; no mailbox selected
338 use constant Authenticated => 2;
339 # mailbox selected
340 use constant Selected => 3;
341  
342 # What a link break is on the network connection
343 use constant LB => "\015\012";
344 use constant LBLEN => length(LB);
345  
346 # Regexps used to determine if header is MIME encoded (we remove . from
347 # especials because of dumb ANSI_X3.4-1968 encoding)
348 my $RFC2047Token = qr/[^\x00-\x1f\(\)\<\>\@\,\;\:\"\/\[\]\?\=\ ]+/;
349 my $RFC2047Encoded = qr/=\?$RFC2047Token\?$RFC2047Token\?[^\?]*\?=/;
350 my $NonAsciiData = qr/[\x1b\x80-\xff]/; # Anything with high-bits or ESC
351  
352 # Known untagged responses
353 my %UntaggedResponses = map { $_ => 1 } qw(exists expunge recent);
354  
355 # Default responses
356 my %RespDefaults = ('annotation' => 'hash', 'metadata' => 'hash', 'fetch' => 'hash', 'list' => 'array', 'lsub' => 'array', 'sort' => 'array', 'search' => 'array');
357  
358 # }}}
359  
360 =head1 CONSTRUCTOR
361  
362 =over 4
363  
364 =cut
365  
366 =item I<Mail::IMAPTalk-E<gt>new(%Options)>
367  
368 Creates new Mail::IMAPTalk object. The following options are supported.
369  
370 =item B<Connection Options>
371  
372 =over 4
373  
374 =item B<Server>
375  
376 The hostname or IP address to connect to. This must be supplied unless
377 the B<Socket> option is supplied.
378  
379 =item B<Port>
380  
381 The port number on the host to connect to. Defaults to 143 if not supplied
382 or 993 if not supplied and UseSSL is true.
383  
384 =item B<UseSSL>
385  
386 If true, use an IO::Socket::SSL connection. All other SSL_* arguments
387 are passed to the IO::Socket::SSL constructor.
388  
389 =item B<Socket>
390  
391 An existing socket to use as the connection to the IMAP server. If you
392 supply the B<Socket> option, you should not supply a B<Server> or B<Port>
393 option.
394  
395 This is useful if you want to create an SSL socket connection using
396 IO::Socket::SSL and then pass in the connected socket to the new() call.
397  
398 It's also useful in conjunction with the C<release_socket()> method
399 described below for reusing the same socket beyond the lifetime of the IMAPTalk
400 object. See a description in the section C<release_socket()> method for
401 more information.
402  
403 You must have write flushing enabled for any
404 socket you pass in here so that commands will actually be sent,
405 and responses received, rather than just waiting and eventually
406 timing out. you can do this using the Perl C<select()> call and
407 $| ($AUTOFLUSH) variable as shown below.
408  
409 my $ofh = select($Socket); $| = 1; select ($ofh);
410  
411 =item B<UseBlocking>
412  
413 For historical reasons, when reading from a socket, the module
414 sets the socket to non-blocking and does a select(). If you're
415 using an SSL socket that doesn't work, so you have to set
416 UseBlocking to true to use blocking reads instead.
417  
418 =item B<State>
419  
420 If you supply a C<Socket> option, you can specify the IMAP state the
421 socket is currently in, namely one of 'Unconnected', 'Connected',
422 'Authenticated' or 'Selected'. This defaults to 'Connected' if not
423 supplied and the C<Socket> option is supplied.
424  
425 =item B<ExpectGreeting>
426  
427 If supplied and true, and a socket is supplied via the C<Socket>
428 option, checks that a greeting line is supplied by the server
429 and reads the greeting line.
430  
431 =item B<PreserveINBOX>
432  
433 For historical reasons, the special name "INBOX" is rewritten as
434 Inbox because it looks nicer on the way out, and back on the way
435 in. If you want to preserve the name INBOX on the outside, set
436 this flag to true.
437  
438 =item B<UseCompress>
439  
440 If you have the Compress::Zlib package installed, and the server
441 supports compress, then setting this flag to true will cause
442 compression to be enabled immediately after login.
443  
444 =back
445  
446 =item B<Login Options>
447  
448 =over 4
449  
450 =item B<Username>
451  
452 The username to connect to the IMAP server as. If not supplied, no login
453 is attempted and the IMAP object is left in the B<CONNECTED> state.
454 If supplied, you must also supply the B<Password> option and a login
455 is attempted. If the login fails, the connection is closed and B<undef>
456 is returned. If you want to do something with a connection even if the
457 login fails, don't pass a B<Username> option, but instead use the B<login>
458 method described below.
459  
460 =item B<Password>
461  
462 The password to use to login to the account.
463  
464 =item B<AsUser>
465  
466 If the server supports it, access the server as this user rather than the
467 authenticate user.
468  
469 =back
470  
471 See the C<login> method for more information.
472  
473 =item B<IMAP message/folder options>
474  
475 =over 4
476  
477 =item B<Uid>
478  
479 Control whether message ids are message uids or not. This is 1 (on) by
480 default because generally that's how most people want to use it. This affects
481 most commands that require/use/return message ids (e.g. B<fetch>, B<search>,
482 B<sort>, etc)
483  
484 =item B<RootFolder>
485  
486 If supplied, sets the root folder prefix. This is the same as calling
487 C<set_root_folder()> with the value passed. If no value is supplied,
488 C<set_root_folder()> is called with no value. See the C<set_root_folder()>
489 method for more details.
490  
491 =item B<Separator>
492  
493 If supplied, sets the folder name text string separator character.
494 Passed as the second parameter to the C<set_root_folder()> method.
495  
496 =item B<AltRootRegexp>
497  
498 If supplied, passed along with RootFolder to the C<set_root_folder()>
499 method.
500  
501 =back
502  
503 Examples:
504  
505 $imap = Mail::IMAPTalk->new(
506 Server => 'foo.com',
507 Port => 143,
508 Username => 'joebloggs',
509 Password => 'mypassword',
510 Separator => '.',
511 RootFolder => 'INBOX',
512 ) || die "Connection to foo.com failed. Reason: $@";
513  
514 $imap = Mail::IMAPTalk->new(
515 Socket => $SSLSocket,
516 State => Mail::IMAPTalk::Authenticated,
517 Uid => 0
518 ) || die "Could not query on existing socket. Reason: $@";
519  
520 =cut
521 sub new {
522 my $Proto = shift;
523 my $Class = ref($Proto) || $Proto;
524 my %Args = @_;
525  
526 # Two main possible new() modes. Either connect to server
527 # or use existing socket passed
528 $Args{Server} || $Args{Socket}
529 || die "No 'Server' or 'Socket' specified";
530 $Args{Server} && $Args{Socket}
531 && die "Can not specify 'Server' and 'Socket' simultaneously";
532  
533 # Set ourself to empty to start with
534 my $Self = {};
535 bless ($Self, $Class);
536  
537 # Empty buffer
538 $Self->{ReadBuf} = '';
539  
540 # Create new socket to server
541 my $Socket;
542 if ($Args{Server}) {
543  
544 # Set starting state
545 $Self->state(Unconnected);
546  
547 my %SocketOpts;
548 my $DefaultPort = 143;
549 my $SocketClass = $DefSocketClass;
550  
551 if (my $SSLOpt = $Args{UseSSL}) {
552 $SSLOpt = $SSLOpt eq '1' ? '' : " qw($SSLOpt)";
553 eval "use IO::Socket::SSL$SSLOpt; 1;" || return undef;
554 $SocketClass = "IO::Socket::SSL";
555 $DefaultPort = 993;
556 $SocketOpts{$_} = $Args{$_} for grep { /^SSL_/ } keys %Args;
557 }
558  
559 $SocketOpts{PeerHost} = $Self->{Server} = $Args{Server} || die "No Server name given";
560 $SocketOpts{PeerPort} = $Self->{Port} = $Args{Port} || $DefaultPort;
561  
562 $Socket = ${SocketClass}->new(%SocketOpts) || return undef;
563  
564 # Force flushing after every write to the socket
565 my $ofh = select($Socket); $| = 1; select ($ofh);
566  
567 # Set to connected state
568 $Self->state(Connected);
569 }
570  
571 # We have an existing socket
572 else {
573 # Copy socket
574 $Socket = $Args{Socket};
575 delete $Args{Socket};
576  
577 # Set state
578 $Self->state(exists $Args{State} ? $Args{State} : Connected);
579 }
580  
581 $Self->{Socket} = $Socket;
582  
583 # Save socket for later use and create IO::Select
584 $Self->{Select} = IO::Select->new();
585 $Self->{Select}->add($Socket);
586 $Self->{LocalFD} = fileno($Socket);
587 $Self->{UseBlocking} = $Args{UseBlocking};
588 $Self->{Pedantic} = $Args{Pedantic};
589 $Self->{PreserveINBOX} = $Args{PreserveINBOX};
590 $Self->{UseCompress} = $Args{UseCompress};
591  
592 # Do this now, so we trace greeting line as well
593 $Self->set_tracing($AlwaysTrace);
594  
595 # Process greeting
596 if ($Args{Server} || $Args{ExpectGreeting}) {
597 $Self->{CmdId} = "*";
598 my ($CompletionResp, $DataResp) = $Self->_parse_response('');
599 return undef if $CompletionResp !~ /^ok/i;
600 }
601  
602 # Start counter when sending commands
603 $Self->{CmdId} = 1;
604  
605 # Set base modes
606 $Self->uid(exists($Args{Uid}) ? $Args{Uid} : 1);
607 $Self->parse_mode(Envelope => 1, BodyStructure => 1, Annotation => 1);
608 $Self->{CurrentFolder} = '';
609 $Self->{CurrentFolderMode} = '';
610  
611 # Login first if specified
612 if ($Args{Username}) {
613 # If login fails, just return undef
614 $Self->login(@Args{'Username', 'Password', 'AsUser'}) || return undef;
615 }
616  
617 # Set root folder and separator (if supplied)
618 $Self->set_root_folder(
619 $Args{RootFolder}, $Args{Separator}, $Args{AltRootRegexp});
620  
621 return $Self;
622 }
623  
624 =back
625 =cut
626  
627 =head1 CONNECTION CONTROL METHODS
628  
629 =over 4
630 =cut
631  
632 =item I<login($User, $Password, [$AsUser])>
633  
634 Attempt to login user specified username and password.
635  
636 The actual authentication may be done using the C<LOGIN> or C<AUTHENTICATE>
637 commands, depending on what the server advertises support for.
638  
639 If C<$AsUser> is supplied, an attempt will be made to login on behalf of that user.
640  
641 =cut
642 sub login {
643 my $Self = shift;
644 my ($User, $Pwd, $AsUser) = @_;
645 my $PwdArr = { 'Quote' => $Pwd };
646  
647 # Clear cached capability responses and the like
648 delete $Self->{Cache};
649  
650 # If we don't to authenticate on behalf of a user and the server can support
651 # the standard IMAP LOGIN command, then just use that
652 if (!$AsUser && !$Self->capability->{logindisabled}) {
653 $Self->_imap_cmd("login", 0, "", $User, $PwdArr)
654 || return undef;
655 }
656  
657 # Otherwise we'll need to do a true SASL auth
658 else {
659 require Authen::SASL;
660 require MIME::Base64;
661  
662 my @Mechanisms = map { m/auth=(.+)/ ? uc $1 : () } keys %{$Self->capability};
663 my $SendFirst = $Self->capability->{'sasl-ir'};
664  
665 my $SASL = Authen::SASL->new(
666 mechanism => join(' ', @Mechanisms),
667 callback => {
668 user => $User,
669 pass => $Pwd,
670 authname => $AsUser,
671 },
672 );
673  
674 my $SASLClient = eval { $SASL->client_new };
675 if ($@) {
676 die "IMAPTalk: Couldn't create SASL client: $@"
677 }
678 my $InitialResponse = $SASLClient->client_start;
679 unless (defined $InitialResponse) {
680 die "IMAPTalk: Couldn't start SASL handshake: ".$SASL->error;
681 }
682  
683 my $PostCommand = sub {
684 $Self->{ReadLine} = undef;
685  
686 if ($InitialResponse && !$SendFirst) {
687 # Need to send initial response (SASL-IR not available)
688  
689 my $Resp = $Self->_next_atom();
690 if (!$Resp || $Resp ne '+') {
691 die "IMAPTalk: Did not get '+' response";
692 }
693  
694 # Consume anything left on the wire. Shouldn't be necessary, but...
695 $Self->_remaining_atoms();
696  
697 $Self->_imap_socket_out(MIME::Base64::encode_base64($InitialResponse, '') . LB);
698 }
699  
700 while ($SASLClient->need_step) {
701  
702 # The server response will either be '+ <challenge>' or '<tag> NO'. So
703 # we read the line and if its not a SASL challenge, we put the whole
704 # line back onto the buffer and bail, letting the normal command
705 # response handler deal with it.
706 my $Line = $Self->_imap_socket_read_line;
707 unless ($Line =~ m/^\+/) {
708 substr($Self->{ReadBuf}, 0, 0, $Line . LB);
709 $Self->{ReadLine} = undef;
710 last;
711 }
712  
713 # It's a challenge line, put it on the regular line buffer so we can
714 # use the atom parser
715 $Self->{ReadLine} = $Line;
716  
717 # Consume the leading '+'
718 $Self->_next_atom();
719  
720 # A SASL challenge. Decode and take a step
721 my ($EncChallenge) = @{$Self->_remaining_atoms()};
722 my $Challenge = MIME::Base64::decode_base64($EncChallenge);
723  
724 my $Response = $SASLClient->client_step($Challenge);
725 unless (defined $Response) {
726 die "IMAPTalk: Couldn't continue SASL handshake: ".$SASL->error;
727 }
728 $Self->_imap_socket_out(MIME::Base64::encode_base64($Response, '') . LB);
729 }
730 };
731  
732 my %ParseMode = (PostCommand => $PostCommand);
733 $Self->_imap_cmd(
734 \%ParseMode, "authenticate", 0, '',
735 $SASLClient->mechanism,
736 ($SendFirst && $InitialResponse) ? MIME::Base64::encode_base64($InitialResponse, '') : ())
737  
738 || return undef;
739 }
740  
741 if ($Self->{UseCompress} && $Self->_require_capability('compress=deflate') && require 'Compress/Zlib.pm') {
742 if ($Self->_imap_cmd("compress", 0, "", "deflate")) {
743 my $error;
744 ($Self->{CompressDeflate}, $error) = Compress::Zlib::deflateInit(-WindowBits => -Compress::Zlib::MAX_WBITS());
745 die "FAILED TO INIT DEFLATE $error" if $error;
746 ($Self->{CompressInflate}, $error) = Compress::Zlib::inflateInit(-WindowBits => -Compress::Zlib::MAX_WBITS());
747 die "FAILED TO INIT INFLATE $error" if $error;
748 }
749 }
750  
751 # Set to authenticated if successful
752 $Self->state(Authenticated);
753  
754 return 1;
755 }
756  
757 =item I<logout()>
758  
759 Log out of IMAP server. This usually closes the servers connection as well.
760  
761 =cut
762 sub logout {
763 my $Self = shift;
764 # Callback to say we're switching folders
765 $Self->cb_switch_folder($Self->{CurrentFolder}, '');
766 $Self->_imap_cmd('logout', 0, '');
767 # Returns the socket, which we immediately discard to close
768 $Self->release_socket(1);
769 return 1;
770 }
771  
772 =item I<state(optional $State)>
773  
774 Set/get the current IMAP connection state. Returned or passed value should be
775 one of the constants (Unconnected, Connected, Authenticated, Selected).
776  
777 =cut
778 sub state {
779 my $Self = shift;
780 $Self->{State} = $_[0] if defined $_[0];
781 return (defined($Self->{State}) ? $Self->{State} : '');
782 }
783  
784 =item I<uid(optional $UidMode)>
785  
786 Get/set the UID status of all UID possible IMAP commands.
787 If set to 1, all commands that can take a UID are set to 'UID Mode',
788 where any ID sent to IMAPTalk is assumed to be a UID.
789  
790 =cut
791 sub uid {
792 $_[0]->{Uid} = $_[1];
793 return 1;
794 }
795  
796 =item I<capability()>
797  
798 This method returns the IMAP servers capability command results.
799 The result is a hash reference of (lc(Capability) => 1) key value pairs.
800 This means you can do things like:
801  
802 if ($IMAP->capability()->{quota}) { ... }
803  
804 to test if the server has the QUOTA capability. If you just want a list of
805 capabilities, use the Perl 'keys' function to get a list of keys from the
806 returned hash reference.
807  
808 =cut
809 sub capability {
810 my $Self = shift;
811  
812 # If we've already executed the capability command once, just return the results
813 return $Self->{Cache}->{capability}
814 if exists $Self->{Cache}->{capability};
815  
816 # Otherwise execute capability command
817 my $Capability = $Self->_imap_cmd("capability", 0, "capability");
818  
819 # Better be a hash-ref...
820 ($Capability && ref($Capability) eq 'HASH') || return {};
821  
822 # Save for any future queries and return
823 return ($Self->{Cache}->{capability} = $Capability);
824 }
825  
826 =item I<namespace()>
827  
828 Returns the result of the IMAP servers namespace command.
829  
830 =cut
831 sub namespace {
832 my $Self = shift;
833  
834 # If we've already executed the capability command once, just return the results
835 return $Self->{Cache}->{namespace}
836 if exists $Self->{Cache}->{namespace};
837  
838 $Self->_require_capability('namespace') || return undef;
839  
840 # Otherwise execute capability command
841 my $Namespace = $Self->_imap_cmd("namespace", 0, "namespace");
842  
843 # Save for any future queries and return
844 return ($Self->{Cache}->{namespace} = $Namespace);
845 }
846  
847 =item I<noop()>
848  
849 Perform the standard IMAP 'noop' command which does nothing.
850  
851 =cut
852 sub noop {
853 my $Self = shift;
854 return $Self->_imap_cmd("noop", 0, "", @_);
855 }
856  
857 =item I<enable($option)>
858  
859 Enabled the given imap extension
860  
861 =cut
862 sub enable {
863 my $Self = shift;
864 my $Feature = shift;
865  
866 # If we've already executed the enable command once, just return the results
867 return $Self->{Cache}->{enable}->{$Feature}
868 if exists $Self->{Cache}->{enable}->{$Feature};
869  
870 $Self->_require_capability($Feature) || return undef;
871  
872 my $Result = $Self->_imap_cmd("enable", 0, "enabled", $Feature);
873 $Self->{Cache}->{enable} = $Result;
874  
875 return $Result && $Result->{$Feature};
876 }
877  
878 =item I<is_open()>
879  
880 Returns true if the current socket connection is still open (e.g. the socket
881 hasn't been closed this end or the other end due to a timeout).
882  
883 =cut
884 sub is_open {
885 my $Self = shift;
886  
887 $Self->_trace("A: is_open test\n") if $Self->{Trace};
888  
889 while (1) {
890  
891 # Ensure no data was left in our own read buffer
892 if ($Self->{ReadLine}) {
893 $Self->_trace("A: unexpected data in read buffer - '" .$Self->{ReadLine}. "'\n")
894 if $Self->{Trace};
895 die "IMAPTalk: Unexpected data in read buffer '" . $Self->{ReadLine} . "'";
896 }
897 $Self->{ReadLine} = undef;
898  
899 # See if there's any data to read
900 local $Self->{Timeout} = 0;
901  
902 # If no sockets with data, must be blocked, so must be connected
903 my $Atom = eval { $Self->_next_atom(); };
904  
905 # If a timeout, socket is still connected and open
906 if ($@ && ($@ =~ /timed out/)) {
907 $Self->_trace("A: is_open test received timeout, still open\n")
908 if $Self->{Trace};
909 return 1;
910 }
911  
912 # Other error, assume it's closed
913 if ($@) {
914 $Self->_trace("A: is_open test received error - $@\n")
915 if $Self->{Trace};
916 $Self->{Socket}->close() if $Self->{Socket};
917 $Self->{Socket} = undef;
918 delete $Self->{CompressInflate};
919 delete $Self->{CompressDeflate};
920 $Self->state(Unconnected);
921 return undef;
922 }
923  
924 # There was something, find what it was
925 $Atom = $Self->_remaining_line();
926  
927 $Self->_trace("A: is_open test returned data - '$Atom'\n")
928 if $Self->{Trace};
929  
930 $Atom || die "IMAPTalk: Unexpected response while checking connection - $Atom";
931  
932 # If it's a bye, we're being closed
933 if ($Atom =~ /^bye/i) {
934 $Self->_trace("A: is_open test received 'bye' response\n")
935 if $Self->{Trace};
936 $Self->{Socket}->close();
937 $Self->{Socket} = undef;
938 delete $Self->{CompressInflate};
939 delete $Self->{CompressDeflate};
940 $Self->state(Unconnected);
941 return undef;
942 }
943  
944 # Otherwise it was probably some sort of alert,
945 # check again
946 }
947  
948 }
949  
950 =item I<set_root_folder($RootFolder, $Separator, $AltRootRegexp)>
951  
952 Change the root folder prefix. Some IMAP servers require that all user
953 folders/mailboxes live under a root folder prefix (current versions of
954 B<cyrus> for example use 'INBOX' for personal folders and 'user' for other
955 users folders). If no value is specified, it sets it to ''. You might
956 want to use the B<namespace()> method to find out what roots are
957 available.
958  
959 Setting this affects all commands that take a folder argument. Basically
960 if the foldername begins with root folder prefix, it's left as is,
961 otherwise the root folder prefix and separator char are prefixed to the
962 folder name.
963  
964 The AltRootRegexp is a regexp that if the start of the folder name matches,
965 does not have $RootFolder preprended. You can use this to protect
966 other namespaces in your IMAP server.
967  
968 Examples:
969  
970 # This is what cyrus uses
971 $IMAP->set_root_folder('INBOX', '.', qr/^user/);
972  
973 # Selects 'Inbox' (because 'Inbox' eq 'inbox' case insensitive)
974 $IMAP->select('Inbox');
975 # Selects 'INBOX.blah'
976 $IMAP->select('blah');
977 # Selects 'INBOX.Inbox.fred'
978 #IMAP->select('Inbox.fred');
979 # Selects 'user.john' (because 'user' is alt root)
980 #IMAP->select('user.john'); # Selects 'user.john'
981  
982 =cut
983 sub set_root_folder {
984 my ($Self, $RootFolder, $Separator, $AltRootRegexp) = @_;
985  
986 $RootFolder = '' if !defined($RootFolder);
987 $Separator = '.' if !defined($Separator);
988  
989 # Strip off the Separator, if the IMAP-Server already appended it
990 $RootFolder =~ s/\Q$Separator\E$//;
991  
992 $Self->{RootFolder} = $RootFolder;
993 $Self->{AltRootRegexp} = $AltRootRegexp;
994 $Self->{Separator} = $Separator;
995  
996 # We map canonical IMAP INBOX to nicer looking Inbox,
997 # but have to be careful if the root is INBOX as well
998  
999 # INBOX -> Inbox (done in _fix_folder_name)
1000 # INBOX.blah -> blah
1001 # INBOX.inbox -> INBOX.inbox
1002 # INBOX.Inbox -> INBOX.Inbox
1003 # INBOX.inbox.inbox -> INBOX.inbox.inbox
1004 # INBOX.Inbox.blah -> Inbox.blah
1005 # user.xyz -> user.xyz
1006  
1007 # RootFolderMatch
1008 # If folder passed in doesn't match this, then prepend $RootFolder . $Separator
1009 # eg prepend inbox. if folder !/^inbox(\.inbox)*$|^user$|^user\./
1010  
1011 # UnrootFolderMatch
1012 # If folder returned matches this, strip $RootFolder . $Separator
1013 # eg strip inbox. if folder /^inbox\.(?!inbox(\.inbox)*)/
1014  
1015 my ($RootFolderMatch, $UnrootFolderMatch);
1016 if ($RootFolder) {
1017 # Note the /i on the end to make this case-insensitive
1018 $RootFolderMatch = qr/\Q${RootFolder}\E(?:\Q${Separator}${RootFolder}\E)*/i;
1019 $UnrootFolderMatch = qr/^\Q${RootFolder}${Separator}\E(?!${RootFolderMatch}$)/;
1020  
1021 if ($AltRootRegexp) {
1022 $RootFolderMatch = qr/^${RootFolderMatch}$|^(?:${AltRootRegexp}(?:\Q${Separator}\E|$))/;
1023 } else {
1024 $RootFolderMatch = qr/^${RootFolderMatch}$/;
1025 }
1026 }
1027  
1028 @$Self{qw(RootFolderMatch UnrootFolderMatch)}
1029 = ($RootFolderMatch, $UnrootFolderMatch);
1030  
1031 return 1;
1032 }
1033  
1034 =item I<_set_separator($Separator)>
1035  
1036 Checks if the given separator is the same as the one we used before.
1037 If not, it calls set_root_folder to recreate the settings with the new
1038 Separator.
1039  
1040 =cut
1041 sub _set_separator {
1042 my ($Self, $Separator) = @_;
1043  
1044 #Nothing to do, if we have the same Separator as before
1045 return 1 if (defined($Separator) && ($Self->{Separator} eq $Separator));
1046 return $Self->set_root_folder($Self->{RootFolder}, $Separator, $Self->{AltRootRegexp});
1047 }
1048  
1049 =item I<literal_handle_control(optional $FileHandle)>
1050  
1051 Sets the mode whether to read literals as file handles or scalars.
1052  
1053 You should pass a filehandle here that any literal will be read into. To
1054 turn off literal reads into a file handle, pass a 0.
1055  
1056 Examples:
1057  
1058 # Read rfc822 text of message 3 into file
1059 # (note that the file will have /r/n line terminators)
1060 open(F, ">messagebody.txt");
1061 $IMAP->literal_handle_control(\*F);
1062 $IMAP->fetch(3, 'rfc822');
1063 $IMAP->literal_handle_control(0);
1064  
1065 =cut
1066 sub literal_handle_control {
1067 my $Self = shift;
1068 $Self->{LiteralControl} = $_[0] if defined $_[0];
1069 return $Self->{LiteralControl} ? 1 : 0;
1070 }
1071  
1072 =item I<release_socket($Close)>
1073  
1074 Release IMAPTalk's ownership of the current socket it's using so it's not
1075 disconnected on DESTROY. This returns the socket, and makes sure that the
1076 IMAPTalk object doesn't hold a reference to it any more and the connection
1077 state is set to "Unconnected".
1078  
1079 This means you can't call any methods on the IMAPTalk object any more.
1080  
1081 If the socket is being released and being closed, then $Close is set to true.
1082  
1083 =cut
1084 sub release_socket {
1085 my $Self = shift;
1086  
1087 # Remove from the select object
1088 $Self->{Select}->remove($Self->{Socket}) if ref($Self->{Select});
1089 my $Socket = $Self->{Socket};
1090  
1091 # Delete any knowledge of the socket in our instance
1092 delete $Self->{Socket};
1093 delete $Self->{Select};
1094 delete $Self->{CompressInflate};
1095 delete $Self->{CompressDeflate};
1096  
1097 $Self->_trace("A: Release socket, fileno=" . fileno($Socket) . "\n")
1098 if $Self->{Trace};
1099  
1100 # Set into no connection state
1101 $Self->state(Mail::IMAPTalk::Unconnected);
1102  
1103 return $Socket;
1104 }
1105  
1106 =item I<get_last_error()>
1107  
1108 Returns a text string which describes the last error that occurred.
1109  
1110 =cut
1111 sub get_last_error {
1112 my $Self = shift;
1113 return $Self->{LastError};
1114 }
1115  
1116 =item I<get_last_completion_response()>
1117  
1118 Returns the last completion response to the tagged command.
1119  
1120 This is either the string "ok", "no" or "bad" (always lower case)
1121  
1122 =cut
1123 sub get_last_completion_response {
1124 my $Self = shift;
1125 return $Self->{LastRespCode};
1126 }
1127  
1128 =item I<get_response_code($Response)>
1129  
1130 Returns the extra response data generated by a previous call. This is
1131 most often used after calling B<select> which usually generates some
1132 set of the following sub-results.
1133  
1134 =over 4
1135  
1136 =item * B<permanentflags>
1137  
1138 Array reference of flags which are stored permanently.
1139  
1140 =item * B<uidvalidity>
1141  
1142 Whether the current UID set is valid. See the IMAP RFC for more
1143 information on this. If this value changes, then all UIDs in the folder
1144 have been changed.
1145  
1146 =item * B<uidnext>
1147  
1148 The next UID number that will be assigned.
1149  
1150 =item * B<exists>
1151  
1152 Number of messages that exist in the folder.
1153  
1154 =item * B<recent>
1155  
1156 Number of messages that are recent in the folder.
1157  
1158 =back
1159  
1160 Other possible responses are B<alert>, B<newname>, B<parse>,
1161 B<trycreate>, B<appenduid>, etc.
1162  
1163 The values are stored in a hash keyed on the $Response item.
1164 They're kept until either overwritten by a future response,
1165 or explicitly cleared via clear_response_code().
1166  
1167 Examples:
1168  
1169 # Select inbox and get list of permanent flags, uidnext and number
1170 # of message in the folder
1171 $IMAP->select('inbox');
1172 my $NMessages = $IMAP->get_response_code('exists');
1173 my $PermanentFlags = $IMAP->get_response_code('permanentflags');
1174 my $UidNext = $IMAP->get_response_code('uidnext');
1175  
1176 =cut
1177 sub get_response_code {
1178 my ($Self, $Response) = @_;
1179 return $Self->{Cache}->{$Response};
1180 }
1181  
1182 =item I<clear_response_code($Response)>
1183  
1184 Clears any response code information. Response code information
1185 is not normally cleared between calls.
1186  
1187 =cut
1188 sub clear_response_code {
1189 my ($Self, $Response) = @_;
1190 delete $Self->{Cache}->{$Response};
1191 return 1;
1192 }
1193  
1194 =item I<parse_mode(ParseOption =E<gt> $ParseMode)>
1195  
1196 Changes how results of fetch commands are parsed. Available
1197 options are:
1198  
1199 =over 4
1200  
1201 =item I<BodyStructure>
1202  
1203 Parse bodystructure into more Perl-friendly structure
1204 See the B<FETCH RESULTS> section.
1205  
1206 =item I<Envelope>
1207  
1208 Parse envelopes into more Perl-friendly structure
1209 See the B<FETCH RESULTS> section.
1210  
1211 =item I<Annotation>
1212  
1213 Parse annotation (from RFC 5257) into more Perl-friendly structure
1214 See the B<FETCH RESULTS> section.
1215  
1216 =item I<EnvelopeRaw>
1217  
1218 If parsing envelopes, create To/Cc/Bcc and
1219 Raw-To/Raw-Cc/Raw-Bcc entries which are array refs of 4
1220 entries each as returned by the IMAP server.
1221  
1222 =item I<DecodeUTF8>
1223  
1224 If parsing envelopes, decode any MIME encoded headers into
1225 Perl UTF-8 strings.
1226  
1227 For this to work, you must have 'used' Mail::IMAPTalk with:
1228  
1229 use Mail::IMAPTalk qw(:utf8support ...)
1230  
1231 =back
1232  
1233 =cut
1234 sub parse_mode {
1235 my $Self = shift;
1236  
1237 my $ParseMode = $Self->{ParseMode} || {};
1238 $Self->{ParseMode} = { %$ParseMode, @_ };
1239  
1240 }
1241  
1242 =item I<set_tracing($Tracer)>
1243  
1244 Allows you to trace both IMAP input and output sent to the server
1245 and returned from the server. This is useful for debugging. Returns
1246 the previous value of the tracer and then sets it to the passed
1247 value. Possible values for $Tracer are:
1248  
1249 =over 4
1250  
1251 =item I<0>
1252  
1253 Disable all tracing.
1254  
1255 =item I<1>
1256  
1257 Print to STDERR.
1258  
1259 =item I<Code ref>
1260  
1261 Call code ref for each line input and output. Pass line as parameter.
1262  
1263 =item I<Glob ref>
1264  
1265 Print to glob.
1266  
1267 =item I<Scalar ref>
1268  
1269 Appends to the referenced scalar.
1270  
1271 =back
1272  
1273 Note: literals are never passed to the tracer.
1274  
1275 =cut
1276 sub set_tracing {
1277 my $Self = shift;
1278 my $OldTrace = $Self->{Trace};
1279 $Self->{Trace} = shift;
1280 return $OldTrace;
1281 }
1282  
1283 =item I<set_unicode_folders($Unicode)>
1284  
1285 $Unicode should be 1 or 0
1286  
1287 Sets whether folder names are expected and returned
1288 as perl unicode strings.
1289  
1290 The default is currently 0, BUT YOU SHOULD NOT ASSUME THIS,
1291 because it will probably change in the future.
1292  
1293 If you want to work with perl unicode strings for
1294 folder names, you should call
1295 $ImapTalk->set_unicode_folders(1)
1296 and IMAPTalk will automatically encode the unicode
1297 strings into IMAP-UTF7 when sending to the IMAP server,
1298 and will also decode IMAP-UTF7 back into perl unicode
1299 strings when returning results from the IMAP server.
1300  
1301 If you want to work with folder names in IMAP-UTF7 bytes,
1302 then call
1303 $ImapTalk->set_unicode_folders(0)
1304 and IMAPTalk will leave folder names as bytes when
1305 sending to and returning results from the IMAP server.
1306  
1307 =cut
1308 sub set_unicode_folders {
1309 my $Self = shift;
1310 $Self->{Cache}->{UnicodeFolders} = shift;
1311 if ($Self->{Cache}->{UnicodeFolders}) {
1312 require Encode;
1313 require Encode::IMAPUTF7;
1314 }
1315 }
1316  
1317 sub unicode_folders {
1318 my $Self = shift;
1319 return 0 if ! $Self->{Cache};
1320 return $Self->{Cache}->{UnicodeFolders} || 0;
1321 }
1322  
1323 =back
1324 =cut
1325  
1326 =head1 IMAP FOLDER COMMAND METHODS
1327  
1328 B<Note:> In all cases where a folder name is used,
1329 the folder name is first manipulated according to the current root folder
1330 prefix as described in C<set_root_folder()>.
1331  
1332 =over 4
1333 =cut
1334  
1335 =item I<select($FolderName, @Opts)>
1336  
1337 Perform the standard IMAP 'select' command to select a folder for
1338 retrieving/moving/adding messages. If $Opts{ReadOnly} is true, the
1339 IMAP EXAMINE verb is used instead of SELECT.
1340  
1341 Mail::IMAPTalk will cache the currently selected folder, and if you
1342 issue another ->select("XYZ") for the folder that is already selected,
1343 it will just return immediately. This can confuse code that expects
1344 to get side effects of a select call. For that case, call ->unselect()
1345 first, then ->select().
1346  
1347 =cut
1348 sub select {
1349 my ($Self, $Folder, %Opts) = @_;
1350  
1351 my $unselect = delete($Opts{unselect});
1352 my $ReadOnly = delete($Opts{ReadOnly});
1353  
1354 if ($unselect) {
1355 $Self->unselect();
1356 }
1357  
1358 # Are we already selected and in the same mode?
1359 if ($Self->_is_current_folder($Folder) &&
1360 ($ReadOnly ? 'read-only' : 'read-write') eq $Self->{CurrentFolderMode}) {
1361 return 1;
1362 }
1363  
1364 # Callback to say we're switching folders
1365 $Self->cb_switch_folder($Self->{CurrentFolder}, $Folder);
1366  
1367 # Fix the folder name to include the root suffix
1368 my $FixFolder = $Self->_fix_folder_name($Folder);
1369  
1370 $Self->clear_response_code('READ-ONLY');
1371 $Self->clear_response_code('READ-WRITE');
1372  
1373 # Do select command
1374 my $Cmd = $ReadOnly ? "examine" : "select";
1375 my $Res = $Self->_imap_cmd($Cmd, 0, "", { Quote => $FixFolder }, keys(%Opts));
1376 if ($Res) {
1377 # Set internal current folder and mode
1378 $Self->{CurrentFolder} = $Folder;
1379 my $foldermode = $Self->get_response_code('foldermode') // '';
1380 if ($foldermode eq 'read-write' and $ReadOnly) {
1381 # odd, we only asked for it to be read-only. Buggy Cyrus 2.3.3?
1382 $foldermode = 'read-only';
1383 }
1384 $Self->{CurrentFolderMode} = $foldermode;
1385  
1386 # Set to selected state
1387 $Self->state(Selected);
1388 return $Self->{CurrentFolderMode} || $Self->{LastRespCode};
1389 } else {
1390 $Self->{CurrentFolder} = "";
1391 $Self->{LastError} = $@ =
1392 "Select failed for folder '$Folder' : $Self->{LastError}";
1393 }
1394  
1395 return undef;
1396 }
1397  
1398 =item I<unselect()>
1399  
1400 Performs the standard IMAP unselect command.
1401  
1402 =cut
1403 sub unselect {
1404 my $Self = shift;
1405  
1406 # Callback to say we're switching folders
1407 $Self->cb_switch_folder($Self->{CurrentFolder}, '');
1408  
1409 my $Res = $Self->_imap_cmd("unselect", 0, "", @_);
1410  
1411 # Clear cached information about current folder
1412 if ($Res) {
1413 $Self->{CurrentFolder} = '';
1414 $Self->{CurrentFolderMode} = 0;
1415 $Self->state(Authenticated);
1416 }
1417 return $Res;
1418 }
1419  
1420 =item I<examine($FolderName)>
1421  
1422 Perform the standard IMAP 'examine' command to select a folder in read only
1423 mode for retrieving messages. This is the same as C<select($FolderName, 1)>.
1424 See C<select()> for more details.
1425  
1426 =cut
1427 sub examine {
1428 return $_[0]->select($_[1], ReadOnly => 1);
1429 }
1430  
1431 =item I<create($FolderName)>
1432  
1433 Perform the standard IMAP 'create' command to create a new folder.
1434  
1435 =cut
1436 sub create {
1437 my $Self = shift;
1438 $Self->cb_folder_changed($_[0]);
1439 return $Self->_imap_cmd("create", 0, "", $Self->_fix_folder_name(+shift), @_);
1440 }
1441  
1442 =item I<delete($FolderName)>
1443  
1444 Perform the standard IMAP 'delete' command to delete a folder.
1445  
1446 =cut
1447 sub delete {
1448 my $Self = shift;
1449 $Self->{CurrentFolder} = "" if $Self->_is_current_folder($_[0]);
1450 $Self->cb_folder_changed($_[0]);
1451 return $Self->_imap_cmd("delete", 0, "", $Self->_fix_folder_name(+shift), @_);
1452 }
1453  
1454 =item I<localdelete($FolderName)>
1455  
1456 Perform the IMAP 'localdelete' command to delete a folder (doesn't delete subfolders even of INBOX, is always immediate.
1457  
1458 =cut
1459 sub localdelete {
1460 my $Self = shift;
1461 $Self->{CurrentFolder} = "" if $Self->_is_current_folder($_[0]);
1462 $Self->cb_folder_changed($_[0]);
1463 return $Self->_imap_cmd("localdelete", 0, "", $Self->_fix_folder_name(+shift), @_);
1464 }
1465  
1466 =item I<rename($OldFolderName, $NewFolderName)>
1467  
1468 Perform the standard IMAP 'rename' command to rename a folder.
1469  
1470 =cut
1471 sub rename {
1472 my $Self = shift;
1473 $Self->{CurrentFolder} = "" if $Self->_is_current_folder($_[0]);
1474 $Self->cb_folder_changed($_[0]);
1475 $Self->cb_folder_changed($_[1]);
1476 my $FolderName1 = $Self->_fix_folder_name(+shift);
1477 my $FolderName2 = $Self->_fix_folder_name(+shift);
1478 return $Self->_imap_cmd("rename", 0, "", $FolderName1, $FolderName2, @_);
1479 }
1480  
1481 =item I<list($Reference, $Name)>
1482  
1483 Perform the standard IMAP 'list' command to return a list of available
1484 folders.
1485  
1486 =cut
1487 sub list {
1488 my $Self = shift;
1489 my @Args = @_;
1490 # If the first argument is an array ref, then it's an extended list,
1491 # and any folder list is 3rd argument, not 2nd
1492 my $FolderPos = ref($Args[0]) ? 2 : 1;
1493 if (ref($Args[$FolderPos])) {
1494 $Args[$FolderPos] = [ map { $Self->_fix_folder_encoding($_) } @{$Args[$FolderPos]} ];
1495 } else {
1496 $Args[$FolderPos] = $Self->_fix_folder_encoding($Args[$FolderPos]);
1497 }
1498 return $Self->_imap_cmd("list", 0, "list", @Args);
1499 }
1500  
1501 =item I<xlist($Reference, $Name)>
1502  
1503 Perform the IMAP 'xlist' extension command to return a list of available
1504 folders and their special use attributes.
1505  
1506 =cut
1507 sub xlist {
1508 my $Self = shift;
1509 $Self->_require_capability('xlist') || return undef;
1510 return $Self->_imap_cmd("xlist", 0, "xlist", @_);
1511 }
1512  
1513 =item I<id($key => $value, ...)>
1514  
1515 Perform the IMAP extension command 'id'
1516  
1517 =cut
1518 sub id {
1519 my $Self = shift;
1520 $Self->_require_capability('id') || return undef;
1521 return $Self->_imap_cmd('id', 0, 'id', { Quote => \@_ });
1522 }
1523  
1524 =item I<lsub($Reference, $Name)>
1525  
1526 Perform the standard IMAP 'lsub' command to return a list of subscribed
1527 folders
1528  
1529 =cut
1530 sub lsub {
1531 my $Self = shift;
1532 return $Self->_imap_cmd("lsub", 0, "lsub", @_);
1533 }
1534  
1535 =item I<subscribe($FolderName)>
1536  
1537 Perform the standard IMAP 'subscribe' command to subscribe to a folder.
1538  
1539 =cut
1540 sub subscribe {
1541 my $Self = shift;
1542 my $FolderName = $Self->_fix_folder_name(+shift);
1543 return $Self->_imap_cmd("subscribe", 0, "", $FolderName);
1544 }
1545  
1546 =item I<unsubscribe($FolderName)>
1547  
1548 Perform the standard IMAP 'unsubscribe' command to unsubscribe from a folder.
1549  
1550 =cut
1551 sub unsubscribe {
1552 my $Self = shift;
1553 my $FolderName = $Self->_fix_folder_name(+shift);
1554 return $Self->_imap_cmd("unsubscribe", 0, "", $FolderName);
1555 }
1556  
1557 =item I<check()>
1558  
1559 Perform the standard IMAP 'check' command to checkpoint the current folder.
1560  
1561 =cut
1562 sub check {
1563 my $Self = shift;
1564 return $Self->_imap_cmd("check", 0, "", @_);
1565 }
1566  
1567 =item I<setacl($FolderName, $User, $Rights)>
1568  
1569 Perform the IMAP 'setacl' command to set the access control list
1570 details of a folder/mailbox. See RFC 4314 for more details on the IMAP
1571 ACL extension. $User is the user name to set the access
1572 rights for. $Rights is either a list of absolute rights to set, or a
1573 list prefixed by a - to remove those rights, or a + to add those rights.
1574  
1575 =over 4
1576  
1577 =item l - lookup (mailbox is visible to LIST/LSUB commands)
1578  
1579 =item r - read (SELECT the mailbox, perform CHECK, FETCH, PARTIAL, SEARCH, COPY from mailbox)
1580  
1581 =item s - keep seen/unseen information across sessions (STORE SEEN flag)
1582  
1583 =item w - write (STORE flags other than SEEN and DELETED)
1584  
1585 =item i - insert (perform APPEND, COPY into mailbox)
1586  
1587 =item p - post (send mail to submission address for mailbox, not enforced by IMAP4 itself)
1588  
1589 =item k - create mailboxes (CREATE new sub-mailboxes in any implementation-defined hierarchy, parent mailbox for the new mailbox name in RENAME)
1590  
1591 =item x - delete mailbox (DELETE mailbox, old mailbox name in RENAME)
1592  
1593 =item t - delete messages (set or clear \DELETED flag via STORE, set \DELETED flag during APPEND/COPY)
1594  
1595 =item e - perform EXPUNGE and expunge as a part of CLOSE
1596  
1597 =item a - administer (perform SETACL)
1598  
1599 =back
1600  
1601 Due to ambiguity in RFC 2086, some existing RFC 2086 server
1602 implementations use the "c" right to control the DELETE command.
1603 Others chose to use the "d" right to control the DELETE command. See
1604 the 2.1.1. Obsolete Rights in RFC 4314 for more details.
1605  
1606 =over 4
1607  
1608 =item c - create (CREATE new sub-mailboxes in any implementation-defined hierarchy)
1609  
1610 =item d - delete (STORE DELETED flag, perform EXPUNGE)
1611  
1612 =back
1613  
1614 The standard access control configurations for cyrus are
1615  
1616 =over 4
1617  
1618 =item read = "lrs"
1619  
1620 =item post = "lrsp"
1621  
1622 =item append = "lrsip"
1623  
1624 =item write = "lrswipcd"
1625  
1626 =item all = "lrswipcda"
1627  
1628 =back
1629  
1630 Examples:
1631  
1632 # Get full access for user 'joe' on his own folder
1633 $IMAP->setacl('user.joe', 'joe', 'lrswipcda') || die "IMAP error: $@";
1634 # Remove write, insert, post, create, delete access for user 'andrew'
1635 $IMAP->setacl('user.joe', 'andrew', '-wipcd') || die "IMAP error: $@";
1636 # Add lookup, read, keep unseen information for user 'paul'
1637 $IMAP->setacl('user.joe', 'paul', '+lrs') || die "IMAP error: $@";
1638  
1639 =cut
1640 sub setacl {
1641 my $Self = shift;
1642 $Self->_require_capability('acl') || return undef;
1643 return $Self->_imap_cmd("setacl", 0, "acl", $Self->_fix_folder_name(+shift), @_);
1644 }
1645  
1646 =item I<getacl($FolderName)>
1647  
1648 Perform the IMAP 'getacl' command to get the access control list
1649 details of a folder/mailbox. See RFC 4314 for more details on the IMAP
1650 ACL extension. Returns an array of pairs. Each pair is
1651 a username followed by the access rights for that user. See B<setacl>
1652 for more information on access rights.
1653  
1654 Examples:
1655  
1656 my $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
1657 $Rights = [
1658 'joe', 'lrs',
1659 'andrew', 'lrswipcda'
1660 ];
1661  
1662 $IMAP->setacl('user.joe', 'joe', 'lrswipcda') || die "IMAP error : $@";
1663 $IMAP->setacl('user.joe', 'andrew', '-wipcd') || die "IMAP error : $@";
1664 $IMAP->setacl('user.joe', 'paul', '+lrs') || die "IMAP error : $@";
1665  
1666 $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
1667 $Rights = [
1668 'joe', 'lrswipcd',
1669 'andrew', 'lrs',
1670 'paul', 'lrs'
1671 ];
1672  
1673 =cut
1674 sub getacl {
1675 my $Self = shift;
1676 $Self->_require_capability('acl') || return undef;
1677 return $Self->_imap_cmd("getacl", 0, "acl", $Self->_fix_folder_name(+shift), @_);
1678 }
1679  
1680 =item I<deleteacl($FolderName, $Username)>
1681  
1682 Perform the IMAP 'deleteacl' command to delete all access
1683 control information for the given user on the given folder. See B<setacl>
1684 for more information on access rights.
1685  
1686 Examples:
1687  
1688 my $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
1689 $Rights = [
1690 'joe', 'lrswipcd',
1691 'andrew', 'lrs',
1692 'paul', 'lrs'
1693 ];
1694  
1695 # Delete access information for user 'andrew'
1696 $IMAP->deleteacl('user.joe', 'andrew') || die "IMAP error : $@";
1697  
1698 $Rights = $IMAP->getacl('user.joe') || die "IMAP error : $@";
1699 $Rights = [
1700 'joe', 'lrswipcd',
1701 'paul', 'lrs'
1702 ];
1703  
1704 =cut
1705 sub deleteacl {
1706 my $Self = shift;
1707 $Self->_require_capability('acl') || return undef;
1708 return $Self->_imap_cmd("deleteacl", 0, "", $Self->_fix_folder_name(+shift), @_);
1709 }
1710  
1711 sub myrights {
1712 my $Self = shift;
1713 $Self->_require_capability('acl') || return undef;
1714 return $Self->_imap_cmd("myrights", 0, "myrights", $Self->_fix_folder_name(+shift), @_);
1715 }
1716  
1717 =item I<setquota($FolderName, $QuotaDetails)>
1718  
1719 Perform the IMAP 'setquota' command to set the usage quota
1720 details of a folder/mailbox. See RFC 2087 for details of the IMAP
1721 quota extension. $QuotaDetails is a bracketed list of limit item/value
1722 pairs which represent a particular type of limit and the value to set
1723 it to. Current limits are:
1724  
1725 =over 4
1726  
1727 =item STORAGE - Sum of messages' RFC822.SIZE, in units of 1024 octets
1728  
1729 =item MESSAGE - Number of messages
1730  
1731 =back
1732  
1733 Examples:
1734  
1735 # Set maximum size of folder to 50M and 1000 messages
1736 $IMAP->setquota('user.joe', '(storage 50000)') || die "IMAP error: $@";
1737 $IMAP->setquota('user.john', '(messages 1000)') || die "IMAP error: $@";
1738 # Remove quotas
1739 $IMAP->setquota('user.joe', '()') || die "IMAP error: $@";
1740  
1741 =cut
1742 sub setquota {
1743 my $Self = shift;
1744 $Self->_require_capability('quota') || return undef;
1745 return $Self->_imap_cmd("setquota", 0, "", $Self->_fix_folder_name(+shift), @_);
1746 }
1747  
1748 =item I<getquota($FolderName)>
1749  
1750 Perform the standard IMAP 'getquota' command to get the quota
1751 details of a folder/mailbox. See RFC 2087 for details of the IMAP
1752 quota extension. Returns an array reference to quota limit triplets.
1753 Each triplet is made of: limit item, current value, maximum value.
1754  
1755 Note that this only returns the quota for a folder if it actually
1756 has had a quota set on it. It's possible that a parent folder
1757 might have a quota as well which affects sub-folders. Use the
1758 getquotaroot to find out if this is true.
1759  
1760 Examples:
1761  
1762 my $Result = $IMAP->getquota('user.joe') || die "IMAP error: $@";
1763 $Result = [
1764 'STORAGE', 31, 50000,
1765 'MESSAGE', 5, 1000
1766 ];
1767  
1768 =cut
1769 sub getquota {
1770 my $Self = shift;
1771 $Self->_require_capability('quota') || return undef;
1772 my $Folder = $Self->_fix_folder_name(+shift);
1773 my @Res = $Self->_imap_cmd("getquota", 0, "quota", $Folder, @_);
1774 return (ref($Res[0]) eq 'HASH') ? @{$Res[0]->{$Folder}} : @Res;
1775 }
1776  
1777 =item I<getquotaroot($FolderName)>
1778  
1779 Perform the IMAP 'getquotaroot' command to get the quota
1780 details of a folder/mailbox and possible root quota as well.
1781 See RFC 2087 for details of the IMAP
1782 quota extension. The result of this command is a little complex.
1783 Unfortunately it doesn't map really easily into any structure
1784 since there are several different responses.
1785  
1786 Basically it's a hash reference. The 'quotaroot' item is the
1787 response which lists the root quotas that apply to the given
1788 folder. The first item is the folder name, and the remaining
1789 items are the quota root items. There is then a hash item
1790 for each quota root item. It's probably easiest to look at
1791 the example below.
1792  
1793 Examples:
1794  
1795 my $Result = $IMAP->getquotaroot('user.joe.blah') || die "IMAP error: $@";
1796 $Result = {
1797 'quotaroot' => [
1798 'user.joe.blah', 'user.joe', ''
1799 ],
1800 'user.joe' => [
1801 'STORAGE', 31, 50000,
1802 'MESSAGES', 5, 1000
1803 ],
1804 '' => [
1805 'MESSAGES', 3498, 100000
1806 ]
1807 };
1808  
1809 =cut
1810 sub getquotaroot {
1811 my $Self = shift;
1812 $Self->_require_capability('quota') || return undef;
1813 return $Self->_imap_cmd("getquotaroot", 0, "quota", $Self->_fix_folder_name(+shift), @_);
1814 }
1815  
1816 =item I<message_count($FolderName)>
1817  
1818 Return the number of messages in a folder. See also C<status()> for getting
1819 more information about messages in a folder.
1820  
1821 =cut
1822 sub message_count {
1823 my $Self = shift;
1824 my $Res = $Self->status(+shift, '(messages)') || return undef;
1825 return $Res->{messages};
1826 }
1827  
1828 =item I<status($FolderName, $StatusList)>
1829  
1830 Perform the standard IMAP 'status' command to retrieve status information about
1831 a folder/mailbox.
1832  
1833 The $StatusList is a bracketed list of folder items to obtain the status of.
1834 Can contain: messages, recent, uidnext, uidvalidity, unseen.
1835  
1836 The return value is a hash reference of lc(status-item) => value.
1837  
1838 Examples:
1839  
1840 my $Res = $IMAP->status('inbox', '(MESSAGES UNSEEN)');
1841  
1842 $Res = {
1843 'messages' => 8,
1844 'unseen' => 2
1845 };
1846  
1847 =cut
1848 sub status {
1849 my $Self = shift;
1850 return $Self->_imap_cmd("status", 0, "status", $Self->_fix_folder_name(+shift), +shift);
1851 }
1852  
1853 =item I<multistatus($StatusList, @FolderNames)>
1854  
1855 Performs many IMAP 'status' commands on a list of folders. Sends all the
1856 commands at once and wait for responses. This speeds up latency issues.
1857  
1858 Returns a hash ref of folder name => status results.
1859  
1860 If an error occurs, the annotation result is a scalar ref to the completion
1861 response string (eg 'bad', 'no', etc)
1862  
1863 =cut
1864 sub multistatus {
1865 my ($Self, $Items, @FolderList) = @_;
1866  
1867 # Send all commands at once
1868 my $CmdBuf = "";
1869 my $FirstId = $Self->{CmdId};
1870 $Items = ref($Items) ? $Self->_send_data({}, "", $Items) : " " . $Items;
1871  
1872 for (@FolderList) {
1873 $CmdBuf .= $Self->{CmdId}++ . " status " . ${_quote($Self->_fix_folder_name($_))} . $Items . LB;
1874 }
1875 $Self->_imap_socket_out($CmdBuf);
1876  
1877 # Parse responses
1878 my %Resp;
1879 $Self->{CmdId} = $FirstId;
1880 for (@FolderList) {
1881 my ($CompletionResp, $DataResp) = $Self->_parse_response("status");
1882 $Resp{$_} = ref($DataResp) ? $DataResp : \$CompletionResp;
1883 $Self->{CmdId}++;
1884 }
1885  
1886 return \%Resp;
1887 }
1888  
1889 =item I<getannotation($FolderName, $Entry, $Attribute)>
1890  
1891 Perform the IMAP 'getannotation' command to get the annotation(s)
1892 for a mailbox. See imap-annotatemore extension for details.
1893  
1894 Examples:
1895  
1896 my $Result = $IMAP->getannotation('user.joe.blah', '/*' '*') || die "IMAP error: $@";
1897 $Result = {
1898 'user.joe.blah' => {
1899 '/vendor/cmu/cyrus-imapd/size' => {
1900 'size.shared' => '5',
1901 'content-type.shared' => 'text/plain',
1902 'value.shared' => '19261'
1903 },
1904 '/vendor/cmu/cyrus-imapd/lastupdate' => {
1905 'size.shared' => '26',
1906 'content-type.shared' => 'text/plain',
1907 'value.shared' => '26-Mar-2004 13:31:56 -0800'
1908 },
1909 '/vendor/cmu/cyrus-imapd/partition' => {
1910 'size.shared' => '7',
1911 'content-type.shared' => 'text/plain',
1912 'value.shared' => 'default'
1913 }
1914 }
1915 };
1916  
1917 =cut
1918 sub getannotation {
1919 my $Self = shift;
1920 $Self->_require_capability('annotatemore') || return undef;
1921 return $Self->_imap_cmd("getannotation", 0, "annotation", $Self->_fix_folder_name(+shift, Wildcard => 1), { Quote => $_[0] }, { Quote => $_[1] });
1922 }
1923  
1924 =item I<getmetadata($FolderName, [ \%Options ], @Entries)>
1925  
1926 Perform the IMAP 'getmetadata' command to get the metadata items
1927 for a mailbox. See RFC 5464 for details.
1928  
1929 If $Options is passed, it is a hashref of options to set.
1930  
1931 If foldername is the empty string, gets server annotations
1932  
1933 Examples:
1934  
1935 my $Result = $IMAP->getmetadata('user.joe.blah', {depth => 'infinity'}, '/shared') || die "IMAP error: $@";
1936 $Result = {
1937 'user.joe.blah' => {
1938 '/shared/vendor/cmu/cyrus-imapd/size' => '19261',
1939 '/shared/vendor/cmu/cyrus-imapd/lastupdate' => '26-Mar-2004 13:31:56 -0800',
1940 '/shared/vendor/cmu/cyrus-imapd/partition' => 'default',
1941 }
1942 };
1943  
1944 my $Result = $IMAP->getmetadata('', "/shared/comment");
1945 $Result => {
1946 '' => {
1947 '/shared/comment' => "Shared comment",
1948 }
1949 };
1950  
1951 =cut
1952 sub getmetadata {
1953 my $Self = shift;
1954 $Self->_require_capability('metadata') || return undef;
1955  
1956 # First arg is folder name
1957 my @Args = $Self->_fix_folder_name(+shift);
1958 # Next is optional hash of options
1959 push @Args, [%{ +shift }] if ref($_[0]) eq 'HASH';
1960  
1961 return $Self->_imap_cmd("getmetadata", 0, "metadata", @Args, { Quote => [ @_ ] });
1962 }
1963  
1964 =item I<multigetmetadata(\@Entries, @FolderNames)>
1965  
1966 Performs many IMAP 'getmetadata' commands on a list of folders. Sends
1967 all the commands at once and wait for responses. This speeds up latency
1968 issues.
1969  
1970 Returns a hash ref of folder name => metadata results.
1971  
1972 If an error occurs, the annotation result is a scalar ref to the completion
1973 response string (eg 'bad', 'no', etc)
1974  
1975 =cut
1976 sub multigetmetadata {
1977 my ($Self, $Entries, @FolderList) = @_;
1978 $Self->_require_capability('metadata') || return undef;
1979  
1980 # Send all commands at once
1981 my $FirstId = $Self->{CmdId};
1982 for (@FolderList) {
1983 $Self->_send_cmd("getmetadata", $Self->_fix_folder_name($_, Wildcard => 1), { Quote => ref($Entries) ? $Entries : [ $Entries ] });
1984 $Self->{CmdId}++;
1985 }
1986  
1987 # Parse responses
1988 my %Resp;
1989 $Self->{CmdId} = $FirstId;
1990 for (@FolderList) {
1991 my ($CompletionResp, $DataResp) = $Self->_parse_response("metadata");
1992 $Resp{$_} = ref($DataResp) ?
1993 (ref($Entries) ? $DataResp->{$_} : $DataResp->{$_}->{$Entries}) :
1994 \$CompletionResp;
1995 $Self->{CmdId}++;
1996 }
1997  
1998 return \%Resp;
1999 }
2000  
2001 =item I<setannotation($FolderName, $Entry, [ $Attribute, $Value ])>
2002  
2003 Perform the IMAP 'setannotation' command to get the annotation(s)
2004 for a mailbox. See imap-annotatemore extension for details.
2005  
2006 Examples:
2007  
2008 my $Result = $IMAP->setannotation('user.joe.blah', '/comment', [ 'value.priv' 'A comment' ])
2009 || die "IMAP error: $@";
2010  
2011 =cut
2012 sub setannotation {
2013 my $Self = shift;
2014 $Self->_require_capability('annotatemore') || return undef;
2015 return $Self->_imap_cmd("setannotation", 0, "annotation", $Self->_fix_folder_name(+shift, Wildcard => 1), { Quote => $_[0] }, { Quote => $_[1] });
2016 }
2017  
2018 =item I<setmetadata($FolderName, $Name, $Value, $Name2, $Value2)>
2019  
2020 Perform the IMAP 'setmetadata' command. See RFC 5464 for details.
2021  
2022 Examples:
2023  
2024 my $Result = $IMAP->setmetadata('user.joe.blah', '/comment', 'A comment')
2025 || die "IMAP error: $@";
2026  
2027 =cut
2028 sub setmetadata {
2029 my $Self = shift;
2030 $Self->_require_capability('metadata') || return undef;
2031 return $Self->_imap_cmd("setmetadata", 0, "metadata", $Self->_fix_folder_name(+shift, Wildcard => 1), { Quote => [ @_ ] });
2032 }
2033  
2034 =item I<close()>
2035  
2036 Perform the standard IMAP 'close' command to expunge deleted messages
2037 from the current folder and return to the Authenticated state.
2038  
2039 =cut
2040 sub close {
2041 my $Self = shift;
2042 $Self->_imap_cmd("close", 0, "", @_) || return undef;
2043 $Self->state(Authenticated);
2044 }
2045  
2046 =item I<idle(\&Callback, [ $Timeout ])>
2047  
2048 Perform an IMAP idle call. Call given callback for each IDLE event
2049 received.
2050  
2051 If the callback returns 0, the idle continues. If the callback returns 1,
2052 the idle is finished and this call returns.
2053  
2054 If no timeout is passed, will continue to idle until the callback returns
2055 1 or the server disconnects.
2056  
2057 If a timeout is passed (including a 0 timeout), the call will return if
2058 no events are received within the given time. It will return the result
2059 of the DONE command, and set $Self->get_response_code('timeout') to true.
2060  
2061 If the server closes the connection with a "bye" response, it will
2062 return undef and $@ =~ /bye/ will be true with the remainder of the bye
2063 line following.
2064  
2065 =cut
2066 sub idle {
2067 my ($Self, $Callback, $Timeout) = @_;
2068  
2069 # Create a closure to handle the idle semantics that runs
2070 # between sending the command and parsing the tagged
2071 # response (that only appears after sending DONE)
2072 my $PostCommand = sub {
2073 local $Self->{Timeout} = $Timeout if $Timeout;
2074  
2075 $Self->{ReadLine} = undef;
2076  
2077 my $Resp = $Self->_next_atom();
2078 my ($Text) = @{$Self->_remaining_atoms()};
2079 if (!$Resp || !$Text || $Resp ne '+' || $Text ne 'idling') {
2080 die "IMAPTalk: Did not get '+ idling' response";
2081 }
2082  
2083 # Special case 0 timeout
2084 if (defined $Timeout && $Timeout == 0) {
2085 $Self->{Cache}->{timeout} = 1;
2086 goto DoneIdle;
2087 }
2088  
2089 # If callback returns true, set $Exit to exit loop
2090 my $Exit = 0;
2091 my $WrapCallback = sub { $Exit = $Callback->(@_); };
2092 my %ParseCB = map { $_ => $WrapCallback } qw(exists recent expunge fetch);
2093  
2094 while (!$Exit) {
2095 eval {
2096 $Self->_parse_response(\%ParseCB, { IdleResponse => 1 });
2097 };
2098 if ($@) {
2099 if ($@ =~ /timed out/) {
2100 $Self->{Cache}->{timeout} = 1;
2101 goto DoneIdle;
2102  
2103 } elsif ($@ =~ /closed by host/) {
2104 die "IMAPTalk: bye: " . $Self->get_response_code('bye');
2105  
2106 } else {
2107 die $@;
2108 }
2109 }
2110 }
2111  
2112 # Send DONE, and then fallout to parse response
2113 DoneIdle:
2114 $Self->_imap_socket_out("DONE" . LB);
2115 };
2116  
2117 my %ParseMode = (PostCommand => $PostCommand);
2118 return $Self->_imap_cmd(\%ParseMode, 'idle', 0, '');
2119 }
2120  
2121  
2122 =back
2123 =cut
2124  
2125 =head1 IMAP MESSAGE COMMAND METHODS
2126  
2127 =over 4
2128 =cut
2129  
2130 =item I<fetch([ \%ParseMode ], $MessageIds, $MessageItems)>
2131  
2132 Perform the standard IMAP 'fetch' command to retrieve the specified message
2133 items from the specified message IDs.
2134  
2135 The first parameter can be an optional hash reference that overrides
2136 particular parse mode parameters just for this fetch. See C<parse_mode>
2137 for possible keys.
2138  
2139 C<$MessageIds> can be one of two forms:
2140  
2141 =over 4
2142  
2143 =item 1.
2144  
2145 A text string with a comma separated list of message ID's or message ranges
2146 separated by colons. A '*' represents the highest message number.
2147  
2148 Examples:
2149  
2150 =over 4
2151  
2152 =item * '1' - first message
2153  
2154 =item * '1,2,5'
2155  
2156 =item * '1:*' - all messages
2157  
2158 =item * '1,3:*' - all but message 2
2159  
2160 =back
2161  
2162 Note that , separated lists and : separated ranges can be mixed, but to
2163 make sure a certain hack works, if a '*' is used, it must be the last
2164 character in the string.
2165  
2166 =item 2.
2167  
2168 An array reference with a list of message ID's or ranges. The array contents
2169 are C<join(',', ...)>ed together.
2170  
2171 =back
2172  
2173 Note: If the C<uid()> state has been set to true, then all message ID's
2174 must be message UIDs.
2175  
2176 C<$MessageItems> can be one of, or a bracketed list of:
2177  
2178 =over 4
2179  
2180 =item * uid
2181  
2182 =item * flags
2183  
2184 =item * internaldate
2185  
2186 =item * envelope
2187  
2188 =item * bodystructure
2189  
2190 =item * body
2191  
2192 =item * body[section]<partial>
2193  
2194 =item * body.peek[section]<partial>
2195  
2196 =item * rfc822
2197  
2198 =item * rfc822.header
2199  
2200 =item * rfc822.size
2201  
2202 =item * rfc822.text
2203  
2204 =item * fast
2205  
2206 =item * all
2207  
2208 =item * full
2209  
2210 =back
2211  
2212 It would be a good idea to see RFC 3501 for what all these means.
2213  
2214 Examples:
2215  
2216 my $Res = $IMAP->fetch('1:*', 'rfc822.size');
2217 my $Res = $IMAP->fetch([1,2,3], '(bodystructure envelope)');
2218  
2219 Return results:
2220  
2221 The results returned by the IMAP server are parsed into a Perl structure.
2222 See the section B<FETCH RESULTS> for all the interesting details.
2223  
2224 Note that message can disappear on you, so you may not get back
2225 all the entries you expect in the hash
2226  
2227 There is one piece of magic. If your request is for a single uid,
2228 (eg "123"), and no data is return, we return undef, because it's
2229 easier to handle as an error condition.
2230  
2231 =cut
2232 sub fetch {
2233 my $Self = shift;
2234  
2235 my $ParseMode = ref($_[0]) eq 'HASH' ? shift : {};
2236  
2237 # Are we fetching one uid
2238 my $FetchOne = !ref($_[0]) && $_[0] =~ /^\d+$/ && $_[0];
2239  
2240 # Clear any existing fetch responses and call the fetch command
2241 $Self->{Responses}->{fetch} = undef;
2242 my $FetchRes = $Self->_imap_cmd($ParseMode, "fetch", 1, "fetch", _fix_message_ids(+shift), @_);
2243  
2244 # Single message fetch with no data returns
2245 my $NoFetchData = ref($FetchRes) && !%$FetchRes;
2246 if ($NoFetchData && $FetchOne) {
2247 $Self->{LastError} = $@ = "Fetch of message uid $FetchOne failed. Message deleted by POP or other IMAP connection.";
2248 return undef;
2249 }
2250  
2251 # Multi message fetch with no data
2252 return {} if $NoFetchData;
2253  
2254 # Return data returned
2255 return $FetchRes;
2256 }
2257  
2258 =item I<copy($MsgIds, $ToFolder)>
2259  
2260 Perform standard IMAP copy command to copy a set of messages from one folder
2261 to another.
2262  
2263 =cut
2264 sub copy {
2265 my $Self = shift;
2266 my $Uids = _fix_message_ids(+shift);
2267 my $FolderName = $Self->_fix_folder_name(+shift);
2268 $Self->cb_folder_changed($FolderName);
2269 return $Self->_imap_cmd("copy", 1, "", $Uids, $FolderName, @_);
2270 }
2271  
2272 =item I<append($FolderName, optional $MsgFlags, optional $MsgDate, $MessageData)>
2273  
2274 Perform standard IMAP append command to append a new message into a folder.
2275  
2276 The $MessageData to append can either be a Perl scalar containing the data,
2277 or a file handle to read the data from. In each case, the data must be in
2278 proper RFC 822 format with \r\n line terminators.
2279  
2280 Any optional fields not needed should be removed, not left blank.
2281  
2282 Examples:
2283  
2284 # msg.txt should have \r\n line terminators
2285 open(F, "msg.txt");
2286 $IMAP->append('inbox', \*F);
2287  
2288 my $MsgTxt =<<MSG;
2289 From: blah\@xyz.com
2290 To: whoever\@whereever.com
2291 ...
2292 MSG
2293  
2294 $MsgTxt =~ s/\n/\015\012/g;
2295 $IMAP->append('inbox', { Literal => $MsgTxt });
2296  
2297 =cut
2298 sub append {
2299 my $Self = shift;
2300 my $FolderName = $Self->_fix_folder_name(+shift);
2301 $Self->cb_folder_changed($FolderName);
2302 return $Self->_imap_cmd("append", 0, "", $FolderName, @_);
2303 }
2304  
2305 =item I<search($MsgIdSet, @SearchCriteria)>
2306  
2307 Perform standard IMAP search command. The result is an array reference to a list
2308 of message IDs (or UIDs if in Uid mode) of messages that are in the $MsgIdSet
2309 and also meet the search criteria.
2310  
2311 @SearchCriteria is a list of search specifications, for example to look for
2312 ASCII messages bigger than 2000 bytes you would set the list to be:
2313  
2314 my @SearchCriteria = ('CHARSET', 'US-ASCII', 'LARGER', '2000');
2315  
2316 Examples:
2317  
2318 my $Res = $IMAP->search('1:*', 'NOT', 'DELETED');
2319 $Res = [ 1, 2, 5 ];
2320  
2321 =cut
2322 sub search {
2323 return (+shift)->_imap_cmd("search", 1, "search", _fix_message_ids(+shift), @_);
2324 }
2325  
2326 =item I<store($MsgIdSet, $FlagOperation, $Flags)>
2327  
2328 Perform standard IMAP store command. Changes the flags associated with a
2329 set of messages.
2330  
2331 Examples:
2332  
2333 $IMAP->store('1:*', '+flags', '(\\deleted)');
2334 $IMAP->store('1:*', '-flags.silent', '(\\read)');
2335  
2336 =cut
2337 sub store {
2338 my $Self = shift;
2339 $Self->cb_folder_changed($Self->{CurrentFolder});
2340 return $Self->_imap_cmd("store", 1, "fetch", _fix_message_ids(+shift), @_);
2341 }
2342  
2343 =item I<expunge()>
2344  
2345 Perform standard IMAP expunge command. This actually deletes any messages
2346 marked as deleted.
2347  
2348 =cut
2349 sub expunge {
2350 my $Self = shift;
2351 $Self->cb_folder_changed($Self->{CurrentFolder});
2352 return $Self->_imap_cmd("expunge", 0, "", @_);
2353 }
2354  
2355 =item I<uidexpunge($MsgIdSet)>
2356  
2357 Perform IMAP uid expunge command as per RFC 2359.
2358  
2359 =cut
2360 sub uidexpunge {
2361 my $Self = shift;
2362 $Self->cb_folder_changed($Self->{CurrentFolder});
2363 return $Self->_imap_cmd("uid expunge", 0, "", _fix_message_ids(+shift));
2364 }
2365  
2366 =item I<sort($SortField, $CharSet, @SearchCriteria)>
2367  
2368 Perform extension IMAP sort command. The result is an array reference to a list
2369 of message IDs (or UIDs if in Uid mode) in sorted order.
2370  
2371 It would probably be a good idea to look at the sort RFC 5256 details at
2372 somewhere like : http://www.ietf.org/rfc/rfc5256.txt
2373  
2374 Examples:
2375  
2376 my $Res = $IMAP->sort('(subject)', 'US-ASCII', 'NOT', 'DELETED');
2377 $Res = [ 5, 2, 3, 1, 4 ];
2378  
2379 =cut
2380 sub sort {
2381 return (+shift)->_imap_cmd("sort", 1, "sort", @_);
2382 }
2383  
2384 =item I<thread($ThreadType, $CharSet, @SearchCriteria)>
2385  
2386 Perform extension IMAP thread command. The $ThreadType should be one
2387 of 'REFERENCES' or 'ORDEREDSUBJECT'. You should check the C<capability()>
2388 of the server to see if it supports one or both of these.
2389  
2390 Examples
2391  
2392 my $Res = $IMAP->thread('REFERENCES', 'US-ASCII', 'NOT', 'DELETED');
2393 $Res = [ [10, 15, 20], [11], [ [ 12, 16 ], [13, 17] ];
2394  
2395 =cut
2396 sub thread {
2397 return (+shift)->_imap_cmd("thread", 1, "thread", @_);
2398 }
2399  
2400 =item I<fetch_flags($MessageIds)>
2401  
2402 Perform an IMAP 'fetch flags' command to retrieve the specified flags
2403 for the specified messages.
2404  
2405 This is just a special fast path version of C<fetch>.
2406  
2407 =cut
2408 sub fetch_flags {
2409 my $Self = shift;
2410  
2411 my $Cmd = $Self->{Uid} ? 'uid fetch' : 'fetch';
2412 $Self->_send_cmd($Cmd, _fix_message_ids(+shift), '(flags)');
2413  
2414 my $Tag = '';
2415 my ($MsgId, $Resp, %FetchRes);
2416  
2417 while (1) {
2418 local $_ = $Self->_imap_socket_read_line();
2419  
2420 ($Tag, $MsgId, $Resp, $_) = (/^(\S+) (\S+) (\S+)(?: \((.*)\))?/)
2421 or die "IMAPTalk: Expected tagged response, got $_";
2422 last if $Tag eq $Self->{CmdId};
2423 $Resp = lc $Resp;
2424  
2425 if ($Tag eq '*' and ($MsgId =~ m/\D/ or $UntaggedResponses{$Resp})) {
2426 # ignore untagged response
2427 next;
2428 }
2429  
2430 # only want FETCH responses
2431 if ($Resp eq 'fetch') {
2432 my ($Uid) = /UID (\d+)/i;
2433 my ($Flags) = /FLAGS \(([^)]*)\)/i;
2434  
2435 if (!defined $Uid || !defined $Flags) {
2436 $@ = "Unexpected response line. tag=$Tag, msgid=$MsgId, line=$_";
2437 return undef;
2438 }
2439  
2440 $FetchRes{$Uid} = { uid => $Uid, flags => [ split ' ', $Flags ] };
2441  
2442 # Unknown unexpected response line
2443 } else {
2444 $@ = "Unexpected response line. tag=$Tag, msgid=$MsgId, respond=$Resp, line=$_";
2445 return undef;
2446 }
2447 }
2448  
2449 return \%FetchRes;
2450 }
2451  
2452 =item I<fetch_meta($MessageIds, @MetaItems)>
2453  
2454 Perform an IMAP 'fetch' command to retrieve the specified meta
2455 items. These must be simple items that return only atoms
2456 (eg no flags, bodystructure, body, envelope, etc)
2457  
2458 This is just a special fast path version of C<fetch>.
2459  
2460 =cut
2461 sub fetch_meta {
2462 my $Self = shift;
2463  
2464 my $Cmd = $Self->{Uid} ? 'uid fetch' : 'fetch';
2465 $Self->_send_cmd($Cmd, _fix_message_ids(+shift), '(' . join(" ", @_) . ')');
2466  
2467 my $Tag = '';
2468 my ($MsgId, $Resp, %FetchRes);
2469  
2470 while (1) {
2471 local $_ = $Self->_imap_socket_read_line();
2472  
2473 ($Tag, $MsgId, $Resp, $_) = (/^(\S+) (\S+) (\S+)(?: \((.*)\))?/)
2474 or die "IMAPTalk: Expected tagged meta list, got $_";
2475 last if $Tag eq $Self->{CmdId};
2476  
2477 if ($Tag eq '*' and ($MsgId =~ m/\D/ or $UntaggedResponses{lc $Resp})) {
2478 # ignore untagged response
2479 next;
2480 }
2481  
2482 $_ = '' unless defined $_;
2483  
2484 # Fetch can always return flags result, need to handle that
2485 my %Items = /\bflags\b/i ? m{(\S+) ([^(]\S*|\([^)]*\)) ?}g : split(' ', $_);
2486 my $Uid = $Items{UID};
2487  
2488 unless (defined $Uid) {
2489 $@ = "Unexpected response line: $_";
2490 return undef;
2491 }
2492  
2493 $FetchRes{$Uid} = { map { lc($_) => $Items{$_} } keys %Items };
2494 }
2495  
2496 return \%FetchRes;
2497 }
2498  
2499 sub move {
2500 my $Self = shift;
2501 my $Uids = _fix_message_ids(+shift);
2502 my $FolderName = $Self->_fix_folder_name(+shift);
2503 $Self->cb_folder_changed($FolderName);
2504 return $Self->_imap_cmd("move", 1, "", $Uids, $FolderName, @_);
2505 }
2506  
2507 sub xmove {
2508 my $Self = shift;
2509 my $Uids = _fix_message_ids(+shift);
2510 my $FolderName = $Self->_fix_folder_name(+shift);
2511 $Self->cb_folder_changed($FolderName);
2512 return $Self->_imap_cmd("xmove", 1, "", $Uids, $FolderName, @_);
2513 }
2514  
2515 =back
2516 =cut
2517  
2518 =head1 IMAP CYRUS EXTENSION METHODS
2519  
2520 Methods provided by extensions to the cyrus IMAP server
2521  
2522 B<Note:> In all cases where a folder name is used,
2523 the folder name is first manipulated according to the current root folder
2524 prefix as described in C<set_root_folder()>.
2525  
2526 =over 4
2527 =cut
2528  
2529 =item I<xrunannotator($MessageIds)>
2530  
2531 Run the xannotator command on the given message id's
2532  
2533 =cut
2534 sub xrunannotator {
2535 my $Self = shift;
2536 return $Self->_imap_cmd("xrunannotator", 1, "fetch", _fix_message_ids(+shift), @_);
2537 }
2538  
2539 =item I<xconvfetch($CIDs, $ChangedSince, $Items)>
2540  
2541 Use the server XCONVFETCH command to fetch information about messages
2542 in a conversation.
2543  
2544 CIDs can be a single CID or an array ref of CIDs.
2545  
2546 my $Res = $IMAP->xconvfetch('2fc2122a109cb6c8', 0, '(uid cid envelope)')
2547 $Res = {
2548 state => { CID => [ HighestModSeq ], ... }
2549 folders => [ [ FolderName, UidValidity ], ..., ],
2550 found => [ [ FolderIndex, Uid, { Details } ], ... ],
2551 }
2552  
2553 Note: FolderIndex is an integer index into the folders list
2554  
2555 =cut
2556 sub xconvfetch {
2557 my $Self = shift;
2558 my $CID = shift;
2559  
2560 my %Results;
2561 $Results{found} = \my @Fetch;
2562 $Results{folders} = \my @Folders;
2563  
2564 my %FolderMap;
2565  
2566 my %Callbacks = (
2567 xconvmeta => sub {
2568 my ($CID, $Data) = @{$_[1]};
2569 my $Res = _parse_list_to_hash($Data);
2570 $Results{state}{$CID} = [ $Res->{modseq} ];
2571 },
2572  
2573 fetch => sub {
2574 my (undef, $Fetch) = @_;
2575 my ($FolderName, $UidValidity, $Uid) = delete @$Fetch{qw(folder uidvalidity uid)};
2576 $FolderName = $Self->_unfix_folder_name($FolderName);
2577 if (!exists $FolderMap{$FolderName}) {
2578 my $FolderIndex = scalar @Folders;
2579 push @Folders, [ $FolderName, $UidValidity ];
2580 $FolderMap{$FolderName} = $FolderIndex;
2581 }
2582 push @Fetch, [ $FolderMap{$FolderName}, int($Uid), $Fetch ];
2583 }
2584 );
2585  
2586 $Self->_imap_cmd("xconvfetch", 0, \%Callbacks, $CID, @_)
2587 || return undef;
2588  
2589 return \%Results;
2590 }
2591  
2592 =item I<xconvmeta($CIDs, $Items)>
2593  
2594 Use the server XCONVMETA command to fetch information about
2595 a conversation.
2596  
2597 CIDs can be a single CID or an array ref of CIDs.
2598  
2599 my $Res = $IMAP->xconvmeta('2fc2122a109cb6c8', '(senders exists unseen)')
2600 $Res = {
2601 CID1 => { senders => { name => ..., email => ... }, exists => ..., unseen => ..., ... },
2602 CID2 => { ... },
2603 }
2604  
2605 =cut
2606 sub xconvmeta {
2607 my ($Self, $CIDs, $Args) = @_;
2608  
2609 # Fix folder names in passed folderexists and folderunseen arguments
2610 $Self->_find_arg($Args, 'folderexists', sub { $_ = $Self->_fix_folder_name($_) for @$_; });
2611 $Self->_find_arg($Args, 'folderunseen', sub { $_ = $Self->_fix_folder_name($_) for @$_; });
2612  
2613 my %Results;
2614  
2615 my %Callbacks = (
2616 xconvmeta => sub {
2617 my (undef, $Data) = @_;
2618 my $Res = _parse_list_to_hash($Data->[1]);
2619 my %ResHash;
2620 foreach my $Item (keys %$Res) {
2621 if (lc($Item) eq 'senders') {
2622 $ResHash{senders} = [
2623 map {
2624 _decode_utf8($_->[0]);
2625 {
2626 name => $_->[0],
2627 email => "$_->[2]\@$_->[3]",
2628 }
2629 } @{$Res->{$Item}} ];
2630 }
2631 elsif (lc($Item) eq 'count') {
2632 my %FolderCount = @{$Res->{$Item}};
2633 $ResHash{count} = { map {
2634 $Self->_unfix_folder_name($_) => int($FolderCount{$_})
2635 } keys %FolderCount };
2636 }
2637 elsif (lc($Item) eq 'folderexists') {
2638 my %FolderExists = @{$Res->{$Item}};
2639 $ResHash{folderexists} = { map {
2640 $Self->_unfix_folder_name($_) => int($FolderExists{$_})
2641 } keys %FolderExists };
2642 }
2643 elsif (lc($Item) eq 'folderunseen') {
2644 my %FolderUnseen = @{$Res->{$Item}};
2645 $ResHash{folderunseen} = { map {
2646 $Self->_unfix_folder_name($_) => int($FolderUnseen{$_})
2647 } keys %FolderUnseen };
2648 }
2649 else {
2650 $ResHash{lc($Item)} = int($Res->{$Item} // 0); # numeric
2651 }
2652  
2653 }
2654 $Results{$Data->[0]} = \%ResHash;
2655 },
2656 );
2657  
2658 $Self->_imap_cmd("xconvmeta", 0, \%Callbacks, $CIDs, $Args)
2659 || return undef;
2660  
2661 return \%Results;
2662 }
2663  
2664 =item I<xconvsort($Sort, $Window, $Charset, @SearchParams)>
2665  
2666 Use the server XCONVSORT command to fetch exemplar conversation
2667 messages in a mailbox.
2668  
2669 my $Res = $IMAP->xconvsort( [ qw(reverse arrival) ], [ 'conversations', position => [1, 10] ], 'utf-8', 'ALL')
2670 $Res = {
2671 sort => [ Uid, ... ],
2672 position => N,
2673 highestmodseq => M,
2674 uidvalidity => V,
2675 uidnext => U,
2676 total => R,
2677 }
2678  
2679 =cut
2680 sub xconvsort {
2681 my ($Self, $Sort, $Window, @Search) = @_;
2682  
2683 my %Callbacks = (responseitem => 'sort');
2684 my $Res = $Self->_imap_cmd("xconvsort", 0, \%Callbacks, $Sort, $Window, @Search)
2685 || return undef;
2686  
2687 my %Results;
2688 $Results{'sort'} = $Res if ref($Res);
2689 for (qw(position highestmodseq uidvalidity uidnext total)) {
2690 $Results{$_} = delete $Self->{Cache}->{$_};
2691 }
2692  
2693 return \%Results;
2694 }
2695  
2696 =item I<xconvupdates($Sort, $Window, $Charset, @SearchParams)>
2697  
2698 Use the server XCONVUPDATES command to find changed exemplar
2699 messages
2700  
2701 my $Res = $IMAP->xconvupdates( [ qw(reverse arrival) ], [ 'conversations', changedsince => [ $mod_seq, $uid_next ] ], 'utf-8', 'ALL');
2702 $Res = {
2703 added => [ [ Uid, Pos ], ... ],
2704 removed => [ Uid, ... ],
2705 changed => [ CID, ... ],
2706 highestmodseq => M,
2707 uidvalidity => V,
2708 uidnext => U,
2709 total => R,
2710 }
2711  
2712 =cut
2713 sub xconvupdates {
2714 my ($Self, $Sort, $Window, @Search) = @_;
2715
2716 my %Results;
2717  
2718 my %Callbacks = (
2719 added => sub { $Results{added} = $_[1]; },
2720 removed => sub { $Results{removed} = $_[1]; },
2721 changed => sub { $Results{changed} = $_[1]; },
2722 );
2723  
2724 my $Res = $Self->_imap_cmd("xconvupdates", 0, \%Callbacks, $Sort, $Window, @Search)
2725 || return undef;
2726  
2727 for (qw(highestmodseq uidvalidity uidnext total)) {
2728 $Results{$_} = delete $Self->{Cache}->{$_};
2729 }
2730  
2731 return \%Results;
2732 }
2733  
2734 =item I<xconvmultisort($Sort, $Window, $Charset, @SearchParams)>
2735  
2736 Use the server XCONVMULTISORT command to fetch messages across
2737 all mailboxes
2738  
2739 my $Res = $IMAP->xconvmultisort( [ qw(reverse arrival) ], [ 'conversations', postion => [1,10] ], 'utf-8', 'ALL')
2740 $Res = {
2741 folders => [ [ FolderName, UidValidity ], ... ],
2742 sort => [ FolderIndex, Uid ], ... ],
2743 position => N,
2744 highestmodseq => M,
2745 total => R,
2746 }
2747  
2748 Note: FolderIndex is an integer index into the folders list
2749  
2750 =cut
2751 sub xconvmultisort {
2752 my ($Self, $Sort, $Window, @Search) = @_;
2753  
2754 $Self->_find_arg(\@Search, 'folder', sub { $_ = $Self->_fix_folder_name($_) });
2755 $Self->_find_arg($Window, 'multianchor', sub { $_->[1] = $Self->_fix_folder_name($_->[1]) });
2756  
2757 my ($FolderList, $SortList);
2758  
2759 my %Callbacks = (xconvmulti => sub { ($FolderList, $SortList) = @{$_[1]}; });
2760 my $Res = $Self->_imap_cmd("xconvmultisort", 0, \%Callbacks, $Sort, $Window, @Search)
2761 || return undef;
2762  
2763 $_->[0] = $Self->_unfix_folder_name($_->[0]) for @$FolderList;
2764  
2765 my %Results;
2766 $Results{'folders'} = $FolderList;
2767 $Results{'sort'} = $SortList;
2768 for (qw(position highestmodseq total)) {
2769 $Results{$_} = delete $Self->{Cache}->{$_};
2770 }
2771  
2772 return \%Results;
2773 }
2774  
2775 =item I<xsnippets($Items, $Charset, @SearchParams)>
2776  
2777 Use the server XSNIPPETS command to fetch message search snippets
2778  
2779 my $Res = $IMAP->xsnippets( [ [ FolderName, UidValidity, [ Uid, ... ] ], ... ], 'utf-8', 'ALL')
2780 $Res = {
2781 folders => [ [ FolderName, UidValidity ], ... ],
2782 snippets => [
2783 [ FolderIndex, Uid, Location, Snippet ],
2784 ...
2785 ]
2786 ]
2787  
2788 Note: FolderIndex is an integer index into the folders list
2789  
2790 =cut
2791 sub xsnippets {
2792 my ($Self, $Items, @Search) = @_;
2793  
2794 $Self->_find_arg(\@Search, 'folder', sub { $_ = $Self->_fix_folder_name($_) });
2795  
2796 # Fix folder names passed in items argument
2797 $_->[0] = $Self->_fix_folder_name($_->[0]) for @$Items;
2798  
2799 my %Results;
2800 $Results{snippets} = \my @Snippets;
2801 $Results{folders} = \my @Folders;
2802  
2803 my %FolderMap;
2804  
2805 my %Callbacks = (snippet => sub {
2806 my ($FolderName, $UidValidity, $Uid, $Location, $Snippet) = @{$_[1]};
2807 $FolderName = $Self->_unfix_folder_name($FolderName);
2808 if (!exists $FolderMap{$FolderName}) {
2809 my $FolderIndex = scalar @Folders;
2810 push @Folders, [ $FolderName, $UidValidity ];
2811 $FolderMap{$FolderName} = $FolderIndex;
2812 }
2813 eval { $Snippet = decode("utf-8", $Snippet) };
2814 $Snippet =~ s/\x{fffd}//g; # Remove any bogus replacement chars, ugly display
2815 push @Snippets, [ $FolderMap{$FolderName}, int($Uid), $Location, $Snippet ];
2816 });
2817  
2818 my $Res = $Self->_imap_cmd("xsnippets", 0, \%Callbacks, $Items, @Search)
2819 || return undef;
2820  
2821 return \%Results;
2822 }
2823  
2824 sub xwarmup {
2825 my $Self = shift;
2826 $Self->_find_arg($_[1], 'uids', sub { $_ = _fix_message_ids($_) });
2827 return $Self->_imap_cmd("xwarmup", 0, "", $Self->_fix_folder_name(+shift), @_);
2828 }
2829  
2830 sub xmeid {
2831 my $Self = shift;
2832 my $XMEId = shift || '';
2833 return 1 if ($Self->{CurrentXMEId} || '') eq $XMEId;
2834 $Self->{CurrentXMEId} = $XMEId;
2835 return $Self->_imap_cmd('xmeid', 0, '', $XMEId);
2836 }
2837  
2838 =back
2839 =cut
2840  
2841 =head1 IMAP HELPER FUNCTIONS
2842  
2843 =over 4
2844 =cut
2845  
2846 =item I<get_body_part($BodyStruct, $PartNum)>
2847  
2848 This is a helper function that can be used to further parse the
2849 results of a fetched bodystructure. Given a top level body
2850 structure, and a part number, it returns the reference to
2851 the bodystructure sub part which that part number refers to.
2852  
2853 Examples:
2854  
2855 # Fetch body structure
2856 my $FR = $IMAP->fetch(1, 'bodystructure');
2857 my $BS = $FR->{1}->{bodystructure};
2858  
2859 # Parse further to find particular sub part
2860 my $P12 = $IMAP->get_body_part($BS, '1.2');
2861 $P12->{'IMAP->Partnum'} eq '1.2' || die "Unexpected IMAP part number";
2862  
2863 =cut
2864 sub get_body_part {
2865 my ($BS, $PartNum) = @_;
2866  
2867 my @PartNums = split(/\./, $PartNum);
2868  
2869 # This is a hack for special messages where the first entity
2870 # is a message/rfc822 type. In which case, we have to strip
2871 # the first item
2872 my $IsFirst = 1;
2873  
2874 while (1) {
2875 # Go no further if we found what we want
2876 return $BS
2877 if $BS->{'IMAP-Partnum'} eq $PartNum;
2878  
2879 # Has to have sub-parts, either mime-multipart or rfc822 sub-message
2880 return undef
2881 if (!$BS) ||
2882 (!@PartNums) ||
2883 (!exists $BS->{'MIME-Subparts'} &&
2884 !exists $BS->{'Message-Bodystructure'});
2885  
2886 # Get sub-part
2887 if (exists $BS->{'Message-Bodystructure'}) {
2888 $BS = $BS->{'Message-Bodystructure'};
2889 shift(@PartNums) if $IsFirst;
2890 }
2891 $BS = ($BS->{'MIME-Subparts'} || [])->[shift(@PartNums)-1] || $BS;
2892 $IsFirst = 0;
2893 }
2894 }
2895  
2896 =item I<find_message($BodyStruct)>
2897  
2898 This is a helper function that can be used to further parse the results of
2899 a fetched bodystructure. It returns a hash reference with the following
2900 items.
2901  
2902 text => $best_text_part
2903 html => $best_html_part (optional)
2904 textlist => [ ... text/html (if no alt text bits)/image (if inline) parts ... ]
2905 htmllist => [ ... text (if no alt html bits)/html/image (if inline) parts ... ]
2906 att => [ {
2907 bs => $part, text => 0/1, html => 0/1, msg => 1/0,
2908 }, { ... }, ... ]
2909  
2910 For instance, consider a message with text and html pages that's then
2911 gone through a list software manager that attaches a header/footer
2912  
2913 multipart/mixed
2914 text/plain, cd=inline - A
2915 multipart/mixed
2916 multipart/alternative
2917 multipart/mixed
2918 text/plain, cd=inline - B
2919 image/jpeg, cd=inline - C
2920 text/plain, cd=inline - D
2921 multipart/related
2922 text/html - E
2923 image/jpeg - F
2924 image/jpeg, cd=attachment - G
2925 application/x-excel - H
2926 message/rfc822 - J
2927 text/plain, cd=inline - K
2928  
2929 In this case, we'd have the following list items
2930  
2931 text => B
2932 html => E
2933 textlist => [ A, B, C, D, K ]
2934 htmllist => [ A, E, K ]
2935 att => [
2936 { bs => C, text => 1, html => 1 },
2937 { bs => F, text => 1, html => 0 },
2938 { bs => G, text => 1, html => 1 },
2939 { bs => H, text => 1, html => 1 },
2940 { bs => J, text => 0, html => 0, msg => 1 },
2941 ]
2942  
2943 Examples:
2944  
2945 # Fetch body structure
2946 my $FR = $IMAP->fetch(1, 'bodystructure');
2947 my $BS = $FR->{1}->{bodystructure};
2948  
2949 # Parse further to find message components
2950 my $MC = $IMAP->find_message($BS);
2951 $MC = { 'plain' => ... text body struct ref part ...,
2952 'html' => ... html body struct ref part (if present) ...
2953 'htmllist' => [ ... html body struct ref parts (if present) ... ] };
2954  
2955 # Now get the text part of the message
2956 my $MT = $IMAP->fetch(1, 'body[' . $MC->{text}->{'IMAP-Part'} . ']');
2957  
2958 =cut
2959 sub find_message {
2960 my (%MsgComponents);
2961  
2962 my %KnownTextParts = (
2963 plain => 'text', text => 'text', enriched => 'text',
2964 html => 'html',
2965 'application/octet-stream' => 'text'
2966 );
2967  
2968 my @PartList = ([ undef, $_[0], 0, '', \(my $Tmp = '') ]);
2969  
2970 # Repeat until we find something
2971 while (my $Part = shift @PartList) {
2972 my ($Parent, $BS, $Pos, $InMultiList, $MultiTypeRef) = @$Part;
2973  
2974 my $InsideAlt = $InMultiList =~ /\balternative\b/ ? 1 : 0;
2975 my $InsideEnc = $InMultiList =~ /\bencrypted\b/ ? 1 : 0;
2976  
2977 # Pull out common MIME fields we'll look at
2978 my ($MTT, $MT, $ST, $SP) = @$BS{qw(MIME-TxtType MIME-Type MIME-Subtype MIME-Subparts)};
2979  
2980 # Note: $DT can be "", which really is default "inline", so compare
2981 # with "$DT ne 'attachment'", rather than "$DT eq 'inline'"
2982 my ($DT, $CD) = @$BS{qw(Disposition-Type Content-Disposition)};
2983  
2984 # Parts we want to treat as "text"
2985 my $IsInline = 0;
2986 # Text component of type we understand that isn't an attachment or has a filename
2987 $IsInline = 1 if $MT eq 'text' &&
2988 $KnownTextParts{$ST} &&
2989 $DT ne 'attachment' &&
2990 !$CD->{filename} &&
2991 !$CD->{'filename*'};
2992 # Bah, PGP has application/octet-stream inside an application/pgp-encrypted part
2993 $IsInline = 1 if $MTT eq 'application/octet-stream' &&
2994 $InsideEnc &&
2995 $CD->{filename} =~ /encrypted/;
2996  
2997 if ($IsInline) {
2998 # Map to just text or html type
2999 my $UT = $KnownTextParts{$MTT} // $KnownTextParts{$ST};
3000  
3001 # Found it if not already found one of this type
3002 if ( !exists $MsgComponents{$UT} ) {
3003  
3004 # Don't treat html parts in a multipart/mixed as an
3005 # alternative representation if not the first part
3006 # and text part already found
3007 if ( $ST eq 'html'
3008 && $Parent
3009 && $Parent->{'MIME-Subtype'} eq 'mixed'
3010 && $Pos > 0
3011 && $MsgComponents{text})
3012 {
3013 }
3014 else {
3015 $MsgComponents{$UT} ||= $BS;
3016 }
3017  
3018 }
3019  
3020 # Override existing part if old part is <= 10 bytes (eg 5 blank
3021 # lines), and new part is > 10 bytes. Or if old part has
3022 # 0 lines and new part has some lines
3023 elsif ( ( $MsgComponents{$UT}->{'Size'} <= 10 && $BS->{'Size'} > 10 )
3024 || ( $MsgComponents{$UT}->{Lines} < 1 && $BS->{Lines} > 0 ) )
3025 {
3026 $MsgComponents{$UT} = $BS;
3027 }
3028  
3029 # Add to textlist/htmllist if not in alternative part
3030 # or best part type if we are
3031 if ($UT eq 'text' || !$InsideAlt) {
3032 push @{$MsgComponents{'textlist'}}, $BS;
3033 $$MultiTypeRef ||= $UT;
3034 }
3035 if ($UT eq 'html' || !$InsideAlt) {
3036 push @{$MsgComponents{'htmllist'}}, $BS;
3037 $$MultiTypeRef ||= $UT;
3038 }
3039  
3040 # Ok got a known part, move to next
3041 next;
3042  
3043 } elsif ($MT eq 'image') {
3044  
3045 # Only add inline images
3046 if ($DT ne 'attachment') {
3047 # In alternative parts, we store which list part
3048 # we're in in $InsideAlt
3049 my $ItemList = $MsgComponents{$$MultiTypeRef . 'list'};
3050 if ($ItemList) {
3051 push @$ItemList, $BS;
3052 # Mark this list as having an image
3053 $MsgComponents{$$MultiTypeRef . 'listimage'} = 1;
3054 }
3055 }
3056 # And always add the image as an attachment below
3057  
3058 # If it's a multi-part, what type
3059 } elsif ($MT eq 'multipart') {
3060  
3061 # Look at all sub-parts
3062 my $Pos = 0;
3063 my $MultiType = '';
3064 my $SubMultiList = join ",", ($InMultiList or ()), $ST;
3065 my @SubParts = map { [ $BS, $_, $Pos++, $SubMultiList, \$MultiType ] } @$SP;
3066  
3067 # If it's a signed/alternative/related sub-part, look in it FIRST
3068 if ($ST eq 'signed' || $ST eq 'alternative' || $ST eq 'related' || $DT ne 'attachment') {
3069 unshift @PartList, @SubParts;
3070  
3071 # Otherwise look in it after we've looked at all the other components
3072 # at the current level
3073 } else {
3074 push @PartList, @SubParts;
3075 }
3076  
3077 # No attachment, move on to next part
3078 next;
3079 }
3080  
3081 # Pretty much everything goes in as an attachment, except images
3082 # inside related parts
3083 push @{$MsgComponents{att}}, {
3084 bs => $BS,
3085 $MTT eq 'message/rfc822' ? (
3086 msg => 1
3087 ) : (
3088 text => 1,
3089 html => $MT eq 'image' && $InMultiList =~ /\brelated\b/ ? 0 : 1,
3090 )
3091 };
3092 }
3093  
3094 # If there's no simple text or html bit, remove any
3095 # corresponding list versions as well
3096 for (qw(text html)) {
3097 $MsgComponents{$_} || delete $MsgComponents{$_ . "list"};
3098 }
3099  
3100 return \%MsgComponents;
3101 }
3102  
3103 =item I<generate_cid( $Token, $PartBS )>
3104  
3105 This method generates a ContentID based on $Token and $PartBS.
3106  
3107 The same value should always be returned for a given $Token and $PartBS
3108  
3109 =cut
3110 sub generate_cid {
3111  
3112 my $Digester = Digest->new( 'MD5' );
3113 $Digester->add( $_[0] );
3114 $Digester->add( $_[1]->{'IMAP-Partnum'} || '' );
3115 $Digester->add( $_[1]->{'Size'} || 'none' );
3116 $Digester->add( $_[1]->{'MIME-TxtType'} || 'none' );
3117 my $Cid = 'generated-' . $Digester->hexdigest() . '@messagingengine.com';
3118 return $Cid;
3119 }
3120  
3121 =item I<build_cid_map($BodyStruct, [ $IMAP, $Uid, $GenCidToken ])>
3122  
3123 This is a helper function that can be used to further parse the
3124 results of a fetched bodystructure. It recursively parses the
3125 bodystructure and returns a hash of Content-ID to bodystruct
3126 part references. This is useful when trying to determine CID
3127 links from an HTML message.
3128  
3129 If you pass a Mail::IMAPTalk object as the second parameter,
3130 the CID map built may be even more detailed. It seems some
3131 stupid versions of exchange put details in the Content-Location
3132 header rather than the Content-Type header. If that's the
3133 case, this will try and fetch the header from the message
3134  
3135 Examples:
3136  
3137 # Fetch body structure
3138 my $FR = $IMAP->fetch(1, 'bodystructure');
3139 my $BS = $FR->{1}->{bodystructure};
3140  
3141 # Parse further to get CID links
3142 my $CL = build_cid_map($BS);
3143 $CL = { '2958293123' => ... ref to body part ..., ... };
3144  
3145 =cut
3146 sub build_cid_map {
3147 my @PartStack = shift;
3148 my ($IMAP, $Uid, $GenCidToken) = @_;
3149 my %CIDHash;
3150  
3151 # While items left to process
3152 while (my $Part = shift @PartStack) {
3153  
3154 # For multi-part types, just add sub-parts to process stack
3155 if ($Part->{'MIME-Type'} eq 'multipart') {
3156 push @PartStack, @{$Part->{'MIME-Subparts'}};
3157 }
3158  
3159 # If content-id present
3160 my $CID = $Part->{'Content-ID'};
3161 if (! $CID) {
3162 $CID = generate_cid( $GenCidToken, $Part );
3163 }
3164 if ($CID) {
3165 # Strip any <> parts and add to hash
3166 $CID =~ s/^<(.*)>$/$1/;
3167 $CIDHash{$CID} = $Part
3168  
3169 }
3170  
3171 # If content-location present
3172 my $CLOC;
3173 if ($CLOC = $Part->{'Content-Location'}) {
3174 $CLOC =~ s/\s+//g;
3175 $CIDHash{$CLOC} ||= $Part;
3176 } elsif ($IMAP && $Uid) {
3177 # header.fields is only for rfc822 parts, have to get .MIME
3178 my $Headers = $IMAP->fetch($Uid, "body[" . $Part->{'IMAP-Partnum'} . ".MIME]");
3179 $Headers = $Headers->{$Uid}->{body} if $Headers;
3180 ($CLOC) = ($Headers =~ /^Content-Location: ([^\r\n]*(?:\r\n\s+[^\r\n]*)*)/m) if $Headers;
3181 $CLOC =~ s/\s+//g if $CLOC;
3182 $CIDHash{$CLOC} ||= $Part if $CLOC;
3183 }
3184  
3185 # Add content by name as well
3186 if (my $Name = $Part->{'Content-Type'}->{name}) {
3187 $CIDHash{$Name} ||= $Part;
3188 }
3189  
3190 }
3191  
3192 return \%CIDHash;
3193 }
3194  
3195 =item I<obliterate($CyrusName)>
3196  
3197 Given a username (optionally username\@domain) immediately delete all messages belonging
3198 to this user. Uses LOCALDELETE. Quite FastMail Patchd Cyrus specific.
3199  
3200 =cut
3201 sub obliterate {
3202 my $Self = shift;
3203 my $CyrusName = shift;
3204  
3205 # convert to bang notation
3206 my $basename = $CyrusName;
3207 my $domain;
3208 if ($basename =~ s{\@(.*)}{}) {
3209 $domain = $1;
3210 }
3211  
3212 my $folders = $Self->list($domain ? "$domain!user.$basename.*" : "user.$basename.*", "*");
3213 my $dfolders = $Self->list($domain ? "$domain!DELETED.user.$basename.*" : "DELETED.user.$basename.*", "*");
3214 $folders = [] unless ref($folders) eq 'ARRAY'; # stupid "completed" bug
3215 $dfolders = [] unless ref($dfolders) eq 'ARRAY'; # stupid "completed" bug
3216  
3217 my @list = reverse sort
3218 ($domain ? "$domain!user.$basename" : "user.$basename"),
3219 map { $_->[2] } @$folders, @$dfolders;
3220  
3221 foreach my $folder (@list) {
3222 $Self->localdelete($folder);
3223 }
3224  
3225 return 1;
3226 }
3227  
3228 =back
3229 =cut
3230  
3231 =head1 IMAP CALLBACKS
3232  
3233 By default, these methods do nothing, but you can dervice
3234 from Mail::IMAPTalk and override these methods to trap
3235 any things you want to catch
3236  
3237 =over 4
3238 =cut
3239  
3240 =item I<cb_switch_folder($CurrentFolder, $NewFolder)>
3241  
3242 Called when the currently selected folder is being changed
3243 (eg 'select' called and definitely a different folder
3244 is being selected, or 'unselect' methods called)
3245  
3246 =cut
3247 sub cb_switch_folder { }
3248  
3249 =item I<cb_folder_changed($Folder)>
3250  
3251 Called when a command changes the contents of a folder
3252 (eg copy, append, etc). $Folder is the name of the
3253 folder that's changing.
3254  
3255 =cut
3256 sub cb_folder_changed { }
3257  
3258 =back
3259 =cut
3260  
3261 =head1 FETCH RESULTS
3262  
3263 The 'fetch' operation is probably the most common thing you'll do with an
3264 IMAP connection. This operation allows you to retrieve information about a
3265 message or set of messages, including header fields, flags or parts of the
3266 message body.
3267  
3268 C<Mail::IMAPTalk> will always parse the results of a fetch call into a Perl like
3269 structure, though 'bodystructure', 'envelope' and 'uid' responses may
3270 have additional parsing depending on the C<parse_mode> state and the C<uid>
3271 state (see below).
3272  
3273 For an example case, consider the following IMAP commands and responses
3274 (C is what the client sends, S is the server response).
3275  
3276 C: a100 fetch 5,6 (flags rfc822.size uid)
3277 S: * 1 fetch (UID 1952 FLAGS (\recent \seen) RFC822.SIZE 1150)
3278 S: * 2 fetch (UID 1958 FLAGS (\recent) RFC822.SIZE 110)
3279 S: a100 OK Completed
3280  
3281 The fetch command can be sent by calling:
3282  
3283 my $Res = $IMAP->fetch('1:*', '(flags rfc822.size uid)');
3284  
3285 The result in response will look like this:
3286  
3287 $Res = {
3288 1 => {
3289 'uid' => 1952,
3290 'flags' => [ '\\recent', '\\seen' ],
3291 'rfc822.size' => 1150
3292 },
3293 2 => {
3294 'uid' => 1958,
3295 'flags' => [ '\\recent' ],
3296 'rfc822.size' => 110
3297 }
3298 };
3299  
3300  
3301 A couple of points to note:
3302  
3303 =over
3304  
3305 =item 1.
3306  
3307 The message IDs have been turned into a hash from message ID to fetch
3308 response result.
3309  
3310 =item 2.
3311  
3312 The response items (e.g. uid, flags, etc) have been turned into a hash for
3313 each message, and also changed to lower case values.
3314  
3315 =item 3.
3316  
3317 Other bracketed (...) lists have become array references.
3318  
3319 =back
3320  
3321 In general, this is how all fetch responses are parsed.
3322 There is one major difference however when the IMAP connection
3323 is in 'uid' mode. In this case, the message IDs in the main hash are changed
3324 to message UIDs, and the 'uid' entry in the inner hash is removed. So the
3325 above example would become:
3326  
3327 my $Res = $IMAP->fetch('1:*', '(flags rfc822.size)');
3328  
3329 $Res = {
3330 1952 => {
3331 'flags' => [ '\\recent', '\\seen' ],
3332 'rfc822.size' => 1150
3333 },
3334 1958 => {
3335 'flags' => [ '\\recent' ],
3336 'rfc822.size' => 110
3337 }
3338 };
3339  
3340 =head2 Bodystructure
3341  
3342 When dealing with messages, we need to understand the MIME structure of
3343 the message, so we can work out what is the text body, what is attachments,
3344 etc. This is where the 'bodystructure' item from an IMAP server comes in.
3345  
3346 C: a101 fetch 1 (bodystructure)
3347 S: * 1 fetch (BODYSTRUCTURE ("TEXT" "PLAIN" NIL NIL NIL "QUOTED-PRINTABLE" 255 11 NIL ("INLINE" NIL) NIL))
3348 S: a101 OK Completed
3349  
3350 The fetch command can be sent by calling:
3351  
3352 my $Res = $IMAP->fetch(1, 'bodystructure');
3353  
3354 As expected, the resultant response would look like this:
3355  
3356 $Res = {
3357 1 => {
3358 'bodystructure' => [
3359 'TEXT', 'PLAIN', undef, undef, undef, 'QUOTED-PRINTABLE',
3360 255, 11, UNDEF, [ 'INLINE', undef ], undef
3361 ]
3362 }
3363 };
3364  
3365 However, if you set the C<parse_mode(BodyStructure => 1)>, then the result would be:
3366  
3367 $Res = {
3368 '1' => {
3369 'bodystructure' => {
3370 'MIME-Type' => 'text',
3371 'MIME-Subtype' => 'plain',
3372 'MIME-TxtType' => 'text/plain',
3373 'Content-Type' => {},
3374 'Content-ID' => undef,
3375 'Content-Description' => undef,
3376 'Content-Transfer-Encoding' => 'QUOTED-PRINTABLE',
3377 'Size' => '3569',
3378 'Lines' => '94',
3379 'Content-MD5' => undef,
3380 'Disposition-Type' => 'inline',
3381 'Content-Disposition' => {},
3382 'Content-Language' => undef,
3383 'Remainder' => [],
3384 'IMAP-Partnum' => ''
3385 }
3386 }
3387 };
3388  
3389 A couple of points to note here:
3390  
3391 =over 4
3392  
3393 =item 1.
3394  
3395 All the positional fields from the bodystructure list response
3396 have been turned into nicely named key/value hash items.
3397  
3398 =item 2.
3399  
3400 The MIME-Type and MIME-Subtype fields have been made lower case.
3401  
3402 =item 3.
3403  
3404 An IMAP-Partnum item has been added. The value in this field can
3405 be passed as the 'section' number of an IMAP body fetch call to
3406 retrieve the text of that IMAP section.
3407  
3408 =back
3409  
3410 In general, the following items are defined for all body structures:
3411  
3412 =over 4
3413  
3414 =item * MIME-Type
3415  
3416 =item * MIME-Subtype
3417  
3418 =item * Content-Type
3419  
3420 =item * Disposition-Type
3421  
3422 =item * Content-Disposition
3423  
3424 =item * Content-Language
3425  
3426 =back
3427  
3428 For all bodystructures EXCEPT those that have a MIME-Type of 'multipart',
3429 the following are defined:
3430  
3431 =over 4
3432  
3433 =item * Content-ID
3434  
3435 =item * Content-Description
3436  
3437 =item * Content-Transfer-Encoding
3438  
3439 =item * Size
3440  
3441 =item * Content-MD5
3442  
3443 =item * Remainder
3444  
3445 =item * IMAP-Partnum
3446  
3447 =back
3448  
3449 For bodystructures where MIME-Type is 'text', an extra item 'Lines'
3450 is defined.
3451  
3452 For bodystructures where MIME-Type is 'message' and MIME-Subtype is 'rfc822', the
3453 extra items 'Message-Envelope', 'Message-Bodystructure' and 'Message-Lines'
3454 are defined. The 'Message-Bodystructure' item is itself a reference
3455 to an entire bodystructure hash with all the format information of the
3456 contained message. The 'Message-Envelope' item is a hash structure with
3457 the message header information. See the B<Envelope> entry below.
3458  
3459 For bodystructures where MIME-Type is 'multipart', an extra item 'MIME-Subparts' is
3460 defined. The 'MIME-Subparts' item is an array reference, with each item being a
3461 reference to an entire bodystructure hash with all the format information
3462 of each MIME sub-part.
3463  
3464 For further processing, you can use the B<find_message()> function.
3465 This will analyse the body structure and find which part corresponds
3466 to the main text/html message parts to display. You can also use
3467 the B<find_cid_parts()> function to find CID links in an html
3468 message.
3469  
3470 =head2 Envelope
3471  
3472 The envelope structure contains most of the addressing header fields from
3473 an email message. The following shows an example envelope fetch (the
3474 response from the IMAP server has been neatened up here)
3475  
3476 C: a102 fetch 1 (envelope)
3477 S: * 1 FETCH (ENVELOPE
3478 ("Tue, 7 Nov 2000 08:31:21 UT" # Date
3479 "FW: another question" # Subject
3480 (("John B" NIL "jb" "abc.com")) # From
3481 (("John B" NIL "jb" "abc.com")) # Sender
3482 (("John B" NIL "jb" "abc.com")) # Reply-To
3483 (("Bob H" NIL "bh" "xyz.com") # To
3484 ("K Jones" NIL "kj" "lmn.com"))
3485 NIL # Cc
3486 NIL # Bcc
3487 NIL # In-Reply-To
3488 NIL) # Message-ID
3489 )
3490 S: a102 OK Completed
3491  
3492 The fetch command can be sent by calling:
3493  
3494 my $Res = $IMAP->fetch(1, 'envelope');
3495  
3496 And you get the idea of what the resultant response would be. Again
3497 if you change C<parse_mode(Envelope => 1)>, you get a neat structure as follows:
3498  
3499 $Res = {
3500 '1' => {
3501 'envelope' => {
3502 'Date' => 'Tue, 7 Nov 2000 08:31:21 UT',
3503 'Subject' => 'FW: another question',
3504 'From' => '"John B" <jb@abc.com>',
3505 'Sender' => '"John B" <jb@abc.com>',
3506 'Reply-To' => '"John B" <jb@abc.com>',
3507 'To' => '"Bob H" <bh@xyz.com>, "K Jones" <kj@lmn.com>',
3508 'Cc' => '',
3509 'Bcc' => '',
3510 'In-Reply-To' => undef,
3511 'Message-ID' => undef,
3512  
3513 'From-Raw' => [ [ 'John B', undef, 'jb', 'abc.com' ] ],
3514 'Sender-Raw' => [ [ 'John B', undef, 'jb', 'abc.com' ] ],
3515 'Reply-To-Raw' => [ [ 'John B', undef, 'jb', 'abc.com' ] ],
3516 'To-Raw' => [
3517 [ 'Bob H', undef, 'bh', 'xyz.com' ],
3518 [ 'K Jones', undef, 'kj', 'lmn.com' ],
3519 ],
3520 'Cc-Raw' => [],
3521 'Bcc-Raw' => [],
3522 }
3523 }
3524 };
3525  
3526 All the fields here are from straight from the email headers.
3527 See RFC 822 for more details.
3528  
3529 =head2 Annotation
3530  
3531 If the server supports RFC 5257 (ANNOTATE Extension), then you can
3532 fetch per-message annotations.
3533  
3534 Annotation responses would normally be returned as a a nested set of
3535 arrays. However it's much easier to access the results as a nested set
3536 of hashes, so the results are so converted if the Annotation parse
3537 mode is enabled, which is on by default.
3538  
3539 Part of an example from the RFC
3540  
3541 S: * 12 FETCH (UID 1123 ANNOTATION
3542 (/comment (value.priv "My comment"
3543 size.priv "10")
3544 /altsubject (value.priv "Rhinoceroses!"
3545 size.priv "13")
3546  
3547 So the fetch command:
3548  
3549 my $Res = $IMAP->fetch(1123, 'annotation', [ '/*', [ 'value.priv', 'size.priv' ] ]);
3550  
3551 Would have the result:
3552  
3553 $Res = {
3554 '1123' => {
3555 'annotation' => {
3556 '/comment' => {
3557 'value.priv' => 'My comment',
3558 'size.priv => 10
3559 },
3560 '/altsubject' => {
3561 'value.priv' => '"Rhinoceroses',
3562 'size.priv => 13
3563 }
3564 }
3565 }
3566 }
3567
3568 =cut
3569  
3570 =head1 INTERNAL METHODS
3571  
3572 =over 4
3573 =cut
3574  
3575 =item I<_imap_cmd($Command, $IsUidCmd, $RespItems, @Args)>
3576  
3577 Executes a standard IMAP command.
3578  
3579 =item I<Method arguments>
3580  
3581 =over 4
3582  
3583 =item B<$Command>
3584  
3585 Text string of command to call IMAP server with (e.g. 'select', 'search', etc).
3586  
3587 =item B<$IsUidCmd>
3588  
3589 1 if command involved message ids and can be prefixed with UID, 0 otherwise.
3590  
3591 =item B<$RespItems>
3592  
3593 Responses to look for from command (eg 'list', 'fetch', etc). Commands
3594 which return results usually return them untagged. The following is an
3595 example of fetching flags from a number of messages.
3596  
3597 C123 uid fetch 1:* (flags)
3598 * 1 FETCH (FLAGS (\Seen) UID 1)
3599 * 2 FETCH (FLAGS (\Seen) UID 2)
3600 C123 OK Completed
3601  
3602 Between the sending of the command and the 'OK Completed' response,
3603 we have to pick up all the untagged 'FETCH' response items so we
3604 would pass 'fetch' (always use lower case) as the $RespItems to extract.
3605  
3606 This can also be a hash ref of callback functions. See _parse_response
3607 for more examples
3608  
3609 =item B<@Args>
3610  
3611 Any extra arguments to pass to command.
3612  
3613 =back
3614  
3615 =cut
3616 sub _imap_cmd {
3617 my $Self = shift;
3618 my $ParseMode = ref($_[0]) eq 'HASH' ? shift : {};
3619 my ($Cmd, $IsUidCmd, $RespItems) = (shift, shift, shift);
3620  
3621 # Remember the last command and reset last error
3622 $Self->{LastCmd} = $Cmd;
3623 $Self->{LastError} = undef;
3624  
3625 # Prefix command with uid if uid command and in uid mode
3626 $Cmd = 'uid ' . $Cmd if $IsUidCmd && $Self->{Uid};
3627  
3628 # Send command and parse response. Put in an eval because we 'die' if any problems
3629 my ($CompletionResp, $DataResp);
3630 eval {
3631 # Send the command and parse the response
3632 $Self->_send_cmd($Cmd, @_);
3633 $ParseMode->{PostCommand}->() if $ParseMode->{PostCommand};
3634 # Items returned are the complete response (eg ok/bad/no) and
3635 # the any parsed data to return from the command
3636 ($CompletionResp, $DataResp) = $Self->_parse_response($RespItems, $ParseMode);
3637 };
3638 $Self->{CmdId}++;
3639 $Self->{LastRespCode} = $CompletionResp;
3640  
3641 # Return undef if any error occurred (either through 'die' or non-'OK' IMAP response)
3642 if ($@) {
3643 warn($@) if $@ !~ /NO Over quota/;
3644  
3645 # One of our errors? Capture, set $@ and return undef
3646 if ($@ =~ /IMAPTalk/ && !$Self->{Pedantic}) {
3647 $Self->{LastError} = $@ = "IMAP Command : '$Cmd' failed. Reason was : $@";
3648 return undef;
3649 }
3650  
3651 # If something else threw the error, rethrow, but release socket first since
3652 # connection is in an indeterminate state
3653 $Self->release_socket(1);
3654 die $@;
3655 };
3656  
3657 if ($CompletionResp !~ /^ok/) {
3658 $Self->{LastError} = $@ = "IMAP Command : '$Cmd' failed. Response was : $CompletionResp - $DataResp";
3659 return undef;
3660 }
3661  
3662 # If we want an array response, handle undef and array ref cases specially
3663 if (wantarray) {
3664 # If undef response, return empty array
3665 return () if !defined($DataResp);
3666 # If respose is array reference, return array
3667 return @$DataResp if ref($DataResp) eq "ARRAY";
3668 }
3669  
3670 # Otherwise return response as single item
3671 return $DataResp;
3672 }
3673  
3674 =item I<_send_cmd($Self, $Cmd, @InArgs)>
3675  
3676 Helper method used by the B<_imap_cmd> method to actually build (and
3677 quote where necessary) the command arguments and then send the
3678 actual command.
3679  
3680 =cut
3681 sub _send_cmd {
3682 my ($Self, $Cmd) = (shift, shift);
3683  
3684 # Send command. Build line buffer of args
3685 my $LineBuffer = $Self->{CmdId} . " " . $Cmd;
3686 $LineBuffer = $Self->_send_data({}, $LineBuffer, @_);
3687  
3688 # Output remainder of line buffer (if empty, we still want
3689 # to send the \015\012 chars)
3690 $Self->_imap_socket_out($LineBuffer . LB) if defined $LineBuffer;
3691  
3692 return 1;
3693 }
3694  
3695 =item I<_send_data($Self, $Opts, $Buffer, @Args)>
3696  
3697 Helper method used by the B<_send_cmd> method to actually build (and
3698 quote where necessary) the command arguments and then send the
3699 actual command.
3700  
3701 =cut
3702 sub _send_data {
3703 my ($Self, $Opts, $LineBuffer, @Args) = @_;
3704  
3705 my ($AddSpace, $NextAddSpace) = (1, 1);
3706 foreach my $Arg (@Args) {
3707 my ($IsQuote, $IsLiteral, $IsFile) = ($Opts->{Quote}, 0, 0);
3708  
3709 # --- Determine value type and appropriate output
3710  
3711 # Map undef to NIL atom
3712 if (!defined($Arg)) {
3713 $Arg = "NIL";
3714 $IsQuote = 0;
3715  
3716 # If it's a reference, then must be a file, scalar or hash ref
3717 } elsif (ref($Arg)) {
3718  
3719 # Hash refs are used to encode special handling of items
3720 if (ref($Arg) eq "HASH") {
3721 if (exists $Arg->{Quote}) {
3722 $IsQuote = 1;
3723 $Arg = $Arg->{Quote};
3724 } elsif (exists $Arg->{Literal}) {
3725 $IsLiteral = 1;
3726 $Arg = ref($Arg->{Literal}) ? $Arg->{Literal} : \$Arg->{Literal};
3727 } elsif (exists $Arg->{Raw}) {
3728 $AddSpace = !$Arg->{NoSpace};
3729 $NextAddSpace = !$Arg->{NoNextSpace};
3730 $IsQuote = 0;
3731 $Arg = $Arg->{Raw};
3732 } else {
3733 die "Unknown hash arg type: " . (keys %$Arg)[0];
3734 }
3735 }
3736  
3737 # Above may have changed $Arg, so not an elsif here
3738  
3739 if (ref($Arg)) {
3740 # Array reference, wrap in ()'s
3741 if (ref($Arg) eq "ARRAY") {
3742 $LineBuffer = $Self->_send_data(
3743 { Quote => $IsQuote },
3744 $LineBuffer,
3745 { NoSpace => !$AddSpace, Raw => "(", NoNextSpace => 1 },
3746 @$Arg,
3747 { NoSpace => 1, Raw => ")", NoNextSpace => 1 }
3748 );
3749 next;
3750  
3751 # If it's a scalar ref, just use value it references
3752 } elsif (ref($Arg) eq "SCALAR") {
3753  
3754 # If it's a hash ref, deal with
3755 # Must be a file ref
3756 } elsif (UNIVERSAL::isa($Arg, "GLOB")) {
3757 $IsLiteral = $IsFile = 1;
3758  
3759 } else {
3760 die "Unknown reference arg type: " . ref($Arg);
3761 }
3762 }
3763  
3764 # If it's got a \000 or \012 or \015, we need to make it a literal.
3765 } elsif ($Arg =~ m/[\000\012\015]/) {
3766 $IsLiteral = 1;
3767  
3768 # If it's got other invalid chars, but doesn't start with a "(",
3769 # just quote it
3770 } elsif ($Arg =~ m/[\000-\040\{\} \%\*\"\(\)]/ && !($Arg =~ m/^\(/)) {
3771 $IsQuote = 1;
3772  
3773 # Empty string, send empty quotes
3774 } elsif ($Arg eq "") {
3775 $IsQuote = 1;
3776  
3777 # Otherwise leave as normal
3778 } else {
3779 }
3780  
3781 # --- Deal with outputing value
3782  
3783 # Handle non-literals
3784 if (!$IsLiteral) {
3785 $Arg = _quote(ref($Arg) ? $$Arg : $Arg) if $IsQuote;
3786
3787 # Must be a scalar reference for a non-literal
3788 $LineBuffer .= ($AddSpace ? " " : "") . (ref($Arg) ? $$Arg : $Arg);
3789  
3790 # It's a literal, has to be scalar, scalar ref or file ref
3791 } else {
3792 # Get the size of the literal
3793 my $LiteralSize = 0;
3794  
3795 if (!$IsFile) {
3796 $LiteralSize = ref($Arg) ? length($$Arg) : length($Arg);
3797  
3798 # Otherwise it's a file ref
3799 } else {
3800 seek($Arg, 0, 2); # SEEK_END
3801 $LiteralSize = tell($Arg);
3802 seek($Arg, 0, 0); # SEEK_SET
3803 }
3804  
3805 # Add to line buffer and send
3806 $LineBuffer .= ($AddSpace ? " " : "") . "{" . $LiteralSize . "}" . LB;
3807 $Self->_imap_socket_out($LineBuffer);
3808  
3809 $LineBuffer = "";
3810  
3811 # Wait for "+ go ahead" response
3812 my $GoAhead = $Self->_imap_socket_read_line();
3813 if ($GoAhead =~ /^\+/) {
3814 if (!$IsFile) {
3815 $Self->_imap_socket_out(ref($Arg) ? $$Arg : $Arg);
3816 } else {
3817 $Self->_copy_handle_to_imap_socket($Arg, $LiteralSize);
3818 }
3819  
3820 # If no "+ go ahead" response, stick back in read buffer and fall out
3821 # to parse what the response was
3822 } else {
3823 substr($Self->{ReadBuf}, 0, 0, $GoAhead . LB);
3824 return undef;
3825 }
3826  
3827 }
3828 $AddSpace = $NextAddSpace;
3829 $NextAddSpace = 1;
3830 }
3831  
3832 return $LineBuffer;
3833 }
3834  
3835 =item I<_parse_response($Self, $RespItems, [ \%ParseMode ])>
3836  
3837 Helper method called by B<_imap_cmd> after sending the command. This
3838 methods retrieves data from the IMAP socket and parses it into Perl
3839 structures and returns the results.
3840  
3841 $RespItems is either a string, which is the untagged response(s)
3842 to find and return, or for custom processing, it can be a
3843 hash ref.
3844  
3845 If a hash ref, then each key will be an untagged response to look for,
3846 and each value a callback function to call for the corresponding untagged
3847 response.
3848  
3849 Each callback will be called with 2 or 3 arguments; the untagged
3850 response string, the remainder of the line parsed into an array ref, and
3851 for fetch type responses, the id will be passed as the third argument.
3852  
3853 One other piece of magic, if you pass a 'responseitem' key, then the
3854 value should be a string, and will be the untagged response returned
3855 from the function
3856  
3857 =cut
3858 sub _parse_response {
3859 my ($Self, $RespItems, $ParseMode) = @_;
3860  
3861 # Loop until we get the tagged response for the sent command
3862 my $Result;
3863 my $Tag = '';
3864 my (%DataResp, $CompletionResp, $Res1, $Callback, %UnfixCache);
3865  
3866 # Build final parse mode. Note overrides come second to replace defaults
3867 my %ParseMode = (%{$Self->{ParseMode} || {}}, %{$ParseMode || {}});
3868  
3869 # Some commands might have no results (eg list, fetch, etc), but we
3870 # want to distinguish no results vs IMAP NO result, so setup a default
3871 # empty hash/array for these commands as appropriate.
3872 # Create empty hash/array, don't copy ref to global!
3873 if (!ref($RespItems) && (my $RespDefault = $RespDefaults{$RespItems})) {
3874 $DataResp{$RespItems} = {} if $RespDefault eq 'hash';
3875 $DataResp{$RespItems} = [] if $RespDefault eq 'array';
3876 }
3877  
3878 # Response item we'll return
3879 my $RespItem = !ref($RespItems) ? $RespItems : $RespItems->{responseitem} || '';
3880  
3881 # Store completion response and data responses
3882 while ($Tag ne $Self->{CmdId}) {
3883 if ($Tag && $Tag ne '*' && $Self->{Pedantic}) {
3884 die "IMAPTalk: Unexpected tag '$Tag'";
3885 }
3886  
3887 # Force starting new line read
3888 $Self->{ReadLine} = undef;
3889  
3890 # Get next response id and response item type
3891 $Tag = $Self->_next_simple_atom();
3892 $Res1 = $CompletionResp = lc($Self->_next_simple_atom());
3893  
3894 # This is a big switch that works out what to do with each result type
3895  
3896 # If it's a number, we're getting some info about a message
3897 RepeatSwitch:
3898 if ($Res1 =~ /^(\d+)$/) {
3899  
3900 my $Res2 = lc($Self->_next_simple_atom());
3901  
3902 # Parse fetch response into perl structure
3903 my $Fetch;
3904 if ($Res2 eq 'fetch') {
3905 $Fetch = _parse_fetch_result($Self->_next_atom(), \%ParseMode);
3906 }
3907  
3908 if (ref($RespItems) && ($Callback = $RespItems->{$Res2})) {
3909 $Callback->($Res2, $Fetch || $Res1, $Res1);
3910  
3911 } elsif ($Res2 eq 'exists' || $Res2 eq 'recent' || $Res2 eq 'expunge') {
3912 $DataResp{$Res2} = $Res1;
3913  
3914 } elsif ($Res2 eq 'fetch') {
3915 # If UID mode, and got fetch result, transform from ID -> UID hash
3916 $Res1 = $Fetch->{uid} if $Self->{Uid};
3917 $Res1 ||= '';
3918 # Store the result in our response hash
3919 my $FetchRes = ($DataResp{fetch}->{$Res1} ||= {});
3920 %$FetchRes = (%$FetchRes, %$Fetch);
3921  
3922 } else {
3923 # Don't know other response types, just store the atom
3924 $DataResp{$Res2} = $Self->_next_atom();
3925 }
3926  
3927 } elsif (ref($RespItems) && ($Callback = $RespItems->{$Res1})) {
3928 $Callback->($Res1, $Self->_remaining_atoms($Res1 =~ /sort/ ? 1 : 0));
3929  
3930 } elsif ($Res1 eq 'ok') {
3931 # If OK, probably something like * OK [... ]
3932 my $Line = $DataResp{remainder} = $Self->_remaining_line();
3933  
3934 # Extract items inside [...]
3935 if ($Line =~ /\[(.*)\] ?(.*)$/) {
3936 $Self->{ReadLine} = $1;
3937 $DataResp{remainder} = $2;
3938  
3939 # Use atom parser to get internal items (ignore errors)
3940 $Res1 = eval { lc($Self->_next_atom()) };
3941 goto RepeatSwitch if defined $Res1;
3942  
3943 # Error case, empty any buffer and keep going
3944 $Self->{ReadLine} = '';
3945 }
3946  
3947 } elsif ($Res1 eq 'search' || $Res1 eq 'sort') {
3948 my $IdList = $Self->_remaining_atoms(1);
3949  
3950 # AOL server returns multiple SEARCH responses
3951 if (ref($DataResp{$Res1}) eq 'ARRAY') {
3952 push @{$DataResp{$Res1}}, @$IdList;
3953 } else {
3954 # Avoid data copy if possible, could be large UID list
3955 $DataResp{$Res1} = $IdList;
3956 }
3957 } elsif ($Res1 eq 'status') {
3958 my ($Name, $StatusRes) = @{$Self->_remaining_atoms()};
3959 $StatusRes = _parse_list_to_hash($StatusRes);
3960  
3961 # If we explicit requested parsing the status response, we just want
3962 # the data (we know the folder). Otherwise this is an unsolicited
3963 # status response (eg list extended return status), and we want
3964 # to store the folder so we can get it via get_response_code.
3965 if ($RespItem eq 'status') {
3966 $DataResp{$Res1} = $StatusRes;
3967 } else {
3968 $Name = ($UnfixCache{$Name} ||= $Self->_unfix_folder_name($Name));
3969 $DataResp{$Res1}->{$Name} = $StatusRes;
3970 }
3971  
3972 } elsif ($Res1 eq 'flags' || $Res1 eq 'thread' || $Res1 eq 'namespace' || $Res1 eq 'myrights') {
3973 $DataResp{$Res1} = $Self->_remaining_atoms();
3974  
3975 } elsif ($Res1 eq 'xlist' || $Res1 eq 'list' || $Res1 eq 'lsub') {
3976 my ($Attr, $Sep, $Name) = @{$Self->_remaining_atoms()};
3977 $Self->_set_separator($Sep);
3978 # Remove root text from folder name
3979 $Name = ($UnfixCache{$Name} ||= $Self->_unfix_folder_name($Name));
3980 push @{$DataResp{$Res1}}, [ $Attr, $Sep, $Name ];
3981 } elsif ($Res1 eq 'permanentflags' || $Res1 eq 'uidvalidity' ||
3982 $Res1 eq 'uidnext' || $Res1 eq 'highestmodseq' || $Res1 eq 'numresults') {
3983 $DataResp{$Res1} = $Self->_next_atom();
3984 $Self->_remaining_line();
3985  
3986 } elsif ($Res1 eq 'newname' ||
3987 $Res1 eq 'parse' || $Res1 eq 'trycreate') {
3988 $DataResp{$Res1} = $Self->_remaining_line();
3989  
3990 } elsif ($Res1 eq 'alert') {
3991 # No argument to alert, it's the remainder of the line after the ]
3992 $DataResp{$Res1} = delete $DataResp{remainder};
3993  
3994 } elsif ($Res1 eq 'capability' || $Res1 eq 'enabled') {
3995 $DataResp{$Res1} = { map { lc($_) => 1 } @{$Self->_remaining_atoms() || []} };
3996  
3997 } elsif ($Res1 eq 'vanished') {
3998 $DataResp{$Res1} = $Self->_remaining_atoms();
3999  
4000 } elsif ($Res1 eq 'appenduid') {
4001 $DataResp{$Res1} = [ $Self->_next_atom(), $Self->_next_atom() ];
4002 $Self->_remaining_line();
4003  
4004 } elsif ($Res1 eq 'copyuid') {
4005 $DataResp{$Res1} = [ $Self->_next_atom(), $Self->_next_atom(), $Self->_next_atom() ];
4006 $Self->_remaining_line();
4007  
4008 } elsif ($Res1 eq 'read-write' || $Res1 eq 'read-only') {
4009 $DataResp{$Res1} = 1;
4010 $DataResp{foldermode} = $Res1;
4011 $Self->_remaining_line();
4012  
4013 } elsif ($Res1 eq 'quota') {
4014 # Result is: foldername (limits triplets)
4015 # If just a 'getquota', just return triplets. If a 'getrootquota',
4016 # build the hash response
4017 my ($qfolder, $qlimits) = ($Self->_next_atom(), $Self->_next_atom());
4018 if (ref($DataResp{$Res1})) {
4019 $DataResp{$Res1}->{$qfolder} = $qlimits;
4020 } else {
4021 $DataResp{$Res1} = $qlimits;
4022 }
4023  
4024 } elsif ($Res1 eq 'quotaroot') {
4025 # Result is: foldername rootitems
4026 $DataResp{quota} = { 'quotaroot' => $Self->_remaining_atoms() };
4027  
4028 } elsif ($Res1 eq 'acl') {
4029 $DataResp{acl} = $Self->_remaining_atoms();
4030 shift @{$DataResp{acl}};
4031  
4032 } elsif ($Res1 eq 'annotation') {
4033 my ($Name, $Entry, $Attributes) = @{$Self->_remaining_atoms()};
4034 $Name = ($UnfixCache{$Name} ||= $Self->_unfix_folder_name($Name));
4035 $DataResp{annotation}->{$Name}->{$Entry} = { @{$Attributes || []} };
4036  
4037 } elsif ($Res1 eq 'metadata') {
4038 my ($Name, $Bits) = @{$Self->_remaining_atoms()};
4039 $Name = ($UnfixCache{$Name} ||= $Self->_unfix_folder_name($Name));
4040 my %Hash = @$Bits;
4041 $DataResp{metadata}->{$Name}->{$_} = $Hash{$_} for keys %Hash;
4042  
4043 } elsif (($Res1 eq 'bye') && ($Self->{LastCmd} ne 'logout')) {
4044 $Self->{Cache}->{bye} = $Self->_remaining_line();
4045 die "IMAPTalk: Connection was unexpectedly closed by host";
4046  
4047 } elsif ($Res1 eq 'no' || $Res1 eq 'bad') {
4048 $Result = $Self->_remaining_line();
4049  
4050 } else {
4051 $DataResp{$Res1} = $Self->_remaining_line();
4052 }
4053  
4054 # Should have read all of line
4055 if ($Self->{ReadLine} ne '') {
4056 die 'IMAPTalk: Unexpected data remaining on response line "' . $Self->{ReadLine} . '"';
4057 }
4058  
4059 last if $ParseMode{IdleResponse};
4060 }
4061  
4062 # Return the requested item from %DataResp, and put
4063 # the rest in $Self->{Cache}
4064 $Result ||= delete $DataResp{$RespItem};
4065 $Result ||= $Res1;
4066 $Self->{Cache}->{$_} = $DataResp{$_} for keys %DataResp;
4067  
4068 return ($CompletionResp, $Result);
4069 }
4070  
4071 =item I<_require_capability($Self, $Capability)>
4072  
4073 Helper method which checks that the server has a certain capability.
4074 If not, it sets the internal last error, $@ and returns undef.
4075  
4076 =cut
4077 sub _require_capability {
4078 my ($Self, $Capability) = @_;
4079 my $Caps = $Self->capability() || {};
4080 if (!exists $Caps->{$Capability}) {
4081 $Self->{LastError} = $@ = "IMAP server has no $Capability capability";
4082 return undef;
4083 }
4084 return 1;
4085 }
4086  
4087 =item I<_trace($Self, $Line)>
4088  
4089 Helper method which outputs any tracing data.
4090  
4091 =cut
4092 sub _trace {
4093 my ($Self, $Line) = @_;
4094 $Line =~ s/\015\012/\n/;
4095 my $Trace = $Self->{Trace};
4096
4097 if (ref($Trace) eq 'GLOB') {
4098 print $Trace $Line;
4099 } elsif (ref($Trace) eq 'CODE') {
4100 $Trace->($Line);
4101 } elsif (ref($Trace) eq 'SCALAR') {
4102 $$Trace ||= '';
4103 $$Trace .= $Line;
4104 } elsif ($Trace == 1) {
4105 print STDERR $Line;
4106 }
4107 }
4108  
4109 =item I<_is_current_folder($Self, $FolderName)>
4110  
4111 Return true if a folder is currently selected and that
4112 folder is $FolderName
4113  
4114 =cut
4115 sub _is_current_folder {
4116 my ($Self, $Folder) = @_;
4117  
4118 return ($Self->state() == Selected) &&
4119 ($Folder eq $Self->{CurrentFolder});
4120 }
4121  
4122 =back
4123 =cut
4124  
4125 =head1 INTERNAL SOCKET FUNCTIONS
4126  
4127 =over 4
4128 =cut
4129  
4130 =item I<_next_atom($Self)>
4131  
4132 Returns the next atom from the current line. Uses $Self->{ReadLine} for
4133 line data, or if undef, fills it with a new line of data from the IMAP
4134 connection socket and then begins processing.
4135  
4136 If the next atom is:
4137  
4138 =over 4
4139  
4140 =item *
4141  
4142 An unquoted string, simply returns the string.
4143  
4144 =item *
4145  
4146 A quoted string, unquotes the string, changes any occurances
4147 of \" to " and returns the string.
4148  
4149 =item *
4150  
4151 A literal (e.g. {NBytes}\r\n), reads the number of bytes of data
4152 in the literal into a scalar or file (depending on C<literal_handle_control>).
4153  
4154 =item *
4155  
4156 A bracketed structure, reads all the sub-atoms within the structure
4157 and returns an array reference with all the sub-atoms.
4158  
4159 =back
4160  
4161 In each case, after parsing the atom, it removes any trailing space separator,
4162 and then returns the remainder of the line to $Self->{ReadLine} ready for the
4163 next call to C<_next_atom()>.
4164  
4165 =cut
4166 sub _next_atom {
4167 my ($Self, $Atom, $CurAtom, @AtomStack) = (+shift, undef, undef);
4168 my ($Line, $AtomRef) = ($Self->{ReadLine}, \$Atom);
4169  
4170 # Fill line buffer if nothing left
4171 $Line = $Self->_imap_socket_read_line() if !defined $Line;
4172  
4173 # While this is a recursive structure, doing some profiling showed
4174 # that this call was taking up quite a bit of time in the application
4175 # I was using this module with. Thus I've tried to optimise the code
4176 # a bit by turning it into a loop with an explicit stack and keeping
4177 # the most common cases quick.
4178  
4179 # Always do this once, and keep doing it while we're within
4180 # a bracketed list of items
4181 do {
4182  
4183 # Single item? (and any trailing space)
4184 # (make it trailing spaces, due to buggy XIMAPPROXY)
4185 if ($Line =~ m/\G([^()\"{\s]+)(?: +|\z|(?=\)))/gc) {
4186 # Add to current atom. If there's a stack, must be within a bracket
4187 if (scalar @AtomStack) {
4188 push @$AtomRef, $1 eq 'NIL' ? undef : $1;
4189 } else {
4190 $$AtomRef = $1 eq 'NIL' ? undef : $1;
4191 }
4192 }
4193  
4194 # Quoted section? (but non \" end quote and any trailing space)
4195 elsif ($Line =~ m/\G"((?:\\.|[^"])*?)"(?: |\z|(?=\)))/gc) {
4196 # Unquote quoted items
4197 ($CurAtom = $1) =~ s/\\(.)/$1/g;
4198 # Add to current atom. If there's a stack, must be within a bracket
4199 if (scalar @AtomStack) {
4200 push @$AtomRef, $CurAtom;
4201 } else {
4202 $$AtomRef = $CurAtom;
4203 }
4204 }
4205
4206 # Bracket?
4207 elsif ($Line =~ m/\G\(/gc) {
4208 # Begin a new sub-array
4209 my $CurAtom = [];
4210 # Add to current atom. If there's a stack, must be within a bracket
4211 if (scalar @AtomStack) {
4212 push @$AtomRef, $CurAtom;
4213 } else {
4214 $$AtomRef = $CurAtom;
4215 }
4216  
4217 # Check for simple response list to fast parse
4218 if ($Line =~ m/\G([^()\"{}~\s]+(?: [^()\"{}~\s]+)*)\) ?/gc) {
4219 push @$CurAtom, map { $_ eq 'NIL' ? undef : $_ } split(' ', $1);
4220  
4221 } else {
4222 # Add current ref to stack and update
4223 push @AtomStack, $AtomRef;
4224 $AtomRef = $CurAtom;
4225 }
4226  
4227 }
4228  
4229 # End bracket? (and possible trailing space)
4230 elsif ($Line =~ m/\G\) ?/gc) {
4231 # Close existing sub-array
4232 if (!scalar @AtomStack) {
4233 die "IMAPTalk: Unexpected close bracket in IMAP response : '$Line'";
4234 }
4235 $AtomRef = pop @AtomStack;
4236 }
4237  
4238 # Literal or binary literal? (Must end line)
4239 elsif ($Line =~ m/\G~?\{(\d+)\}$/gc) {
4240 my $Bytes = $1;
4241 $CurAtom = undef;
4242 if ($Self->{LiteralControl}) {
4243 if (ref($Self->{LiteralControl}) eq 'CODE') {
4244 $CurAtom = $Self->{LiteralControl}->($Bytes);
4245 } else {
4246 $CurAtom = $Self->{LiteralControl};
4247 }
4248 }
4249 if ($CurAtom) {
4250 $Self->_copy_imap_socket_to_handle($CurAtom, $Bytes);
4251 }
4252 else {
4253 # Capture with regexp to untaint
4254 my $Content = $Self->_imap_socket_read_bytes($Bytes);
4255 ($CurAtom) = ($Content =~ /^(.*)$/s);
4256 }
4257 # Read new line and strip first space if any
4258 $Line = $Self->_imap_socket_read_line();
4259 $Line =~ s/^ //;
4260 # Add to current atom. If there's a stack, must be within a bracket
4261 if (scalar @AtomStack) {
4262 push @$AtomRef, $CurAtom;
4263 } else {
4264 $$AtomRef = $CurAtom;
4265 }
4266 }
4267  
4268 # End of line?
4269 elsif ($Line =~ m/\G$/gc) {
4270 # Should not be within brackets
4271 if (scalar @AtomStack) {
4272 die "IMAPTalk: Unexpected end of line in IMAP response : '".$Self->{ReadLine}."'";
4273 }
4274 # Otherwise fine, we're about to exit anyway
4275 }
4276  
4277 else {
4278 die "IMAPTalk: Error parsing atom in IMAP response : '$Line'";
4279 }
4280  
4281 # Repeat while we're within brackets
4282 } while (scalar @AtomStack);
4283  
4284 # Return rest of line to read line buffer
4285 $Self->{ReadLine} = substr($Line, pos($Line) // 0);
4286  
4287 return $Atom;
4288 }
4289  
4290 =item I<_next_simple_atom($Self)>
4291  
4292 Faster version of _next_atom() for known simple cases
4293  
4294 =cut
4295 sub _next_simple_atom {
4296 my $Self = shift;
4297  
4298 # Fill line buffer if nothing left
4299 my $Line = $Self->{ReadLine};
4300 $Line = $Self->_imap_socket_read_line() if !defined $Line;
4301  
4302 # Should be single item
4303 if ($Line =~ m/\G([^()\"{}~\s]+) ?/gc) {
4304 my $Atom = $1 eq 'NIL' ? undef : $1;
4305  
4306 # Return rest of line to read line buffer
4307 $Self->{ReadLine} = substr($Line, pos($Line));
4308  
4309 return $Atom;
4310 } else {
4311 die "IMAPTalk: Expected simple atom, got: " . substr($Line, 0, 100);
4312 }
4313 }
4314  
4315 =item I<_remaining_atoms($Self)>
4316  
4317 Returns all the remaining atoms for the current line in the read line
4318 buffer as an array reference. Leaves $Self->{ReadLine} eq ''.
4319 See C<_next_atom()>
4320  
4321 =cut
4322 sub _remaining_atoms() {
4323 my ($Self, $SlurpIDs) = @_;
4324  
4325 # A hack. 'search' and 'sort' commands return a ID/UID list to end-of-line.
4326 # Use a quick loop to pull these out one at a time and cast to int() which
4327 # reduces memory usage, and is faster than general _next_atom() calls
4328 if ($SlurpIDs) {
4329 my $res = _read_int_list($Self->{ReadLine});
4330 $Self->{ReadLine} = '';
4331 return $res;
4332 }
4333  
4334 my @AtomList;
4335  
4336 # Pull all atoms until no line left
4337 while ($Self->{ReadLine} ne '') {
4338 push @AtomList, $Self->_next_atom();
4339 }
4340  
4341 return \@AtomList;
4342 }
4343  
4344 =item I<_remaining_line($Self)>
4345  
4346 Returns the remaining data in the read line buffer ($Self->{ReadLine}) as
4347 a scalar string/data value.
4348  
4349 =cut
4350 sub _remaining_line {
4351 my $Line = $_[0]->{ReadLine};
4352 $_[0]->{ReadLine} = '';
4353 return $Line;
4354 }
4355  
4356 =item I<_fill_imap_read_buffer($Self)>
4357  
4358 Wait until data is available on the IMAP connection socket (or a timeout
4359 occurs). Read the data into the internal buffer $Self->{ReadBuf}. You
4360 can then use C<_imap_socket_read_line()>, C<_imap_socket_read_bytes()>
4361 or C<_copy_imap_socket_to_handle()> to read data from the buffer in
4362 lines or bytes at a time.
4363  
4364 =cut
4365 sub _fill_imap_read_buffer {
4366 my ($Self, $Timeout, $Append) = @_;
4367 my $Buffer = '';
4368 $Timeout = $Self->{Timeout} if !defined $Timeout;
4369 my $Blocking = $Self->{UseBlocking};
4370  
4371 # Timeout not 0, nothing to do if buffer already has data.
4372 if (!defined($Timeout) || $Timeout != 0) {
4373 return 1 if !$Append && length($Self->{ReadBuf});
4374 }
4375  
4376 # Wait for data to become available, signals can interrupt
4377 # select() calls, so loop until definitely past $Timeout time
4378 my @ReadList;
4379 my ($StartTime, $UsedTime) = (time, 0);
4380 do {
4381 if ($Blocking) {
4382 @ReadList = ( $Self->{Socket} );
4383 }
4384 else {
4385 my $ThisTimeout = $Timeout;
4386 @ReadList =
4387 $Self->{Select}->can_read(
4388 defined($ThisTimeout) ? ( $ThisTimeout - $UsedTime ) : () );
4389 }
4390 $UsedTime = time - $StartTime;
4391 } while (!@ReadList && (!defined($Timeout) || $UsedTime < $Timeout));
4392  
4393 # If no handles, then timedout
4394 if (scalar(@ReadList) == 0) {
4395 die "IMAPTalk: Read timed out on socket";
4396 }
4397  
4398 # Check assumption...
4399 if ($ReadList[0] != $Self->{Socket}) {
4400 die "IMAPTalk: Read handles don't match. Internal error";
4401 }
4402  
4403 # Now read data into read buffer
4404 my $IsBlocking = $Self->{Socket}->blocking();
4405 $Self->{Socket}->blocking(0) if !$Blocking;
4406 my $BytesRead = $Self->{Socket}->sysread($Buffer, 16384);
4407 $Self->{Socket}->blocking($IsBlocking) if !$Blocking;
4408 CORE::select(undef, undef, undef, 0.25) if $Self->{go_slow};
4409  
4410 # The select told us there was data, if there wasn't
4411 # any, it means the other end closed the connection
4412 if (!defined $BytesRead || $BytesRead == 0) {
4413 $Self->state(Unconnected);
4414 die "IMAPTalk: IMAP Connection closed by other end: $!";
4415 }
4416  
4417 if ($Self->{CompressInflate}) {
4418 my ($data, $error) = $Self->{CompressInflate}->inflate($Buffer);
4419 die "FAILED TO INFLATE $error ($Buffer)" if $error;
4420 $Buffer = $data;
4421 }
4422  
4423 # Store in read buffer
4424 $Self->{ReadBuf} .= $Buffer;
4425  
4426 return 1;
4427 }
4428  
4429 =item I<_imap_socket_read_line($Self)>
4430  
4431 Read a \r\n terminated list from the buffered IMAP connection socket.
4432  
4433 =cut
4434 sub _imap_socket_read_line {
4435 my $Self = shift;
4436  
4437 while (1) {
4438  
4439 # Got end of line chars?
4440 if ((my $LineLen = index($Self->{ReadBuf}, LB)) != -1) {
4441  
4442 # Remove line from buffer (including CRLF)
4443 my $Line = substr($Self->{ReadBuf}, 0, $LineLen + LBLEN, '');
4444 $Self->_trace("S: " . substr($Line, 0, - LBLEN) . "\n") if $Self->{Trace};
4445  
4446 # Remove CRLF on return
4447 return substr($Line, 0, - LBLEN);
4448 }
4449  
4450 # Add to buffer
4451 $Self->_fill_imap_read_buffer(undef, 1);
4452 }
4453 return 1;
4454 }
4455  
4456 =item I<_imap_socket_read_bytes($Self, $NBytes)>
4457  
4458 Read a certain number of bytes from the buffered IMAP connection socket.
4459  
4460 =cut
4461 sub _imap_socket_read_bytes {
4462 my ($Self, $Bytes) = @_;
4463  
4464 while (length($Self->{ReadBuf}) < $Bytes) {
4465 $Self->_fill_imap_read_buffer(undef, 1);
4466 }
4467  
4468 return substr($Self->{ReadBuf}, 0, $Bytes, '');
4469 }
4470  
4471 =item I<_imap_socket_out($Self, $Data)>
4472  
4473 Write the data in $Data to the IMAP connection socket.
4474  
4475 =cut
4476 sub _imap_socket_out {
4477 my $Self = shift;
4478  
4479 # Do tracing
4480 $Self->_trace("C: " . $_[0]) if $Self->{Trace};
4481  
4482 if ($Self->{CompressDeflate}) {
4483 my ($bytes, $error) = $Self->{CompressDeflate}->deflate($_[0]);
4484 die "FAILED TO DEFLATE $error" if $error;
4485 $Self->_imap_socket_write_bytes($bytes);
4486 }
4487 else {
4488 $Self->_imap_socket_write_bytes($_[0]);
4489 }
4490  
4491 $Self->_imap_socket_flush();
4492 }
4493  
4494 sub _imap_socket_write_bytes {
4495 my $Self = shift;
4496  
4497 # Keep track of bytes written and total number to write
4498 my ($WCount, $TCount) = (0, length($_[0]));
4499  
4500 # Loop to write out all the data if needs multiple passes
4501 while ($TCount != $WCount) {
4502 my $NWrite = $Self->{Socket}->syswrite($_[0], $TCount - $WCount, $WCount);
4503 if (!defined $NWrite) {
4504 # A bit hacky, but try and avoid exposing password
4505 my $Data = $_[0];
4506 $Data =~ s/^(\d+ login \S+ )("(?:\\.|[^"])*?"|[^"\s]*)/$1 . ("*" x length($2))/e;
4507 my $TryData = substr($Data, $WCount, $TCount - $WCount);
4508 die 'IMAPTalk: Error writing data "' . Dumper($TryData) . '" to socket.';
4509 }
4510 $WCount += $NWrite;
4511 }
4512  
4513 return 1;
4514 }
4515  
4516 sub _imap_socket_flush {
4517 my $Self = shift;
4518 if ($Self->{CompressDeflate}) {
4519 my ($bytes, $error) = $Self->{CompressDeflate}->flush(Compress::Zlib::Z_FULL_FLUSH());
4520 die "FAILED TO FLUSH $error" if $error;
4521 $Self->_imap_socket_write_bytes($bytes) if $bytes ne '';
4522 }
4523 }
4524  
4525 =item I<_copy_handle_to_imapsocket($Self, $InHandle)>
4526  
4527 Copy a given number of bytes from a file handle to the IMAP connection
4528  
4529 =cut
4530 sub _copy_handle_to_imap_socket {
4531 my ($Self, $InHandle) = @_;
4532  
4533 # Loop over in handle reading chunks at a time and writing to the out handle
4534 my $Val;
4535 while ($InHandle->read($Val, 8192)) {
4536 if ($Self->{CompressDeflate}) {
4537 my ($bytes, $error) = $Self->{CompressDeflate}->deflate($Val);
4538 die "FAILED TO DEFLATE $error" if $error;
4539 $Self->_imap_socket_write_bytes($bytes);
4540 }
4541 else {
4542 $Self->_imap_socket_write_bytes($Val);
4543 }
4544 }
4545 $Self->_imap_socket_flush();
4546  
4547 # Done
4548 return 1;
4549 }
4550  
4551 =item I<_copy_imap_socket_to_handle($Self, $OutHandle, $NBytes)>
4552  
4553 Copies data from the IMAP socket to a file handle. This is different
4554 to _copy_handle_to_imap_socket() because we internally buffer the IMAP
4555 socket so we can't just use it to copy from the socket handle, we
4556 have to copy the contents of our buffer first.
4557  
4558 The number of bytes specified must be available on the IMAP socket,
4559 if the function runs out of data it will 'die' with an error.
4560
4561 =cut
4562 sub _copy_imap_socket_to_handle {
4563 my ($Self, $OutHandle, $NBytes) = @_;
4564  
4565 # Loop over socket reading chunks at a time and writing to the out handle
4566 my $Val;
4567 while ($NBytes) {
4568 my $NToRead = ($NBytes > 16384 ? 16384 : $NBytes);
4569 $Val = $Self->_imap_socket_read_bytes($NToRead);
4570 my $NRead = length($Val);
4571 if (length($Val) == 0) {
4572 die 'IMAPTalk: Error reading data from socket.' . $@;
4573 }
4574 $NBytes -= $NRead;
4575  
4576 my $NWritten = 0;
4577 while ($NWritten != $NRead) {
4578 my $NWrite = syswrite($OutHandle,$Val, $NRead-$NWritten, $NWritten);
4579 if (!defined $NWrite) {
4580 die 'IMAPTalk: Error writing data to io handle.' . $@;
4581 }
4582 $NWritten += $NWrite;
4583 }
4584 }
4585  
4586 # Done
4587 return 1;
4588 }
4589
4590 =item I<_quote($String)>
4591  
4592 Returns an IMAP quoted version of a string. This place "..." around the
4593 string, and replaces any internal " with \".
4594
4595 =cut
4596 sub _quote {
4597 # Replace " and \ with \" and \\ and surround with "..."
4598 my $Str = shift;
4599 $Str =~ s/(["\\])/\\$1/g;
4600 return \qq{"$Str"};
4601 }
4602  
4603 =back
4604 =cut
4605  
4606 =head1 INTERNAL PARSING FUNCTIONS
4607  
4608 =over 4
4609 =cut
4610  
4611 =item I<_parse_list_to_hash($ListRef, $Recursive)>
4612  
4613 Parses an array reference list of ($Key, $Value) pairs into a hash.
4614 Makes sure that all the keys are lower cased (lc) first.
4615  
4616 =cut
4617 sub _parse_list_to_hash {
4618 my $ContentHashList = shift || [];
4619 my $Recursive = shift;
4620  
4621 ref($ContentHashList) eq 'ARRAY' || return { };
4622  
4623 my %Res;
4624 while (@$ContentHashList) {
4625 my ($Param, $Val) = (shift @$ContentHashList, shift @$ContentHashList);
4626  
4627 $Val = _parse_list_to_hash($Val, $Recursive-1)
4628 if (ref($Val) && $Recursive);
4629  
4630 $Res{lc($Param)} = $Val;
4631 }
4632  
4633 return \%Res;
4634 }
4635  
4636 sub _find_arg {
4637 my ($Self, $Args, $Term, $CB) = @_;
4638  
4639 for (0 .. @$Args-1) {
4640 if (!ref $Args->[$_] && lc($Args->[$_]) eq $Term) {
4641 # Alias arg into $_ and call callback
4642 $CB->() for $Args->[$_+1];
4643 }
4644 }
4645 }
4646  
4647 =item I<_fix_folder_name($FolderName, %Opts)>
4648  
4649 Changes a folder name based on the current root folder prefix as set
4650 with the C<set_root_prefix()> call.
4651  
4652 Wildcard => 1 = a folder name with % or * is left alone
4653 NoEncoding => 1 = don't do modified utf-7 encoding, leave as unicode
4654  
4655 =cut
4656 sub _fix_folder_name {
4657 my ($Self, $FolderName, %Opts) = @_;
4658  
4659 return '' if $FolderName eq '';
4660  
4661 # Map nicer looking Inbox to canonical INBOX
4662 return 'INBOX' if ($FolderName eq 'Inbox' and not $Self->{PreserveINBOX});
4663  
4664 # Handle select of special-use folder (cyrus feature)
4665 return $FolderName if $FolderName =~ m{^\\};
4666  
4667 $FolderName = $Self->_fix_folder_encoding($FolderName) unless $Opts{NoEncoding};
4668  
4669 return $FolderName if $Opts{Wildcard} && $FolderName =~ /[\*\%]/;
4670  
4671 my $RootFolderMatch = $Self->{RootFolderMatch}
4672 || return $FolderName;
4673  
4674 # If no root folder, just return passed in folder
4675 return $FolderName if $FolderName =~ $RootFolderMatch;
4676  
4677 my ($RootFolder, $Separator) = @$Self{'RootFolder', 'Separator'};
4678 return !$RootFolder ? $FolderName : $RootFolder . $Separator . $FolderName;
4679 }
4680  
4681 =item I<_fix_folder_encoding($FolderName)>
4682  
4683 Encode folder name using IMAP-UTF-7
4684  
4685 =cut
4686 sub _fix_folder_encoding {
4687 my ($Self, $FolderName) = @_;
4688  
4689 if ( $Self->unicode_folders()
4690 && ( $FolderName =~ m{[^\x00-\x25\x27-\x7f]} ) )
4691 {
4692 $FolderName = Encode::encode( 'IMAP-UTF-7', $FolderName );
4693 }
4694  
4695 return $FolderName;
4696 }
4697  
4698 =item I<_unfix_folder_name($FolderName)>
4699  
4700 Unchanges a folder name based on the current root folder prefix as set
4701 with the C<set_root_prefix()> call.
4702  
4703 =cut
4704 sub _unfix_folder_name {
4705 my ($Self, $FolderName) = @_;
4706  
4707 my $UFM = $Self->{UnrootFolderMatch};
4708 $FolderName =~ s/^$UFM// if $UFM;
4709  
4710 # Map canonical INBOX to nicer looking Inbox
4711 $FolderName = "Inbox" if ($FolderName eq "INBOX" && not $Self->{PreserveINBOX});
4712  
4713 my $UnicodeFolders = $Self->unicode_folders();
4714 if ( $UnicodeFolders && ( $FolderName =~ m{&} ) )
4715 {
4716 $FolderName = Encode::decode( 'IMAP-UTF-7', $FolderName );
4717 }
4718  
4719 return $FolderName;
4720 }
4721  
4722 =item I<_fix_message_ids($MessageIds)>
4723  
4724 Used by IMAP commands to handle a number of different ways that message
4725 IDs can be specified.
4726  
4727 =item I<Method arguments>
4728  
4729 =over 4
4730  
4731 =item B<$MessageIds>
4732  
4733 String or array ref which specified the message IDs or UIDs.
4734  
4735 =back
4736  
4737 The $MessageIds parameter may take the following forms:
4738  
4739 =over 4
4740  
4741 =item B<array ref>
4742  
4743 Array is turned into a string of comma separated ID numbers.
4744  
4745 =item B<1:*>
4746  
4747 Normally a * would result in the message ID string being quoted.
4748 This ensure that such a range string is not quoted because some
4749 servers (e.g. cyrus) don't like.
4750  
4751 =back
4752  
4753 =cut
4754 sub _fix_message_ids {
4755 my $Item = shift;
4756 # If the item is an array reference, turn into a comma separated of items
4757 if (ref($Item) eq 'ARRAY') {
4758 my @Src = sort { $a <=> $b } @$Item;
4759 push @Src, 0; # end marker to make the logic below simpler
4760 my @Dest;
4761 my $Start;
4762 my $Prev;
4763 while (defined (my $Single = shift @Src)) {
4764 if (defined $Prev and $Single == $Prev + 1) {
4765 $Start = $Prev unless defined $Start;
4766 }
4767 else {
4768 if (defined $Start) {
4769 push @Dest, "$Start:$Prev";
4770 $Start = undef;
4771 }
4772 elsif (defined $Prev) {
4773 push @Dest, $Prev;
4774 }
4775 }
4776 $Prev = $Single;
4777 }
4778 # Make scalar ref, so we don't quote
4779 $Item = \join(',', @Dest);
4780 }
4781 # If the item ends in a *, don't put "'s around it. This is
4782 # a hack so "1:*" doesn't end up with quotes that cyrus doesn't like
4783 $Item = \"$Item" if !ref($Item) && $Item =~ /\*$/;
4784 return $Item;
4785 }
4786  
4787 =item I<_parse_email_address($EmailAddressList)>
4788  
4789 Converts a list of IMAP email address structures as parsed and returned
4790 from an IMAP fetch (envelope) call into a single RFC 822 email string
4791 (e.g. "Person 1 Name" <ename@ecorp.com>, "Person 2 Name" <...>, etc) to
4792 finally return to the user.
4793  
4794 This is used to parse an envelope structure returned from a fetch call.
4795
4796 See the documentation section 'FETCH RESULTS' for more information.
4797  
4798 =cut
4799 sub _parse_email_address {
4800 my $EmailAddressList = shift || [];
4801 my $DecodeUTF8 = shift;
4802  
4803 # Email addresses always come as a list of addresses (possibly in groups)
4804 my @EmailGroups = ([ undef ]);
4805 foreach my $Adr (@$EmailAddressList) {
4806  
4807 # Check address assumption
4808 scalar(@$Adr) == 4
4809 || die "IMAPTalk: Wrong number of fields in email address structure " . Dumper($Adr);
4810  
4811 # No hostname is start/end of group
4812 if (!defined $Adr->[0] && !defined $Adr->[3]) {
4813 push @EmailGroups, [ $Adr->[2] ];
4814 next;
4815 }
4816  
4817 # Build 'ename@ecorp.com' part
4818  
4819 # If domain is "unspecified-domain" and no name part, move localpart to name part
4820 if (defined $Adr->[3] && $Adr->[3] eq "unspecified-domain" && !$Adr->[0]) {
4821 @$Adr[0,2,3] = ($Adr->[2], undef, undef);
4822 }
4823  
4824 my $EmailAdr = defined $Adr->[2] ? $Adr->[2] : '';
4825 my $EmailDom = defined $Adr->[3] ? $Adr->[3] : '';
4826 my $EmailStr = $EmailAdr || $EmailDom ? $EmailAdr . '@' . $EmailDom : '';
4827  
4828 # If the email address has a name, add it at the start and put <> around address
4829 if (defined $Adr->[0] and $Adr->[0] ne '') {
4830 # CRLF's are folding that's leaked into data where it shouldn't, strip them
4831 $Adr->[0] =~ s/\r?\n//g;
4832 _decode_utf8($Adr->[0]) if $DecodeUTF8;
4833 # Strip any existing " and \ chars
4834 $Adr->[0] =~ s/["\\]//g;
4835 $EmailStr = '"' . $Adr->[0] . '"' . ($EmailStr ? ' <' . $EmailStr . '>' : '');
4836 }
4837  
4838 push @{$EmailGroups[-1]}, $EmailStr;
4839 }
4840  
4841 # Join the results with commas between each address, and "groupname: adrs ;" for groups
4842 for (@EmailGroups) {
4843 my $GroupName = shift @$_;
4844 ($_ = undef), next if !defined $GroupName && !@$_;
4845 my $EmailAdrs = join ", ", @$_;
4846 $_ = defined($GroupName) ? $GroupName . ': ' . $EmailAdrs . ';' : $EmailAdrs;
4847 }
4848  
4849 return join " ", grep { defined $_ } @EmailGroups;
4850 }
4851  
4852 =item I<_parse_envelope($Envelope, $IncludeRaw, $DecodeUTF8)>
4853  
4854 Converts an IMAP envelope structure as parsed and returned from an
4855 IMAP fetch (envelope) call into a convenient hash structure.
4856  
4857 If $IncludeRaw is true, includes the XXX-Raw fields, otherwise
4858 these are left out.
4859  
4860 If $DecodeUTF8 is true, then checks if the fields contain
4861 any quoted-printable chars, and decodes them to a Perl UTF8
4862 string if they do.
4863  
4864 See the documentation section 'FETCH RESULTS' from more information.
4865  
4866 =cut
4867 sub _parse_envelope {
4868 my ($Env, $IncludeRaw, $DecodeUTF8) = @_;
4869  
4870 # Check envelope assumption
4871 scalar(@$Env) == 10
4872 || die "IMAPTalk: Wrong number of fields in envelope structure " . Dumper($Env);
4873  
4874 _decode_utf8($Env->[1]) if $DecodeUTF8;
4875  
4876 # Setup hash directly from envelope structure
4877 my %Res = (
4878 'Date', $Env->[0],
4879 'Subject', $Env->[1],
4880 'From', _parse_email_address($Env->[2], $DecodeUTF8),
4881 'Sender', _parse_email_address($Env->[3], $DecodeUTF8),
4882 'Reply-To', _parse_email_address($Env->[4], $DecodeUTF8),
4883 'To', _parse_email_address($Env->[5], $DecodeUTF8),
4884 'Cc', _parse_email_address($Env->[6], $DecodeUTF8),
4885 'Bcc', _parse_email_address($Env->[7], $DecodeUTF8),
4886 ($IncludeRaw ? (
4887 'From-Raw', $Env->[2],
4888 'Sender-Raw', $Env->[3],
4889 'Reply-To-Raw',$Env->[4],
4890 'To-Raw', $Env->[5],
4891 'Cc-Raw', $Env->[6],
4892 'Bcc-Raw', $Env->[7],
4893 ) : ()),
4894 'In-Reply-To', $Env->[8],
4895 'Message-ID', $Env->[9]
4896 );
4897  
4898 return \%Res;
4899 }
4900  
4901 =item I<_parse_bodystructure($BodyStructure, $IncludeRaw, $DecodeUTF8, $PartNum)>
4902  
4903 Parses a standard IMAP body structure and turns it into a Perl friendly
4904 nested hash structure. This routine is recursive and you should not
4905 pass a value for $PartNum when called for the top level bodystructure
4906 item. Note that this routine destroys the array reference structure
4907 passed in as $BodyStructure.
4908  
4909 See the documentation section 'FETCH RESULTS' from more information
4910  
4911 =cut
4912 sub _parse_bodystructure {
4913 my ($Bs, $IncludeRaw, $DecodeUTF8, $PartNum, $IsMultipart) = @_;
4914 my %Res;
4915  
4916 # If the first item is a reference, then it's a MIME multipart structure
4917 if (ref($Bs->[0])) {
4918  
4919 # Multipart items are of the form: [ part 1 ] [ part 2 ] ...
4920 # "MIME-Subtype" "Content-Type" "Content-Disposition" "Content-Language"
4921  
4922 # Process each mime sub-part recursively
4923 my ($Part, @SubParts);
4924 for ($Part = 1; ref($Bs->[0]); $Part++) {
4925 my $SubPartNum = ($PartNum ? $PartNum . "." : "") . $Part;
4926 my $Res = _parse_bodystructure(shift(@$Bs), $IncludeRaw, $DecodeUTF8, $SubPartNum, 1);
4927 push @SubParts, $Res;
4928 }
4929  
4930 # Setup multi-part hash
4931 %Res = (
4932 'MIME-Subparts', \@SubParts,
4933 'MIME-Type', 'multipart',
4934 'MIME-Subtype', lc(shift(@$Bs) // ''),
4935 'Content-Type', _parse_list_to_hash(shift(@$Bs)),
4936 'Disposition-Type', lc(shift(@{$Bs->[0]}) // ''),
4937 'Content-Disposition', _parse_list_to_hash(@{shift(@$Bs)}),
4938 'Content-Language', shift(@$Bs),
4939 'Content-Location', shift(@$Bs),
4940 # Shouldn't be anything after this. Add as remainder if there is
4941 'Remainder', $Bs
4942 );
4943 }
4944  
4945 # Otherwise it's a normal MIME entity
4946 else {
4947  
4948 # Get the mime type and sub-type
4949 my ($MimeType, $MimeSubtype) = (lc(shift(@$Bs)), lc(shift(@$Bs)));
4950  
4951 # Partnum for getting the text part of an entity. Do this
4952 # here so recursive call works for any embedded messages
4953 $PartNum = $PartNum ? $PartNum . '.1' : '1'
4954 if !$IsMultipart;
4955  
4956 # Pull out special fields for 'text' or 'message/rfc822' types
4957 if ($MimeType eq 'text') {
4958 %Res = (
4959 'Lines', splice(@$Bs, 5, 1)
4960 );
4961 } elsif ($MimeType eq 'message' && $MimeSubtype eq 'rfc822') {
4962  
4963 # message/rfc822 includes the messages envelope and bodystructure
4964 my @MsgParts = splice(@$Bs, 5, 3);
4965 %Res = (
4966 'Message-Envelope', _parse_envelope(shift(@MsgParts), $IncludeRaw, $DecodeUTF8),
4967 'Message-Bodystructure', _parse_bodystructure(shift(@MsgParts), $IncludeRaw, $DecodeUTF8, $PartNum),
4968 'Message-Lines', shift(@MsgParts)
4969 );
4970 }
4971  
4972 # All normal mime-entities have these parts
4973 %Res = (
4974 %Res,
4975 'MIME-Type', $MimeType,
4976 'MIME-Subtype', $MimeSubtype,
4977 'Content-Type', _parse_list_to_hash(shift(@$Bs)),
4978 'Content-ID', shift(@$Bs),
4979 'Content-Description', shift(@$Bs),
4980 'Content-Transfer-Encoding', shift(@$Bs),
4981 'Size', shift(@$Bs),
4982 'Content-MD5', shift(@$Bs),
4983 'Disposition-Type', lc(shift(@{$Bs->[0]}) // ''),
4984 'Content-Disposition', _parse_list_to_hash(@{shift(@$Bs)}),
4985 'Content-Language', shift(@$Bs),
4986 'Content-Location', shift(@$Bs),
4987 # Shouldn't be anything after this. Add as remainder if there is
4988 'Remainder', $Bs
4989 );
4990  
4991 }
4992  
4993 # Finally set the IMAP body part number and overall mime type
4994 $Res{'IMAP-Partnum'} = $PartNum || '';
4995 $Res{'MIME-TxtType'} = $Res{'MIME-Type'} . '/' . $Res{'MIME-Subtype'};
4996  
4997 return \%Res;
4998 }
4999  
5000 =item I<_parse_fetch_annotation($AnnotateItem)>
5001  
5002 Takes the result from a single IMAP annotation item
5003 into a Perl friendly structure.
5004  
5005 See the documentation section 'FETCH RESULTS' from more information.
5006  
5007 =cut
5008 sub _parse_fetch_annotation {
5009 my ($Value) = @_;
5010  
5011 return $Value unless ref($Value) eq 'ARRAY';
5012 my %Result = @$Value;
5013 map { $_ = { @$_ } if ref($_) eq 'ARRAY' } values %Result;
5014  
5015 return \%Result;
5016 }
5017  
5018 =item I<_parse_fetch_result($FetchResult)>
5019  
5020 Takes the result from a single IMAP fetch response line and parses it
5021 into a Perl friendly structure.
5022  
5023 See the documentation section 'FETCH RESULTS' from more information.
5024  
5025 =cut
5026 sub _parse_fetch_result {
5027 my ($FetchResult, $ParseMode) = @_;
5028  
5029 # Loop over fetch results
5030 my %ResultHash;
5031 while (@$FetchResult) {
5032 # Fetch results are in type, value pairs
5033 my $Type = lc(shift(@$FetchResult));
5034 my $Value = shift(@$FetchResult);
5035  
5036 # Process known fetch results into perl form
5037 if ($Type eq 'envelope') {
5038 $Value = _parse_envelope($Value, @$ParseMode{qw(EnvelopeRaw DecodeUTF8)})
5039 if $ParseMode->{Envelope};
5040 } elsif ($Type eq 'bodystructure') {
5041 $Value = _parse_bodystructure($Value, @$ParseMode{qw(EnvelopeRaw DecodeUTF8)})
5042 if $ParseMode->{BodyStructure};
5043 } elsif ($Type =~ /^(body|binary)(?:\.peek)?\[([^\]]*)/) {
5044 my $BodyArgs = $2;
5045  
5046 # Make 'body[]', 'body[]<0>', etc into plain 'body' (unless FullBody mode)
5047 $Type = $1;
5048  
5049 if ($BodyArgs =~ /^[\d.]*header/) {
5050 _parse_header_result($ResultHash{headers} ||= {}, $Value, $FetchResult);
5051 } else {
5052 $Type .= "[${BodyArgs}]" if $ParseMode->{FullBody}
5053 }
5054 } elsif ($Type eq 'annotation') {
5055 $Value = _parse_fetch_annotation($Value)
5056 if $ParseMode->{Annotation};
5057 }
5058  
5059 # Store result (either modified or original) into hash
5060 $ResultHash{$Type} = $Value;
5061 }
5062  
5063 return \%ResultHash;
5064 }
5065  
5066 =item I<_parse_header_result($HeaderResults, $Value, $FetchResult)>
5067  
5068 Take a body[header.fields (xyz)] fetch response and parse out the
5069 header fields and values
5070  
5071 =cut
5072 sub _parse_header_result {
5073 my ($HeaderResults, $Value, $FetchResult) = @_;
5074  
5075 # This is the response for requested headers
5076 # We don't care HOW they are requested, we just return what we've got
5077 # from the server, the result is returned in the key "headers"
5078 $Value = (splice(@$FetchResult,0,2))[1] if (ref($Value) eq 'ARRAY');
5079  
5080 my @HeaderLines = split(/[\r\n]+/,$Value);
5081  
5082 my $PrevHeader;
5083 for (@HeaderLines) {
5084 if (/^[\t ]+/){
5085 next unless $PrevHeader;
5086 # A continuation line belongs to the last element of the array
5087 $HeaderResults->{$PrevHeader}[-1] .= "\r\n" . $_;
5088 next;
5089 }
5090 next unless /^([\x21-\x39\x3b-\x7e]+):\s*(.*)$/;
5091 $PrevHeader = lc($1);
5092 push @{$HeaderResults->{$PrevHeader}}, $2;
5093 }
5094 }
5095  
5096 =item I<_decode_utf8($Value)>
5097  
5098 Decodes the passed quoted printable value to a Perl Unicode string.
5099  
5100 =cut
5101 sub _decode_utf8 {
5102 for (@_) {
5103 next if !defined $_;
5104 if (/$RFC2047Encoded/) {
5105 # Fix dumb, dumb ANSI_X3.4-1968 encoding. It's not actually a valid
5106 # charset according to RFC2047, "." is an especial, so Encode ignores it
5107 # See http://en.wikipedia.org/wiki/ASCII for other aliases
5108 s/=\?ANSI_X3\.4-(?:1968|1986)\?/=?US-ASCII?/gi;
5109 eval { $_ = decode('MIME-Header', $_) };
5110 } elsif (/$NonAsciiData/) {
5111 # Try and guess
5112 my $GuessedCharSet = eval { detect($_) } // "utf-8";
5113 eval { $_ = decode($GuessedCharSet, $_) };
5114 }
5115 }
5116 }
5117  
5118 sub _read_int_list {
5119 my $line = shift;
5120  
5121 # substr and index is faster than regular expressions - we just trust
5122 # that the intervening characters are digits!
5123 my @List;
5124 my $oldpos = 0;
5125 while ((my $pos = index($line, ' ', $oldpos+1)) >= 0) {
5126 push @List, int(substr($line, $oldpos, ($pos - $oldpos)));
5127 $oldpos = $pos;
5128 }
5129 my $final = substr($line, $oldpos);
5130 push @List, int($final) if $final ne '' && $final ne ' ';
5131  
5132 return \@List;
5133 }
5134  
5135 =item I<_expand_sequence(@Sequences)>
5136  
5137 Expand a list of IMAP id sequences into a full list of ids
5138  
5139 =cut
5140 sub _expand_sequence {
5141 my @Ids;
5142 for (@_) {
5143 push(@Ids, int($1) .. int($2)), redo if /\G(\d+):(\d+),?/gc;
5144 push(@Ids, int($1)), redo if /\G(\d+),?/gc;
5145 next if /\G$/;
5146 die "unexpected sequence: " . substr($_, pos($_));
5147 }
5148 return @Ids;
5149 }
5150  
5151 =back
5152 =cut
5153  
5154 =head1 PERL METHODS
5155  
5156 =over 4
5157 =cut
5158  
5159 =item I<DESTROY()>
5160  
5161 Called by Perl when this object is destroyed. Logs out of the
5162 IMAP server if still connected.
5163  
5164 =cut
5165 sub DESTROY {
5166 my $e = $@; # Save errors from code calling us
5167 eval {
5168  
5169 my $Self = shift;
5170  
5171 # If socket exists, and connection is open and authenticated or
5172 # selected, do a logout
5173 if ($Self->{Socket} &&
5174 ($Self->state() == Authenticated || $Self->state() == Selected) &&
5175 $Self->is_open()) {
5176 $Self->logout();
5177 $Self->{Socket}->close();
5178 }
5179  
5180 };
5181 # $e .= " (in cleanup) $@" if $@;
5182 $@ = $e;
5183 }
5184  
5185 =back
5186 =cut
5187  
5188 =head1 SEE ALSO
5189  
5190 I<Net::IMAP>, I<Mail::IMAPClient>, I<IMAP::Admin>, RFC 3501
5191  
5192 Latest news/details can also be found at:
5193  
5194 http://cpan.robm.fastmail.fm/mailimaptalk/
5195  
5196 Available on github at:
5197  
5198 L<https://github.com/robmueller/mail-imaptalk/>
5199  
5200 =cut
5201  
5202 =head1 AUTHOR
5203  
5204 Rob Mueller E<lt>cpan@robm.fastmail.fmE<gt>. Thanks to Jeremy Howard
5205 E<lt>j+daemonize@howard.fmE<gt> for socket code, support and
5206 documentation setup.
5207  
5208 =cut
5209  
5210 =head1 COPYRIGHT AND LICENSE
5211  
5212 Copyright (C) 2003-2016 by FastMail Pty Ltd
5213  
5214 This library is free software; you can redistribute it and/or modify
5215 it under the same terms as Perl itself.
5216  
5217 =cut
5218  
5219 1;
5220