forked from zetacomponents/Mail
/
imap_transport.php
2756 lines (2588 loc) · 97.3 KB
/
imap_transport.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* File containing the ezcMailImapTransport class.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* @package Mail
* @version //autogen//
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
*/
/**
* The class ezcMailImapTransport implements functionality for handling IMAP
* mail servers.
*
* The implementation supports most of the commands specified in:
* - {@link http://www.faqs.org/rfcs/rfc1730.html} (IMAP4)
* - {@link http://www.faqs.org/rfcs/rfc2060.html} (IMAP4rev1)
*
* Each user account on the IMAP server has it's own folders (mailboxes).
* Mailboxes can be created, renamed or deleted. All accounts have a special
* mailbox called Inbox which cannot be deleted or renamed.
*
* Messages are organized in mailboxes, and are identified by a message number
* (which can change over time) and a unique ID (which does not change under
* normal circumstances). The commands operating on messages can handle both
* modes (message numbers or unique IDs).
*
* Messages are marked by certain flags (SEEN, DRAFT, etc). Deleting a message
* actually sets it's DELETED flag, and a later call to {@link expunge()} will
* delete all the messages marked with the DELETED flag.
*
* The IMAP server can be in different states. Most IMAP commands require
* that a connection is established and a user is authenticated. Certain
* commands require in addition that a mailbox is selected.
*
* The IMAP transport class allows developers to interface with an IMAP server.
* The commands which support unique IDs to refer to messages are marked with
* [*] (see {@link ezcMailImapTransportOptions} to find out how to enable
* unique IDs referencing):
*
* Basic commands:
* - connect to an IMAP server ({@link __construct()})
* - authenticate a user with a username and password ({@link authenticate()})
* - select a mailbox ({@link selectMailbox()})
* - disconnect from the IMAP server ({@link disconnect()})
*
* Work with mailboxes:
* - get the list of mailboxes of the user ({@link listMailboxes()})
* - create a mailbox ({@link createMailbox()})
* - rename a mailbox ({@link renameMailbox()})
* - delete a mailbox ({@link deleteMailbox()})
* - append a message to a mailbox ({@link append()})
* - select a mailbox ({@link selectMailbox()})
* - get the status of messages in the current mailbox ({@link status()})
* - get the number of messages with a certain flag ({@link countByFlag()})
*
* Work with message numbers (on the currently selected mailbox):
* - get the message numbers and sizes of all the messages ({@link listMessages()})
* - get the message numbers and IDs of all the messages ({@link listUniqueIdentifiers()})
* - [*] get the headers of a certain message ({@link top()})
* - [*] delete a message ({@link delete()} and {@link expunge()})
* - [*] copy messages to another mailbox ({@link copyMessages()})
* - [*] get the sizes of the specified messages ({@link fetchSizes()})
*
* Work with flags (on the currently selected mailbox):
* - [*] get the flags of the specified messages ({@link fetchFlags()})
* - [*] set a flag on the specified messages ({@link setFlag()})
* - [*] clear a flag from the specified messages ({@link clearFlag()})
*
* Work with {@link ezcMailImapSet} sets (parseable with {@link ezcMailParser})
* (on the currently selected mailbox):
* - [*] create a set from all messages ({@link fetchAll()})
* - [*] create a set from a certain message ({@link fetchByMessageNr()})
* - [*] create a set from a range of messages ({@link fetchFromOffset()})
* - [*] create a set from messages with a certain flag ({@link fetchByFlag()})
* - [*] create a set from a sorted range of messages ({@link sortFromOffset()})
* - [*] create a set from a sorted list of messages ({@link sortMessages()})
* - [*] create a set from a free-form search ({@link searchMailbox()})
*
* Miscellaneous commands:
* - get the capabilities of the IMAP server ({@link capability()})
* - get the hierarchy delimiter (useful for nested mailboxes) ({@link getHierarchyDelimiter()})
* - issue a NOOP command to keep the connection alive ({@link noop()})
*
* The usual operation with an IMAP server is illustrated by this example:
* <code>
* // create a new IMAP transport object by specifying the server name, optional port
* // and optional SSL mode
* $options = new ezcMailImapTransportOptions();
* $options->ssl = true;
* $imap = new ezcMailImapTransport( 'imap.example.com', null, $options );
*
* // Authenticate to the IMAP server
* $imap->authenticate( 'username', 'password' );
*
* // Select a mailbox (here 'Inbox')
* $imap->selectMailbox( 'Inbox' );
*
* // issue commands to the IMAP server
* // for example get the number of RECENT messages
* $recent = $imap->countByFlag( 'RECENT' );
*
* // see the above list of commands or consult the online documentation for
* // the full list of commands you can issue to an IMAP server and examples
*
* // disconnect from the IMAP server
* $imap->disconnect();
* </code>
*
* See {@link ezcMailImapTransportOptions} for other options you can specify
* for IMAP.
*
* @todo ignore messages of a certain size?
* @todo // support for signing?
* @todo listUniqueIdentifiers(): add UIVALIDITY value to UID (like in POP3).
* (if necessary).
*
* @property ezcMailImapTransportOptions $options
* Holds the options you can set to the IMAP transport.
*
* @package Mail
* @version //autogen//
* @mainclass
*/
class ezcMailImapTransport
{
/**
* Internal state when the IMAP transport is not connected to a server.
*
* @access private
*/
const STATE_NOT_CONNECTED = 1;
/**
* Internal state when the IMAP transport is connected to a server,
* but no successful authentication has been performed.
*
* @access private
*/
const STATE_NOT_AUTHENTICATED = 2;
/**
* Internal state when the IMAP transport is connected to a server
* and authenticated, but no mailbox is selected yet.
*
* @access private
*/
const STATE_AUTHENTICATED = 3;
/**
* Internal state when the IMAP transport is connected to a server,
* authenticated, and a mailbox is selected.
*
* @access private
*/
const STATE_SELECTED = 4;
/**
* Internal state when the IMAP transport is connected to a server,
* authenticated, and a mailbox is selected read only.
*
* @access private
*/
const STATE_SELECTED_READONLY = 5;
/**
* Internal state when the LOGOUT command has been issued to the IMAP
* server, but before the disconnect has taken place.
*
* @access private
*/
const STATE_LOGOUT = 6;
/**
* The response sent from the IMAP server is "OK".
*
* @access private
*/
const RESPONSE_OK = 1;
/**
* The response sent from the IMAP server is "NO".
*
* @access private
*/
const RESPONSE_NO = 2;
/**
* The response sent from the IMAP server is "BAD".
*
* @access private
*/
const RESPONSE_BAD = 3;
/**
* The response sent from the IMAP server is untagged (starts with "*").
*
* @access private
*/
const RESPONSE_UNTAGGED = 4;
/**
* The response sent from the IMAP server requires the client to send
* information (starts with "+").
*
* @access private
*/
const RESPONSE_FEEDBACK = 5;
/**
* Use UID commands (access messages by their unique ID).
*
* @access private
*/
const UID = 'UID ';
/**
* Use message number commands (access messages by their message numbers).
*
* @access private
*/
const NO_UID = '';
/**
* The string returned by Google IMAP servers when at connection time.
*
* @access private
*/
const SERVER_GIMAP = 'Gimap';
/**
* Basic flags are used by {@link setFlag()} and {@link clearFlag()}
*
* Basic flags:
* - ANSWERED - message has been answered
* - DELETED - message is marked to be deleted by later EXPUNGE
* - DRAFT - message is marked as a draft
* - FLAGGED - message is "flagged" for urgent/special attention
* - SEEN - message has been read
*
* @var array(string)
*/
protected static $basicFlags = array( 'ANSWERED', 'DELETED', 'DRAFT', 'FLAGGED', 'SEEN' );
/**
* Extended flags are used by {@link searchByFlag()}
*
* Basic flags:
* - ANSWERED - message has been answered
* - DELETED - message is marked to be deleted by later EXPUNGE
* - DRAFT - message is marked as a draft
* - FLAGGED - message is "flagged" for urgent/special attention
* - RECENT - message is recent
* - SEEN - message has been read
*
* Opposites of the above flags:
* - UNANSWERED
* - UNDELETED
* - UNDRAFT
* - UNFLAGGED
* - OLD
* - UNSEEN
*
* Composite flags:
* - NEW - equivalent to RECENT + UNSEEN
* - ALL - all the messages
*
* @var array(string)
*/
protected static $extendedFlags = array( 'ALL', 'ANSWERED', 'DELETED', 'DRAFT', 'FLAGGED', 'NEW', 'OLD', 'RECENT', 'SEEN', 'UNANSWERED', 'UNDELETED', 'UNDRAFT', 'UNFLAGGED', 'UNRECENT', 'UNSEEN' );
/**
* Used to generate a tag for sending commands to the IMAP server.
*
* @var string
*/
protected $currentTag = 'A0000';
/**
* Holds the connection state.
*
* @var int {@link STATE_NOT_CONNECTED},
* {@link STATE_NOT_AUTHENTICATED},
* {@link STATE_AUTHENTICATED},
* {@link STATE_SELECTED},
* {@link STATE_SELECTED_READONLY} or
* {@link STATE_LOGOUT}.
*/
protected $state = self::STATE_NOT_CONNECTED;
/**
* Holds the currently selected mailbox.
*
* @var string
*/
protected $selectedMailbox = null;
/**
* Holds the connection to the IMAP server.
*
* @var ezcMailTransportConnection
*/
protected $connection = null;
/**
* Holds the string which identifies the IMAP server type.
*
* Used for fixing problems with Google IMAP (see issue #14360). Possible
* values are {@link self::SERVER_GIMAP} or null for all other servers.
*
* @todo Add identification strings for each existing IMAP server?
*
* @var string
*/
protected $serverType = null;
/**
* Holds the options for an IMAP transport connection.
*
* @var ezcMailImapTransportOptions
*/
private $options;
/**
* Creates a new IMAP transport and connects to the $server at $port.
*
* You can specify the $port if the IMAP server is not on the default port
* 993 (for SSL connections) or 143 (for plain connections). Use the $options
* parameter to specify an SSL connection.
*
* See {@link ezcMailImapTransportOptions} for options you can specify for
* IMAP.
*
* Example of creating an IMAP transport:
* <code>
* // replace with your IMAP server address
* $imap = new ezcMailImapTransport( 'imap.example.com' );
*
* // if you want to use SSL:
* $options = new ezcMailImapTransportOptions();
* $options->ssl = true;
*
* $imap = new ezcMailImapTransport( 'imap.example.com', null, $options );
* </code>
*
* @throws ezcMailTransportException
* if it was not possible to connect to the server
* @throws ezcBaseExtensionNotFoundException
* if trying to use SSL and the extension openssl is not installed
* @throws ezcBasePropertyNotFoundException
* if $options contains a property not defined
* @throws ezcBaseValueException
* if $options contains a property with a value not allowed
* @param string $server
* @param int $port
* @param ezcMailImapTransportOptions|array(string=>mixed) $options
*/
public function __construct( $server, $port = null, $options = array() )
{
if ( $options instanceof ezcMailImapTransportOptions )
{
$this->options = $options;
}
else if ( is_array( $options ) )
{
$this->options = new ezcMailImapTransportOptions( $options );
}
else
{
throw new ezcBaseValueException( "options", $options, "ezcMailImapTransportOptions|array" );
}
if ( $port === null )
{
$port = ( $this->options->ssl === true ) ? 993 : 143;
}
$this->connection = new ezcMailTransportConnection( $server, $port, $this->options );
// get the server greeting
$response = $this->connection->getLine();
if ( strpos( $response, "* OK" ) === false )
{
throw new ezcMailTransportException( "The connection to the IMAP server is ok, but a negative response from server was received. Try again later." );
}
if ( strpos( $response, self::SERVER_GIMAP ) !== false )
{
$this->serverType = self::SERVER_GIMAP; // otherwise it is null
}
$this->state = self::STATE_NOT_AUTHENTICATED;
}
/**
* Destructs the IMAP transport.
*
* If there is an open connection to the IMAP server it is closed.
*/
public function __destruct()
{
try
{
$this->disconnect();
}
catch ( ezcMailTransportException $e )
{
// Ignore occuring transport exceptions.
}
}
/**
* Sets the value of the property $name to $value.
*
* @throws ezcBasePropertyNotFoundException
* if the property $name does not exist
* @throws ezcBaseValueException
* if $value is not accepted for the property $name
* @param string $name
* @param mixed $value
* @ignore
*/
public function __set( $name, $value )
{
switch ( $name )
{
case 'options':
if ( !( $value instanceof ezcMailImapTransportOptions ) )
{
throw new ezcBaseValueException( 'options', $value, 'instanceof ezcMailImapTransportOptions' );
}
$this->options = $value;
break;
default:
throw new ezcBasePropertyNotFoundException( $name );
}
}
/**
* Returns the value of the property $name.
*
* @throws ezcBasePropertyNotFoundException
* if the property $name does not exist
* @param string $name
* @ignore
*/
public function __get( $name )
{
switch ( $name )
{
case 'options':
return $this->options;
default:
throw new ezcBasePropertyNotFoundException( $name );
}
}
/**
* Returns true if the property $name is set, otherwise false.
*
* @param string $name
* @return bool
* @ignore
*/
public function __isset( $name )
{
switch ( $name )
{
case 'options':
return true;
default:
return false;
}
}
/**
* Disconnects the transport from the IMAP server.
*/
public function disconnect()
{
if ( $this->state !== self::STATE_NOT_CONNECTED
&& $this->connection->isConnected() === true )
{
$tag = $this->getNextTag();
$this->connection->sendData( "{$tag} LOGOUT" );
// discard the "bye bye" message ("{$tag} OK Logout completed.")
$this->getResponse( $tag );
$this->state = self::STATE_LOGOUT;
$this->selectedMailbox = null;
$this->connection->close();
$this->connection = null;
$this->state = self::STATE_NOT_CONNECTED;
}
}
/**
* Authenticates the user to the IMAP server with $user and $password.
*
* This method should be called directly after the construction of this
* object.
*
* If the server is waiting for the authentication process to respond, the
* connection with the IMAP server will be closed, and false is returned,
* and it is the application's task to reconnect and reauthenticate.
*
* Example of creating an IMAP transport and authenticating:
* <code>
* // replace with your IMAP server address
* $imap = new ezcMailImapTransport( 'imap.example.com' );
*
* // replace the values with your username and password for the IMAP server
* $imap->authenticate( 'username', 'password' );
* </code>
*
* @throws ezcMailTransportException
* if already authenticated
* or if the provided username/password combination did not work
* @param string $user
* @param string $password
* @return bool
*/
public function authenticate( $user, $password )
{
if ( $this->state != self::STATE_NOT_AUTHENTICATED )
{
throw new ezcMailTransportException( "Tried to authenticate when there was no connection or when already authenticated." );
}
$tag = $this->getNextTag();
$user = addcslashes($user, '\"');
$password = addcslashes($password, '\"');
$this->connection->sendData( "{$tag} LOGIN \"{$user}\" \"{$password}\"" );
$response = trim( $this->connection->getLine() );
// hack for gmail, to fix issue #15837: imap.google.com (google gmail) changed IMAP response
if ( $this->serverType === self::SERVER_GIMAP && strpos( $response, "* CAPABILITY" ) === 0 )
{
$response = trim( $this->connection->getLine() );
}
if ( strpos( $response, '* OK' ) !== false )
{
// the server is busy waiting for authentication process to
// respond, so it is a good idea to just close the connection,
// otherwise the application will be halted until the server
// recovers
$this->connection->close();
$this->connection = null;
$this->state = self::STATE_NOT_CONNECTED;
return false;
}
if ( $this->responseType( $response ) != self::RESPONSE_OK )
{
throw new ezcMailTransportException( "The IMAP server did not accept the username and/or password: {$response}." );
}
else
{
$this->state = self::STATE_AUTHENTICATED;
$this->selectedMailbox = null;
}
return true;
}
/**
* Returns an array with the names of the available mailboxes for the user
* currently authenticated on the IMAP server.
*
* Before calling this method, a connection to the IMAP server must be
* established and a user must be authenticated successfully.
*
* For more information about $reference and $mailbox, consult
* the IMAP RFCs documents ({@link http://www.faqs.org/rfcs/rfc1730.html}
* or {@link http://www.faqs.org/rfcs/rfc2060.html}, section 7.2.2.).
*
* By default, $reference is "" and $mailbox is "*".
*
* The array returned contains the mailboxes available for the connected
* user on this IMAP server. Inbox is a special mailbox, and it can be
* specified upper-case or lower-case or mixed-case. The other mailboxes
* should be specified as they are (to the {@link selectMailbox()} method).
*
* Example of listing mailboxes:
* <code>
* $imap = new ezcMailImapTransport( 'imap.example.com' );
* $imap->authenticate( 'username', 'password' );
*
* $mailboxes = $imap->listMailboxes();
* </code>
*
* @throws ezcMailMailTransportException
* if the current server state is not accepted
* or if the server sent a negative response
* @param string $reference
* @param string $mailbox
* @return array(string)
*/
public function listMailboxes( $reference = '', $mailbox = '*' )
{
if ( $this->state != self::STATE_AUTHENTICATED &&
$this->state != self::STATE_SELECTED &&
$this->state != self::STATE_SELECTED_READONLY )
{
throw new ezcMailTransportException( "Can't call listMailboxes() when not successfully logged in." );
}
$result = array();
$tag = $this->getNextTag();
$this->connection->sendData( "{$tag} LIST \"{$reference}\" \"{$mailbox}\"" );
$response = trim( $this->connection->getLine() );
while ( strpos( $response, '* LIST (' ) !== false )
{
// only consider the selectable mailboxes
if ( strpos( $response, "\\Noselect" ) === false )
{
$response = substr( $response, strpos( $response, "\" " ) + 2 );
$response = trim( $response );
$response = trim( $response, "\"" );
$result[] = $response;
}
$response = $this->connection->getLine();
}
$response = $this->getResponse( $tag, $response );
if ( $this->responseType( $response ) != self::RESPONSE_OK )
{
throw new ezcMailTransportException( "Could not list mailboxes with the parameters '\"{$reference}\"' and '\"{$mailbox}\"': {$response}." );
}
return $result;
}
/**
* Returns the hierarchy delimiter of the IMAP server, useful for handling
* nested IMAP folders.
*
* For more information about the hierarchy delimiter, consult the IMAP RFCs
* {@link http://www.faqs.org/rfcs/rfc1730.html} or
* {@link http://www.faqs.org/rfcs/rfc2060.html}, section 6.3.8.
*
* Before calling this method, a connection to the IMAP server must be
* established and a user must be authenticated successfully.
*
* Example of returning the hierarchy delimiter:
* <code>
* $imap = new ezcMailImapTransport( 'imap.example.com' );
* $imap->authenticate( 'username', 'password' );
*
* $delimiter = $imap->getDelimiter();
* </code>
*
* After running the above code, $delimiter should be something like "/".
*
* @throws ezcMailMailTransportException
* if the current server state is not accepted
* or if the server sent a negative response
* @return string
*/
public function getHierarchyDelimiter()
{
if ( $this->state != self::STATE_AUTHENTICATED &&
$this->state != self::STATE_SELECTED &&
$this->state != self::STATE_SELECTED_READONLY )
{
throw new ezcMailTransportException( "Can't call getDelimiter() when not successfully logged in." );
}
$tag = $this->getNextTag();
$this->connection->sendData( "{$tag} LIST \"\" \"\"" );
// there should be only one * LIST response line from IMAP
$response = trim( $this->getResponse( '* LIST' ) );
$parts = explode( '"', $response );
if ( count( $parts ) >= 2 )
{
$result = $parts[1];
}
else
{
throw new ezcMailTransportException( "Could not retrieve the hierarchy delimiter: {$response}." );
}
$response = $this->getResponse( $tag, $response );
if ( $this->responseType( $response ) != self::RESPONSE_OK )
{
throw new ezcMailTransportException( "Could not retrieve the hierarchy delimiter: {$response}." );
}
return $result;
}
/**
* Selects the mailbox $mailbox, which will be the active mailbox for the
* subsequent commands until it is changed.
*
* Before calling this method, a connection to the IMAP server must be
* established and a user must be authenticated successfully.
*
* Inbox is a special mailbox and can be specified with any case.
*
* This method should be called after authentication, and before fetching
* any messages.
*
* Example of selecting a mailbox:
* <code>
* $imap = new ezcMailImapTransport( 'imap.example.com' );
* $imap->authenticate( 'username', 'password' );
*
* $imap->selectMailbox( 'Reports 2006' );
* </code>
*
* @throws ezcMailMailTransportException
* if the current server state is not accepted
* or if the server sent a negative response
* @param string $mailbox
* @param bool $readOnly
*/
public function selectMailbox( $mailbox, $readOnly = false )
{
if ( $this->state != self::STATE_AUTHENTICATED &&
$this->state != self::STATE_SELECTED &&
$this->state != self::STATE_SELECTED_READONLY )
{
throw new ezcMailTransportException( "Can't call selectMailbox() when not successfully logged in." );
}
$tag = $this->getNextTag();
// if the mailbox selection will be successful, $state will be STATE_SELECTED
// or STATE_SELECTED_READONLY, depending on the $readOnly parameter
if ( $readOnly !== true )
{
$this->connection->sendData( "{$tag} SELECT \"{$mailbox}\"" );
$state = self::STATE_SELECTED;
}
else
{
$this->connection->sendData( "{$tag} EXAMINE \"{$mailbox}\"" );
$state = self::STATE_SELECTED_READONLY;
}
// if the selecting of the mailbox fails (with "NO" or "BAD" response
// from the server), $state reverts to STATE_AUTHENTICATED
$response = trim( $this->getResponse( $tag ) );
if ( $this->responseType( $response ) == self::RESPONSE_OK )
{
$this->state = $state;
$this->selectedMailbox = $mailbox;
}
else
{
$this->state = self::STATE_AUTHENTICATED;
$this->selectedMailbox = null;
throw new ezcMailTransportException( "Could not select mailbox '{$mailbox}': {$response}." );
}
}
/**
* Creates the mailbox $mailbox.
*
* Inbox cannot be created.
*
* Before calling this method, a connection to the IMAP server must be
* established and a user must be authenticated successfully.
*
* @throws ezcMailTransportException
* if the current server state is not accepted
* or if the server sent a negative response
* @param string $mailbox
* @return bool
*/
public function createMailbox( $mailbox )
{
if ( $this->state != self::STATE_AUTHENTICATED &&
$this->state != self::STATE_SELECTED &&
$this->state != self::STATE_SELECTED_READONLY )
{
throw new ezcMailTransportException( "Can't call createMailbox() when not successfully logged in." );
}
$tag = $this->getNextTag();
$this->connection->sendData( "{$tag} CREATE \"{$mailbox}\"" );
$response = trim( $this->getResponse( $tag ) );
if ( $this->responseType( $response ) != self::RESPONSE_OK )
{
throw new ezcMailTransportException( "The IMAP server could not create mailbox '{$mailbox}': {$response}." );
}
return true;
}
/**
* Renames the mailbox $mailbox to $newName.
*
* Inbox cannot be renamed.
*
* Before calling this method, a connection to the IMAP server must be
* established and a user must be authenticated successfully.
*
* @throws ezcMailTransportException
* if the current server state is not accepted
* or if trying to rename the currently selected mailbox
* or if the server sent a negative response
* @param string $mailbox
* @param string $newName
* @return bool
*/
public function renameMailbox( $mailbox, $newName )
{
if ( $this->state != self::STATE_AUTHENTICATED &&
$this->state != self::STATE_SELECTED &&
$this->state != self::STATE_SELECTED_READONLY )
{
throw new ezcMailTransportException( "Can't call renameMailbox() when not successfully logged in." );
}
if ( strtolower( $this->selectedMailbox ) == strtolower( $mailbox ) )
{
throw new ezcMailTransportException( "Can't rename the currently selected mailbox." );
}
$tag = $this->getNextTag();
$this->connection->sendData( "{$tag} RENAME \"{$mailbox}\" \"{$newName}\"" );
$response = trim( $this->getResponse( $tag ) );
if ( $this->responseType( $response ) != self::RESPONSE_OK )
{
throw new ezcMailTransportException( "The IMAP server could not rename the mailbox '{$mailbox}' to '{$newName}': {$response}." );
}
return true;
}
/**
* Deletes the mailbox $mailbox.
*
* Inbox and the the currently selected mailbox cannot be deleted.
*
* Before calling this method, a connection to the IMAP server must be
* established and a user must be authenticated successfully.
*
* @throws ezcMailTransportException
* if the current server state is not accepted
* or if trying to delete the currently selected mailbox
* or if the server sent a negative response
* @param string $mailbox
* @return bool
*/
public function deleteMailbox( $mailbox )
{
if ( $this->state != self::STATE_AUTHENTICATED &&
$this->state != self::STATE_SELECTED &&
$this->state != self::STATE_SELECTED_READONLY )
{
throw new ezcMailTransportException( "Can't call deleteMailbox() when not successfully logged in." );
}
if ( strtolower( $this->selectedMailbox ) == strtolower( $mailbox ) )
{
throw new ezcMailTransportException( "Can't delete the currently selected mailbox." );
}
$tag = $this->getNextTag();
$this->connection->sendData( "{$tag} DELETE \"{$mailbox}\"" );
$response = trim( $this->getResponse( $tag ) );
if ( $this->responseType( $response ) != self::RESPONSE_OK )
{
throw new ezcMailTransportException( "The IMAP server could not delete the mailbox '{$mailbox}': {$response}." );
}
return true;
}
/**
* Copies message(s) from the currently selected mailbox to mailbox
* $destination.
*
* This method supports unique IDs instead of message numbers. See
* {@link ezcMailImapTransportOptions} for how to enable unique IDs
* referencing.
*
* Warning! When using unique IDs referencing and trying to copy a message
* with an ID that does not exist, this method will not throw an exception.
*
* @todo Find out if it is possible to catch this IMAP bug.
*
* $messages can be:
* - a single message number (eg: '1')
* - a message range (eg. '1:4')
* - a message list (eg. '1,2,4')
*
* Before calling this method, a connection to the IMAP server must be
* established and a user must be authenticated successfully, and a mailbox
* must be selected (the mailbox from which messages will be copied).
*
* Example of copying 3 messages to a mailbox:
* <code>
* $imap = new ezcMailImapTransport( 'imap.example.com' );
* $imap->authenticate( 'username', 'password' );
* $imap->selectMailbox( 'Inbox' );
*
* $imap->copyMessages( '1,2,4', 'Reports 2006' );
* </code>
*
* The above code will copy the messages with numbers 1, 2 and 4 from Inbox
* to Reports 2006.
*
* @throws ezcMailTransportException
* if the current server state is not accepted
* or if the server sent a negative response
* @param string $messages
* @param string $destination
* @return bool
*/
public function copyMessages( $messages, $destination )
{
$uid = ( $this->options->uidReferencing ) ? self::UID : self::NO_UID;
if ( $this->state != self::STATE_SELECTED &&
$this->state != self::STATE_SELECTED_READONLY )
{
throw new ezcMailTransportException( "Can't call copyMessages() on the IMAP transport when a mailbox is not selected." );
}
$tag = $this->getNextTag();
$this->connection->sendData( "{$tag} {$uid}COPY {$messages} \"{$destination}\"" );
$response = trim( $this->getResponse( $tag ) );
if ( $this->responseType( $response ) != self::RESPONSE_OK )
{
throw new ezcMailTransportException( "The IMAP server could not copy '{$messages}' to '{$destination}': {$response}." );
}
return true;
}
/**
* Returns a list of the not deleted messages in the current mailbox.
*
* It returns only the messages with the flag DELETED not set.
*
* Before calling this method, a connection to the IMAP server must be
* established and a user must be authenticated successfully, and a mailbox
* must be selected.
*
* The format of the returned array is
* <code>
* array( message_id => size );
* </code>
*
* Example:
* <code>
* array( 2 => 1700, 5 => 1450, 6 => 21043 );
* </code>
*
* If $contentType is set, it returns only the messages with
* $contentType in the Content-Type header.
*
* For example $contentType can be "multipart/mixed" to return only the
* messages with attachments.
*
* @throws ezcMailTransportException
* if a mailbox is not selected
* or if the server sent a negative response
* @param string $contentType
* @return array(int)
*/
public function listMessages( $contentType = null )
{
if ( $this->state != self::STATE_SELECTED &&
$this->state != self::STATE_SELECTED_READONLY )
{
throw new ezcMailTransportException( "Can't call listMessages() on the IMAP transport when a mailbox is not selected." );
}
$messageList = array();
$messages = array();
// get the numbers of the existing messages
$tag = $this->getNextTag();
$command = "{$tag} SEARCH UNDELETED";
if ( !is_null( $contentType ) )
{
$command .= " HEADER \"Content-Type\" \"{$contentType}\"";
}
$this->connection->sendData( $command );
$response = trim( $this->getResponse( '* SEARCH' ) );
if ( strpos( $response, '* SEARCH' ) !== false )
{
$ids = trim( substr( $response, 9 ) );
if ( $ids !== "" )
{