blib/lib/Mail/IMAPTalk.pm untested

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