blib/lib/Mail/IMAPTalk.pm untested

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