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