thomascube
2010-06-08 af3cf8a0a7de74ab169f44277eda73f5f9e18cd7
commit | author | age
59c216 1 <?php
A 2
3 /*
4  +-----------------------------------------------------------------------+
5  | program/include/rcube_imap_generic.php                                |
6  |                                                                       |
7  | This file is part of the RoundCube Webmail client                     |
8  | Copyright (C) 2005-2010, RoundCube Dev. - Switzerland                 |
9  | Licensed under the GNU GPL                                            |
10  |                                                                       |
11  | PURPOSE:                                                              |
12  |   Provide alternative IMAP library that doesn't rely on the standard  |
13  |   C-Client based version. This allows to function regardless          |
14  |   of whether or not the PHP build it's running on has IMAP            |
15  |   functionality built-in.                                             |
16  |                                                                       |
17  |   Based on Iloha IMAP Library. See http://ilohamail.org/ for details  |
18  |                                                                       |
19  +-----------------------------------------------------------------------+
20  | Author: Aleksander Machniak <alec@alec.pl>                            |
21  | Author: Ryo Chijiiwa <Ryo@IlohaMail.org>                              |
22  +-----------------------------------------------------------------------+
23
24  $Id$
25
26 */
27
28
d062db 29 /**
T 30  * Struct representing an e-mail message header
31  *
32  * @package    Mail
1d5165 33  * @author     Aleksander Machniak <alec@alec.pl>
d062db 34  */
59c216 35 class rcube_mail_header
A 36 {
37     public $id;
38     public $uid;
39     public $subject;
40     public $from;
41     public $to;
42     public $cc;
43     public $replyto;
44     public $in_reply_to;
45     public $date;
46     public $messageID;
47     public $size;
48     public $encoding;
49     public $charset;
50     public $ctype;
51     public $flags;
52     public $timestamp;
53     public $f;
54     public $body_structure;
55     public $internaldate;
56     public $references;
57     public $priority;
58     public $mdn_to;
59     public $mdn_sent = false;
60     public $is_draft = false;
61     public $seen = false;
62     public $deleted = false;
63     public $recent = false;
64     public $answered = false;
65     public $forwarded = false;
66     public $junk = false;
67     public $flagged = false;
68     public $has_children = false;
69     public $depth = 0;
70     public $unread_children = 0;
71     public $others = array();
72 }
73
182093 74 // For backward compatibility with cached messages (#1486602)
A 75 class iilBasicHeader extends rcube_mail_header
76 {
77 }
59c216 78
d062db 79 /**
T 80  * PHP based wrapper class to connect to an IMAP server
81  *
82  * @package    Mail
1d5165 83  * @author     Aleksander Machniak <alec@alec.pl>
d062db 84  */
59c216 85 class rcube_imap_generic
A 86 {
87     public $error;
88     public $errornum;
89     public $message;
90     public $rootdir;
91     public $delimiter;
92     public $permanentflags = array();
93     public $flags = array(
94         'SEEN'     => '\\Seen',
95         'DELETED'  => '\\Deleted',
96         'RECENT'   => '\\Recent',
97         'ANSWERED' => '\\Answered',
98         'DRAFT'    => '\\Draft',
99         'FLAGGED'  => '\\Flagged',
100         'FORWARDED' => '$Forwarded',
101         'MDNSENT'  => '$MDNSent',
102         '*'        => '\\*',
103     );
104
105     private $exists;
106     private $recent;
107     private $selected;
108     private $fp;
109     private $host;
110     private $logged = false;
111     private $capability = array();
112     private $capability_readed = false;
113     private $prefs;
114
115     /**
116      * Object constructor
117      */
118     function __construct()
119     {
120     }
1d5165 121
59c216 122     private function putLine($string, $endln=true)
A 123     {
124         if (!$this->fp)
125             return false;
126
127         if (!empty($this->prefs['debug_mode'])) {
128             write_log('imap', 'C: '. rtrim($string));
129         }
1d5165 130
59c216 131         return fputs($this->fp, $string . ($endln ? "\r\n" : ''));
A 132     }
133
134     // $this->putLine replacement with Command Continuation Requests (RFC3501 7.5) support
135     private function putLineC($string, $endln=true)
136     {
137         if (!$this->fp)
138             return NULL;
139
140         if ($endln)
141             $string .= "\r\n";
142
143         $res = 0;
144         if ($parts = preg_split('/(\{[0-9]+\}\r\n)/m', $string, -1, PREG_SPLIT_DELIM_CAPTURE)) {
145             for ($i=0, $cnt=count($parts); $i<$cnt; $i++) {
146                 if (preg_match('/^\{[0-9]+\}\r\n$/', $parts[$i+1])) {
147                     $bytes = $this->putLine($parts[$i].$parts[$i+1], false);
148                     if ($bytes === false)
149                         return false;
150                     $res += $bytes;
151                     $line = $this->readLine(1000);
152                     // handle error in command
153                     if ($line[0] != '+')
154                         return false;
155                     $i++;
156                 }
157                 else {
158                     $bytes = $this->putLine($parts[$i], false);
159                     if ($bytes === false)
160                         return false;
161                     $res += $bytes;
162                 }
163             }
164         }
165
166         return $res;
167     }
168
169     private function readLine($size=1024)
170     {
171         $line = '';
172
173         if (!$this->fp) {
174             return NULL;
175         }
1d5165 176
59c216 177         if (!$size) {
A 178             $size = 1024;
179         }
1d5165 180
59c216 181         do {
A 182             if (feof($this->fp)) {
183                 return $line ? $line : NULL;
184             }
1d5165 185
59c216 186             $buffer = fgets($this->fp, $size);
A 187
188             if ($buffer === false) {
3978cb 189                 @fclose($this->fp);
A 190                 $this->fp = null;
59c216 191                 break;
A 192             }
193             if (!empty($this->prefs['debug_mode'])) {
194                 write_log('imap', 'S: '. chop($buffer));
195             }
196             $line .= $buffer;
197         } while ($buffer[strlen($buffer)-1] != "\n");
198
199         return $line;
200     }
201
202     private function multLine($line, $escape=false)
203     {
204         $line = chop($line);
205         if (preg_match('/\{[0-9]+\}$/', $line)) {
206             $out = '';
1d5165 207
59c216 208             preg_match_all('/(.*)\{([0-9]+)\}$/', $line, $a);
A 209             $bytes = $a[2][0];
210             while (strlen($out) < $bytes) {
1d5165 211                 $line = $this->readBytes($bytes);
59c216 212                 if ($line === NULL)
A 213                     break;
214                 $out .= $line;
215             }
216
217             $line = $a[1][0] . '"' . ($escape ? $this->Escape($out) : $out) . '"';
218         }
1d5165 219
59c216 220         return $line;
A 221     }
222
223     private function readBytes($bytes)
224     {
225         $data = '';
226         $len  = 0;
227         while ($len < $bytes && !feof($this->fp))
228         {
229             $d = fread($this->fp, $bytes-$len);
230             if (!empty($this->prefs['debug_mode'])) {
231                 write_log('imap', 'S: '. $d);
232             }
233             $data .= $d;
234             $data_len = strlen($data);
235             if ($len == $data_len) {
236                 break; // nothing was read -> exit to avoid apache lockups
237             }
238             $len = $data_len;
239         }
1d5165 240
59c216 241         return $data;
A 242     }
243
244     // don't use it in loops, until you exactly know what you're doing
6a86d2 245     private function readReply(&$untagged=null)
59c216 246     {
A 247         do {
248             $line = trim($this->readLine(1024));
1d5165 249             // store untagged response lines
A 250             if ($line[0] == '*')
251                 $untagged[] = $line;
59c216 252         } while ($line[0] == '*');
1d5165 253
A 254         if ($untagged)
255             $untagged = join("\n", $untagged);
59c216 256
A 257         return $line;
258     }
259
260     private function parseResult($string)
261     {
262         $a = explode(' ', trim($string));
263         if (count($a) >= 2) {
264             $res = strtoupper($a[1]);
265             if ($res == 'OK') {
266                 return 0;
267             } else if ($res == 'NO') {
268                 return -1;
269             } else if ($res == 'BAD') {
270                 return -2;
271             } else if ($res == 'BYE') {
3978cb 272                 @fclose($this->fp);
59c216 273                 $this->fp = null;
A 274                 return -3;
275             }
276         }
277         return -4;
278     }
279
280     // check if $string starts with $match (or * BYE/BAD)
281     private function startsWith($string, $match, $error=false, $nonempty=false)
282     {
283         $len = strlen($match);
284         if ($len == 0) {
285             return false;
286         }
287         if (!$this->fp) {
288             return true;
289         }
290         if (strncmp($string, $match, $len) == 0) {
291             return true;
292         }
293         if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
294             if (strtoupper($m[1]) == 'BYE') {
3978cb 295                 @fclose($this->fp);
59c216 296                 $this->fp = null;
A 297             }
298             return true;
299         }
300         if ($nonempty && !strlen($string)) {
301             return true;
302         }
303         return false;
304     }
305
306     private function startsWithI($string, $match, $error=false, $nonempty=false)
307     {
308         $len = strlen($match);
309         if ($len == 0) {
310             return false;
311         }
312         if (!$this->fp) {
313             return true;
314         }
315         if (strncasecmp($string, $match, $len) == 0) {
316             return true;
317         }
318         if ($error && preg_match('/^\* (BYE|BAD) /i', $string, $m)) {
319             if (strtoupper($m[1]) == 'BYE') {
3978cb 320                 @fclose($this->fp);
59c216 321                 $this->fp = null;
A 322             }
323             return true;
324         }
325         if ($nonempty && !strlen($string)) {
326             return true;
327         }
328         return false;
329     }
330
331     function getCapability($name)
332     {
333         if (in_array($name, $this->capability)) {
334             return true;
335         }
336         else if ($this->capability_readed) {
337             return false;
338         }
339
1d5165 340         // get capabilities (only once) because initial
59c216 341         // optional CAPABILITY response may differ
A 342         $this->capability = array();
343
344         if (!$this->putLine("cp01 CAPABILITY")) {
345             return false;
346         }
347         do {
348             $line = trim($this->readLine(1024));
349             $a = explode(' ', $line);
350             if ($line[0] == '*') {
351                 while (list($k, $w) = each($a)) {
352                     if ($w != '*' && $w != 'CAPABILITY')
353                         $this->capability[] = strtoupper($w);
354                 }
355             }
356         } while ($a[0] != 'cp01');
1d5165 357
59c216 358         $this->capability_readed = true;
A 359
360         if (in_array($name, $this->capability)) {
361             return true;
362         }
363
364         return false;
365     }
366
367     function clearCapability()
368     {
369         $this->capability = array();
370         $this->capability_readed = false;
371     }
372
373     function authenticate($user, $pass, $encChallenge)
374     {
375         $ipad = '';
376         $opad = '';
1d5165 377
59c216 378         // initialize ipad, opad
A 379         for ($i=0; $i<64; $i++) {
380             $ipad .= chr(0x36);
381             $opad .= chr(0x5C);
382         }
383
384         // pad $pass so it's 64 bytes
385         $padLen = 64 - strlen($pass);
386         for ($i=0; $i<$padLen; $i++) {
387             $pass .= chr(0);
388         }
1d5165 389
59c216 390         // generate hash
6f31b3 391         $hash  = md5($this->_xor($pass,$opad) . pack("H*", md5($this->_xor($pass, $ipad) . base64_decode($encChallenge))));
1d5165 392
59c216 393         // generate reply
A 394         $reply = base64_encode($user . ' ' . $hash);
1d5165 395
59c216 396         // send result, get reply
A 397         $this->putLine($reply);
398         $line = $this->readLine(1024);
1d5165 399
59c216 400         // process result
A 401         $result = $this->parseResult($line);
402         if ($result == 0) {
63bff1 403             $this->errornum = 0;
59c216 404             return $this->fp;
A 405         }
406
63bff1 407         $this->error    = "Authentication for $user failed (AUTH): $line";
A 408         $this->errornum = $result;
59c216 409
A 410         return $result;
411     }
412
413     function login($user, $password)
414     {
415         $this->putLine('a001 LOGIN "'.$this->escape($user).'" "'.$this->escape($password).'"');
416
1d5165 417         $line = $this->readReply($untagged);
A 418
419         // re-set capabilities list if untagged CAPABILITY response provided
420         if (preg_match('/\* CAPABILITY (.+)/i', $untagged, $matches)) {
421             $this->capability = explode(' ', strtoupper($matches[1]));
422         }
59c216 423
A 424         // process result
425         $result = $this->parseResult($line);
426
427         if ($result == 0) {
63bff1 428             $this->errornum = 0;
59c216 429             return $this->fp;
A 430         }
431
3978cb 432         @fclose($this->fp);
59c216 433         $this->fp = false;
1d5165 434
63bff1 435         $this->error    = "Authentication for $user failed (LOGIN): $line";
A 436         $this->errornum = $result;
59c216 437
A 438         return $result;
439     }
440
c85424 441     function getNamespace()
59c216 442     {
A 443         if (isset($this->prefs['rootdir']) && is_string($this->prefs['rootdir'])) {
444             $this->rootdir = $this->prefs['rootdir'];
445             return true;
446         }
1d5165 447
59c216 448         if (!$this->getCapability('NAMESPACE')) {
A 449             return false;
450         }
1d5165 451
59c216 452         if (!$this->putLine("ns1 NAMESPACE")) {
A 453             return false;
454         }
455         do {
456             $line = $this->readLine(1024);
457             if ($this->startsWith($line, '* NAMESPACE')) {
458                 $i    = 0;
459                 $line = $this->unEscape($line);
460                 $data = $this->parseNamespace(substr($line,11), $i, 0, 0);
461             }
462         } while (!$this->startsWith($line, 'ns1', true, true));
463
464         if (!is_array($data)) {
465             return false;
466         }
467
468         $user_space_data = $data[0];
469         if (!is_array($user_space_data)) {
470             return false;
471         }
472
473         $first_userspace = $user_space_data[0];
474         if (count($first_userspace)!=2) {
475             return false;
476         }
1d5165 477
59c216 478         $this->rootdir            = $first_userspace[0];
A 479         $this->delimiter          = $first_userspace[1];
480         $this->prefs['rootdir']   = substr($this->rootdir, 0, -1);
481         $this->prefs['delimiter'] = $this->delimiter;
1d5165 482
59c216 483         return true;
A 484     }
485
486
487     /**
488      * Gets the delimiter, for example:
489      * INBOX.foo -> .
490      * INBOX/foo -> /
491      * INBOX\foo -> \
1d5165 492      *
A 493      * @return mixed A delimiter (string), or false.
59c216 494      * @see connect()
A 495      */
496     function getHierarchyDelimiter()
497     {
498         if ($this->delimiter) {
499             return $this->delimiter;
500         }
501         if (!empty($this->prefs['delimiter'])) {
502             return ($this->delimiter = $this->prefs['delimiter']);
503         }
504
505         $delimiter = false;
506
507         // try (LIST "" ""), should return delimiter (RFC2060 Sec 6.3.8)
508         if (!$this->putLine('ghd LIST "" ""')) {
509             return false;
510         }
1d5165 511
59c216 512         do {
A 513             $line = $this->readLine(500);
514             if ($line[0] == '*') {
515                 $line = rtrim($line);
516                 $a = rcube_explode_quoted_string(' ', $this->unEscape($line));
517                 if ($a[0] == '*') {
518                     $delimiter = str_replace('"', '', $a[count($a)-2]);
519                 }
520             }
521         } while (!$this->startsWith($line, 'ghd', true, true));
522
523         if (strlen($delimiter)>0) {
524             return $delimiter;
525         }
526
527         // if that fails, try namespace extension
528         // try to fetch namespace data
529         if (!$this->putLine("ns1 NAMESPACE")) {
530             return false;
531         }
532
533         do {
534             $line = $this->readLine(1024);
535             if ($this->startsWith($line, '* NAMESPACE')) {
536                 $i = 0;
537                 $line = $this->unEscape($line);
538                 $data = $this->parseNamespace(substr($line,11), $i, 0, 0);
539             }
540         } while (!$this->startsWith($line, 'ns1', true, true));
541
542         if (!is_array($data)) {
543             return false;
544         }
1d5165 545
59c216 546         // extract user space data (opposed to global/shared space)
A 547         $user_space_data = $data[0];
548         if (!is_array($user_space_data)) {
549             return false;
550         }
551
552         // get first element
553         $first_userspace = $user_space_data[0];
554         if (!is_array($first_userspace)) {
555             return false;
556         }
557
558         // extract delimiter
1d5165 559         $delimiter = $first_userspace[1];
59c216 560
A 561         return $delimiter;
562     }
563
564     function connect($host, $user, $password, $options=null)
565     {
566         // set options
567         if (is_array($options)) {
568             $this->prefs = $options;
569         }
570         // set auth method
571         if (!empty($this->prefs['auth_method'])) {
572             $auth_method = strtoupper($this->prefs['auth_method']);
573         } else {
574             $auth_method = 'CHECK';
575         }
576
577         $message = "INITIAL: $auth_method\n";
578
579         $result = false;
1d5165 580
59c216 581         // initialize connection
A 582         $this->error    = '';
583         $this->errornum = 0;
584         $this->selected = '';
585         $this->user     = $user;
586         $this->host     = $host;
587         $this->logged   = false;
588
589         // check input
590         if (empty($host)) {
591             $this->error    = "Empty host";
94a6c6 592             $this->errornum = -2;
59c216 593             return false;
A 594         }
595         if (empty($user)) {
596             $this->error    = "Empty user";
597             $this->errornum = -1;
598             return false;
599         }
600         if (empty($password)) {
601             $this->error    = "Empty password";
602             $this->errornum = -1;
603             return false;
604         }
605
606         if (!$this->prefs['port']) {
607             $this->prefs['port'] = 143;
608         }
609         // check for SSL
610         if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
611             $host = $this->prefs['ssl_mode'] . '://' . $host;
612         }
613
f07d23 614         // Connect
A 615         if ($this->prefs['timeout'] > 0)
616             $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
617         else
618             $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr);
619
59c216 620         if (!$this->fp) {
A 621             $this->error    = sprintf("Could not connect to %s:%d: %s", $host, $this->prefs['port'], $errstr);
622             $this->errornum = -2;
623             return false;
624         }
625
f07d23 626         if ($this->prefs['timeout'] > 0)
A 627             stream_set_timeout($this->fp, $this->prefs['timeout']);
628
59c216 629         $line = trim(fgets($this->fp, 8192));
A 630
631         if ($this->prefs['debug_mode'] && $line) {
632             write_log('imap', 'S: '. $line);
633         }
634
635         // Connected to wrong port or connection error?
636         if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
637             if ($line)
638                 $this->error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
639             else
640                 $this->error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);
641             $this->errornum = -2;
642             return false;
643         }
644
645         // RFC3501 [7.1] optional CAPABILITY response
646         if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
647             $this->capability = explode(' ', strtoupper($matches[1]));
b93d00 648             $this->capability_readed = true;
59c216 649         }
A 650
651         $this->message .= $line;
652
653         // TLS connection
654         if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
655             if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
656                    $this->putLine("tls0 STARTTLS");
657
658                 $line = $this->readLine(4096);
659                 if (!$this->startsWith($line, "tls0 OK")) {
660                     $this->error    = "Server responded to STARTTLS with: $line";
661                     $this->errornum = -2;
662                     return false;
663                 }
664
665                 if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
666                     $this->error    = "Unable to negotiate TLS";
667                     $this->errornum = -2;
668                     return false;
669                 }
1d5165 670
59c216 671                 // Now we're authenticated, capabilities need to be reread
A 672                 $this->clearCapability();
673             }
674         }
675
676         $orig_method = $auth_method;
677
678         if ($auth_method == 'CHECK') {
679             // check for supported auth methods
680             if ($this->getCapability('AUTH=CRAM-MD5') || $this->getCapability('AUTH=CRAM_MD5')) {
681                 $auth_method = 'AUTH';
682             }
683             else {
684                 // default to plain text auth
685                 $auth_method = 'PLAIN';
686             }
687         }
688
689         if ($auth_method == 'AUTH') {
690             // do CRAM-MD5 authentication
691             $this->putLine("a000 AUTHENTICATE CRAM-MD5");
692             $line = trim($this->readLine(1024));
693
694             if ($line[0] == '+') {
695                 // got a challenge string, try CRAM-MD5
696                 $result = $this->authenticate($user, $password, substr($line,2));
1d5165 697
59c216 698                 // stop if server sent BYE response
A 699                 if ($result == -3) {
700                     return false;
701                 }
702             }
1d5165 703
59c216 704             if (!is_resource($result) && $orig_method == 'CHECK') {
A 705                 $auth_method = 'PLAIN';
706             }
707         }
1d5165 708
59c216 709         if ($auth_method == 'PLAIN') {
A 710             // do plain text auth
711             $result = $this->login($user, $password);
712         }
713
714         if (is_resource($result)) {
715             if ($this->prefs['force_caps']) {
716                 $this->clearCapability();
717             }
c85424 718             $this->getNamespace();
59c216 719             $this->logged = true;
b93d00 720
59c216 721             return true;
A 722         } else {
723             return false;
724         }
725     }
726
727     function connected()
728     {
729         return ($this->fp && $this->logged) ? true : false;
730     }
731
732     function close()
733     {
734         if ($this->putLine("I LOGOUT")) {
735             if (!feof($this->fp))
736                 fgets($this->fp, 1024);
737         }
738         @fclose($this->fp);
739         $this->fp = false;
740     }
741
742     function select($mailbox)
743     {
744         if (empty($mailbox)) {
745             return false;
746         }
747         if ($this->selected == $mailbox) {
748             return true;
749         }
1d5165 750
59c216 751         if ($this->putLine("sel1 SELECT \"".$this->escape($mailbox).'"')) {
A 752             do {
753                 $line = chop($this->readLine(300));
754                 $a = explode(' ', $line);
755                 if (count($a) == 3) {
756                     $token = strtoupper($a[2]);
757                     if ($token == 'EXISTS') {
758                         $this->exists = (int) $a[1];
759                     }
760                     else if ($token == 'RECENT') {
761                         $this->recent = (int) $a[1];
762                     }
763                 }
764                 else if (preg_match('/\[?PERMANENTFLAGS\s+\(([^\)]+)\)\]/U', $line, $match)) {
765                     $this->permanentflags = explode(' ', $match[1]);
766                 }
767             } while (!$this->startsWith($line, 'sel1', true, true));
768
769             if (strcasecmp($a[1], 'OK') == 0) {
770                 $this->selected = $mailbox;
771                 return true;
772             }
773             else {
774                 $this->error = "Couldn't select $mailbox";
775             }
776         }
777
778         return false;
779     }
780
781     function checkForRecent($mailbox)
782     {
783         if (empty($mailbox)) {
784             $mailbox = 'INBOX';
785         }
1d5165 786
59c216 787         $this->select($mailbox);
A 788         if ($this->selected == $mailbox) {
789             return $this->recent;
790         }
791
792         return false;
793     }
794
795     function countMessages($mailbox, $refresh = false)
796     {
797         if ($refresh) {
798             $this->selected = '';
799         }
1d5165 800
59c216 801         $this->select($mailbox);
A 802         if ($this->selected == $mailbox) {
803             return $this->exists;
804         }
805
806         return false;
807     }
808
809     function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
810     {
811         $field = strtoupper($field);
812         if ($field == 'INTERNALDATE') {
813             $field = 'ARRIVAL';
814         }
1d5165 815
59c216 816         $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
A 817             'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
818
819         if (!$fields[$field]) {
820             return false;
821         }
822
823         /*  Do "SELECT" command */
824         if (!$this->select($mailbox)) {
825             return false;
826         }
1d5165 827
59c216 828         $is_uid = $is_uid ? 'UID ' : '';
1d5165 829
59c216 830         // message IDs
A 831         if (is_array($add))
832             $add = $this->compressMessageSet(join(',', $add));
833
834         $command  = "s ".$is_uid."SORT ($field) $encoding ALL";
835         $line     = $data = '';
836
837         if (!empty($add))
838             $command .= ' '.$add;
839
840         if (!$this->putLineC($command)) {
841             return false;
842         }
843         do {
844             $line = chop($this->readLine());
845             if ($this->startsWith($line, '* SORT')) {
846                 $data .= substr($line, 7);
847             } else if (preg_match('/^[0-9 ]+$/', $line)) {
848                 $data .= $line;
849             }
850         } while (!$this->startsWith($line, 's ', true, true));
1d5165 851
59c216 852         $result_code = $this->parseResult($line);
A 853         if ($result_code != 0) {
854             $this->error = "Sort: $line";
855             return false;
856         }
1d5165 857
59c216 858         return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
A 859     }
860
861     function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
862     {
863         if (is_array($message_set)) {
864             if (!($message_set = $this->compressMessageSet(join(',', $message_set))))
865                 return false;
866         } else {
867             list($from_idx, $to_idx) = explode(':', $message_set);
868             if (empty($message_set) ||
869                 (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
870                 return false;
871             }
872         }
1d5165 873
59c216 874         $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
1d5165 875
59c216 876         $fields_a['DATE']         = 1;
A 877         $fields_a['INTERNALDATE'] = 4;
878         $fields_a['ARRIVAL']       = 4;
879         $fields_a['FROM']         = 1;
880         $fields_a['REPLY-TO']     = 1;
881         $fields_a['SENDER']       = 1;
882         $fields_a['TO']           = 1;
883         $fields_a['CC']           = 1;
884         $fields_a['SUBJECT']      = 1;
885         $fields_a['UID']          = 2;
886         $fields_a['SIZE']         = 2;
887         $fields_a['SEEN']         = 3;
888         $fields_a['RECENT']       = 3;
889         $fields_a['DELETED']      = 3;
890
891         if (!($mode = $fields_a[$index_field])) {
892             return false;
893         }
894
895         /*  Do "SELECT" command */
896         if (!$this->select($mailbox)) {
897             return false;
898         }
1d5165 899
59c216 900         // build FETCH command string
A 901         $key     = 'fhi0';
902         $cmd     = $uidfetch ? 'UID FETCH' : 'FETCH';
903         $deleted = $skip_deleted ? ' FLAGS' : '';
904
905         if ($mode == 1 && $index_field == 'DATE')
906             $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
907         else if ($mode == 1)
908             $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
909         else if ($mode == 2) {
910             if ($index_field == 'SIZE')
911                 $request = " $cmd $message_set (RFC822.SIZE$deleted)";
912             else
913                 $request = " $cmd $message_set ($index_field$deleted)";
914         } else if ($mode == 3)
915             $request = " $cmd $message_set (FLAGS)";
916         else // 4
917             $request = " $cmd $message_set (INTERNALDATE$deleted)";
918
919         $request = $key . $request;
920
921         if (!$this->putLine($request)) {
922             return false;
923         }
924
925         $result = array();
926
927         do {
928             $line = chop($this->readLine(200));
929             $line = $this->multLine($line);
930
931             if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
932                 $id     = $m[1];
933                 $flags  = NULL;
1d5165 934
59c216 935                 if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
A 936                     $flags = explode(' ', strtoupper($matches[1]));
937                     if (in_array('\\DELETED', $flags)) {
938                         $deleted[$id] = $id;
939                         continue;
940                     }
941                 }
942
943                 if ($mode == 1 && $index_field == 'DATE') {
944                     if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
945                         $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
946                         $value = trim($value);
947                         $result[$id] = $this->strToTime($value);
948                     }
949                     // non-existent/empty Date: header, use INTERNALDATE
950                     if (empty($result[$id])) {
951                         if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
952                             $result[$id] = $this->strToTime($matches[1]);
953                         else
954                             $result[$id] = 0;
955                     }
956                 } else if ($mode == 1) {
957                     if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
958                         $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
959                         $result[$id] = trim($value);
960                     } else {
961                         $result[$id] = '';
962                     }
963                 } else if ($mode == 2) {
964                     if (preg_match('/\((UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
965                         $result[$id] = trim($matches[2]);
966                     } else {
967                         $result[$id] = 0;
968                     }
969                 } else if ($mode == 3) {
970                     if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
971                         $flags = explode(' ', $matches[1]);
972                     }
973                     $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
974                 } else if ($mode == 4) {
975                     if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
976                         $result[$id] = $this->strToTime($matches[1]);
977                     } else {
978                         $result[$id] = 0;
979                     }
980                 }
981             }
982         } while (!$this->startsWith($line, $key, true, true));
983
1d5165 984         return $result;
59c216 985     }
A 986
987     private function compressMessageSet($message_set)
988     {
1d5165 989         // given a comma delimited list of independent mid's,
59c216 990         // compresses by grouping sequences together
1d5165 991
59c216 992         // if less than 255 bytes long, let's not bother
A 993         if (strlen($message_set)<255) {
994             return $message_set;
995         }
1d5165 996
59c216 997         // see if it's already been compress
A 998         if (strpos($message_set, ':') !== false) {
999             return $message_set;
1000         }
1d5165 1001
59c216 1002         // separate, then sort
A 1003         $ids = explode(',', $message_set);
1004         sort($ids);
1d5165 1005
59c216 1006         $result = array();
A 1007         $start  = $prev = $ids[0];
1008
1009         foreach ($ids as $id) {
1010             $incr = $id - $prev;
1011             if ($incr > 1) {            //found a gap
1012                 if ($start == $prev) {
1013                     $result[] = $prev;    //push single id
1014                 } else {
1015                     $result[] = $start . ':' . $prev;   //push sequence as start_id:end_id
1016                 }
1017                 $start = $id;            //start of new sequence
1018             }
1019             $prev = $id;
1020         }
1021
1022         // handle the last sequence/id
1023         if ($start==$prev) {
1024             $result[] = $prev;
1025         } else {
1026             $result[] = $start.':'.$prev;
1027         }
1d5165 1028
59c216 1029         // return as comma separated string
A 1030         return implode(',', $result);
1031     }
1032
1033     function UID2ID($folder, $uid)
1034     {
1035         if ($uid > 0) {
1036             $id_a = $this->search($folder, "UID $uid");
1037             if (is_array($id_a) && count($id_a) == 1) {
1038                 return $id_a[0];
1039             }
1040         }
1041         return false;
1042     }
1043
1044     function ID2UID($folder, $id)
1045     {
1046         if (empty($id)) {
1047             return     -1;
1048         }
1049
1050         if (!$this->select($folder)) {
1051             return -1;
1052         }
1053
1054         $result = -1;
1055         if ($this->putLine("fuid FETCH $id (UID)")) {
1056             do {
1057                 $line = chop($this->readLine(1024));
1058                 if (preg_match("/^\* $id FETCH \(UID (.*)\)/i", $line, $r)) {
1059                     $result = $r[1];
1060                 }
1061             } while (!$this->startsWith($line, 'fuid', true, true));
1062         }
1063
1064         return $result;
1065     }
1066
1067     function fetchUIDs($mailbox, $message_set=null)
1068     {
1069         if (is_array($message_set))
1070             $message_set = join(',', $message_set);
1071         else if (empty($message_set))
1072             $message_set = '1:*';
1d5165 1073
59c216 1074         return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
A 1075     }
1076
1077     function fetchHeaders($mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1078     {
1079         $result = array();
1d5165 1080
59c216 1081         if (!$this->select($mailbox)) {
A 1082             return false;
1083         }
1084
1085         if (is_array($message_set))
1086             $message_set = join(',', $message_set);
1087
1088         $message_set = $this->compressMessageSet($message_set);
1089
1090         if ($add)
1091             $add = ' '.strtoupper(trim($add));
1092
1093         /* FETCH uid, size, flags and headers */
1094         $key        = 'FH12';
1095         $request  = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1096         $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1097         if ($bodystr)
1098             $request .= "BODYSTRUCTURE ";
1099         $request .= "BODY.PEEK[HEADER.FIELDS ";
1100         $request .= "(DATE FROM TO SUBJECT REPLY-TO IN-REPLY-TO CC BCC ";
1101         $request .= "CONTENT-TRANSFER-ENCODING CONTENT-TYPE MESSAGE-ID ";
1102         $request .= "REFERENCES DISPOSITION-NOTIFICATION-TO X-PRIORITY ";
1103         $request .= "X-DRAFT-INFO".$add.")])";
1104
1105         if (!$this->putLine($request)) {
1106             return false;
1107         }
1108         do {
1109             $line = $this->readLine(1024);
1110             $line = $this->multLine($line);
1d5165 1111
59c216 1112             if (!$line)
A 1113                 break;
1d5165 1114
59c216 1115             $a    = explode(' ', $line);
A 1116
1117             if (($line[0] == '*') && ($a[2] == 'FETCH')) {
1118                 $id = $a[1];
1d5165 1119
59c216 1120                 $result[$id]            = new rcube_mail_header;
A 1121                 $result[$id]->id        = $id;
1122                 $result[$id]->subject   = '';
1123                 $result[$id]->messageID = 'mid:' . $id;
1124
1125                 $lines = array();
1126                 $ln = 0;
1127
1128                 // Sample reply line:
1129                 // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1130                 // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1131                 // BODY[HEADER.FIELDS ...
1132
1133                 if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/s', $line, $matches)) {
1134                     $str = $matches[1];
1135
1136                     // swap parents with quotes, then explode
1137                     $str = preg_replace('/[()]/', '"', $str);
1138                     $a = rcube_explode_quoted_string(' ', $str);
1139
1140                     // did we get the right number of replies?
1141                     $parts_count = count($a);
1142                     if ($parts_count>=6) {
1143                         for ($i=0; $i<$parts_count; $i=$i+2) {
1144                             if ($a[$i] == 'UID')
1145                                 $result[$id]->uid = $a[$i+1];
1146                             else if ($a[$i] == 'RFC822.SIZE')
1147                                 $result[$id]->size = $a[$i+1];
1148                             else if ($a[$i] == 'INTERNALDATE')
1149                                 $time_str = $a[$i+1];
1150                             else if ($a[$i] == 'FLAGS')
1151                                 $flags_str = $a[$i+1];
1152                         }
1153
1154                         $time_str = str_replace('"', '', $time_str);
1d5165 1155
59c216 1156                         // if time is gmt...
A 1157                         $time_str = str_replace('GMT','+0000',$time_str);
1d5165 1158
59c216 1159                         $result[$id]->internaldate = $time_str;
A 1160                         $result[$id]->timestamp = $this->StrToTime($time_str);
1161                         $result[$id]->date = $time_str;
1162                     }
1163
1d5165 1164                     // BODYSTRUCTURE
59c216 1165                     if($bodystr) {
A 1166                         while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/s', $line, $m)) {
1167                             $line2 = $this->readLine(1024);
1168                             $line .= $this->multLine($line2, true);
1169                         }
1170                         $result[$id]->body_structure = $m[1];
1171                     }
1172
1173                     // the rest of the result
1174                     preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m);
1175                     $reslines = explode("\n", trim($m[1], '"'));
1176                     // re-parse (see below)
1177                     foreach ($reslines as $resln) {
1178                         if (ord($resln[0])<=32) {
1179                             $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($resln);
1180                         } else {
1181                             $lines[++$ln] = trim($resln);
1182                         }
1183                     }
1184                 }
1185
1186                 // Start parsing headers.  The problem is, some header "lines" take up multiple lines.
1187                 // So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1188                 // process the previous line.  Otherwise, we'll keep adding the strings until we come
1189                 // to the next valid header line.
1d5165 1190
59c216 1191                 do {
A 1192                     $line = chop($this->readLine(300), "\r\n");
1193
1194                     // The preg_match below works around communigate imap, which outputs " UID <number>)".
1195                     // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1d5165 1196                     // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
59c216 1197                     // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
A 1198                     // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1199                     // An alternative might be:
1200                     // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1201                     // however, unsure how well this would work with all imap clients.
1202                     if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1203                         break;
1204                     }
1205
1206                     // handle FLAGS reply after headers (AOL, Zimbra?)
1207                     if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1208                         $flags_str = $matches[1];
1209                         break;
1210                     }
1211
1212                     if (ord($line[0])<=32) {
1213                         $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1214                     } else {
1215                         $lines[++$ln] = trim($line);
1216                     }
1217                 // patch from "Maksim Rubis" <siburny@hotmail.com>
1218                 } while ($line[0] != ')' && !$this->startsWith($line, $key, true));
1219
1d5165 1220                 if (strncmp($line, $key, strlen($key))) {
59c216 1221                     // process header, fill rcube_mail_header obj.
A 1222                     // initialize
1223                     if (is_array($headers)) {
1224                         reset($headers);
1225                         while (list($k, $bar) = each($headers)) {
1226                             $headers[$k] = '';
1227                         }
1228                     }
1229
1230                     // create array with header field:data
1231                     while ( list($lines_key, $str) = each($lines) ) {
1232                         list($field, $string) = $this->splitHeaderLine($str);
1d5165 1233
59c216 1234                         $field  = strtolower($field);
A 1235                         $string = preg_replace('/\n\s*/', ' ', $string);
1d5165 1236
59c216 1237                         switch ($field) {
A 1238                         case 'date';
1239                             $result[$id]->date = $string;
1240                             $result[$id]->timestamp = $this->strToTime($string);
1241                             break;
1242                         case 'from':
1243                             $result[$id]->from = $string;
1244                             break;
1245                         case 'to':
1246                             $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1247                             break;
1248                         case 'subject':
1249                             $result[$id]->subject = $string;
1250                             break;
1251                         case 'reply-to':
1252                             $result[$id]->replyto = $string;
1253                             break;
1254                         case 'cc':
1255                             $result[$id]->cc = $string;
1256                             break;
1257                         case 'bcc':
1258                             $result[$id]->bcc = $string;
1259                             break;
1260                         case 'content-transfer-encoding':
1261                             $result[$id]->encoding = $string;
1262                             break;
1263                         case 'content-type':
1264                             $ctype_parts = preg_split('/[; ]/', $string);
1265                             $result[$id]->ctype = array_shift($ctype_parts);
1266                             if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1267                                 $result[$id]->charset = $regs[1];
1268                             }
1269                             break;
1270                         case 'in-reply-to':
1271                             $result[$id]->in_reply_to = preg_replace('/[\n<>]/', '', $string);
1272                             break;
1273                         case 'references':
1274                             $result[$id]->references = $string;
1275                             break;
1276                         case 'return-receipt-to':
1277                         case 'disposition-notification-to':
1278                         case 'x-confirm-reading-to':
1279                             $result[$id]->mdn_to = $string;
1280                             break;
1281                         case 'message-id':
1282                             $result[$id]->messageID = $string;
1283                             break;
1284                         case 'x-priority':
1285                             if (preg_match('/^(\d+)/', $string, $matches))
1286                                 $result[$id]->priority = intval($matches[1]);
1287                             break;
1288                         default:
1289                             if (strlen($field) > 2)
1290                                 $result[$id]->others[$field] = $string;
1291                             break;
1292                         } // end switch ()
1293                     } // end while ()
1294                 } else {
1295                     $a = explode(' ', $line);
1296                 }
1297
1298                 // process flags
1299                 if (!empty($flags_str)) {
1300                     $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1301                     $flags_a   = explode(' ', $flags_str);
1d5165 1302
59c216 1303                     if (is_array($flags_a)) {
A 1304                     //    reset($flags_a);
1305                         foreach($flags_a as $flag) {
1306                             $flag = strtoupper($flag);
1307                             if ($flag == 'SEEN') {
1308                                 $result[$id]->seen = true;
1309                             } else if ($flag == 'DELETED') {
1310                                 $result[$id]->deleted = true;
1311                             } else if ($flag == 'RECENT') {
1312                                 $result[$id]->recent = true;
1313                             } else if ($flag == 'ANSWERED') {
1314                                 $result[$id]->answered = true;
1315                             } else if ($flag == '$FORWARDED') {
1316                                 $result[$id]->forwarded = true;
1317                             } else if ($flag == 'DRAFT') {
1318                                 $result[$id]->is_draft = true;
1319                             } else if ($flag == '$MDNSENT') {
1320                                 $result[$id]->mdn_sent = true;
1321                             } else if ($flag == 'FLAGGED') {
1322                                      $result[$id]->flagged = true;
1323                             }
1324                         }
1325                         $result[$id]->flags = $flags_a;
1326                     }
1327                 }
1328             }
1329         } while (!$this->startsWith($line, $key, true));
1330
1331         return $result;
1332     }
1333
1334     function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1335     {
1336         $a  = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1337         if (is_array($a)) {
1338             return array_shift($a);
1339         }
1340         return false;
1341     }
1342
1343     function sortHeaders($a, $field, $flag)
1344     {
1345         if (empty($field)) {
1346             $field = 'uid';
1347         }
1348         else {
1349             $field = strtolower($field);
1350         }
1351
1352         if ($field == 'date' || $field == 'internaldate') {
1353             $field = 'timestamp';
1354         }
1355         if (empty($flag)) {
1356             $flag = 'ASC';
1357         } else {
1358             $flag = strtoupper($flag);
1359         }
1360
1361         $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ','"') : array('"');
1362
1363         $c = count($a);
1364         if ($c > 0) {
1d5165 1365
59c216 1366             // Strategy:
A 1367             // First, we'll create an "index" array.
1d5165 1368             // Then, we'll use sort() on that array,
59c216 1369             // and use that to sort the main array.
1d5165 1370
59c216 1371             // create "index" array
A 1372             $index = array();
1373             reset($a);
1374             while (list($key, $val) = each($a)) {
1375                 if ($field == 'timestamp') {
1376                     $data = $this->strToTime($val->date);
1377                     if (!$data) {
1378                         $data = $val->timestamp;
1379                     }
1380                 } else {
1381                     $data = $val->$field;
1382                     if (is_string($data)) {
1383                         $data = strtoupper(str_replace($stripArr, '', $data));
1384                     }
1385                 }
1386                 $index[$key]=$data;
1387             }
1d5165 1388
59c216 1389             // sort index
A 1390             $i = 0;
1391             if ($flag == 'ASC') {
1392                 asort($index);
1393             } else {
1394                 arsort($index);
1395             }
1396
1d5165 1397             // form new array based on index
59c216 1398             $result = array();
A 1399             reset($index);
1400             while (list($key, $val) = each($index)) {
1401                 $result[$key]=$a[$key];
1402                 $i++;
1403             }
1404         }
1d5165 1405
59c216 1406         return $result;
A 1407     }
1408
1409     function expunge($mailbox, $messages=NULL)
1410     {
1411         if (!$this->select($mailbox)) {
1412             return -1;
1413         }
1d5165 1414
59c216 1415         $c = 0;
A 1416         $command = $messages ? "UID EXPUNGE $messages" : "EXPUNGE";
1417
1418         if (!$this->putLine("exp1 $command")) {
1419             return -1;
1420         }
1421
1422         do {
1423             $line = $this->readLine(100);
1424             if ($line[0] == '*') {
1425                 $c++;
1426             }
1427         } while (!$this->startsWith($line, 'exp1', true, true));
1d5165 1428
59c216 1429         if ($this->parseResult($line) == 0) {
A 1430             $this->selected = ''; // state has changed, need to reselect
1431             return $c;
1432         }
1433         $this->error = $line;
1434         return -1;
1435     }
1436
1437     function modFlag($mailbox, $messages, $flag, $mod)
1438     {
1439         if ($mod != '+' && $mod != '-') {
1440             return -1;
1441         }
1d5165 1442
59c216 1443         $flag = $this->flags[strtoupper($flag)];
1d5165 1444
59c216 1445         if (!$this->select($mailbox)) {
A 1446             return -1;
1447         }
1d5165 1448
59c216 1449         $c = 0;
A 1450         if (!$this->putLine("flg UID STORE $messages {$mod}FLAGS ($flag)")) {
1451             return false;
1452         }
1453
1454         do {
1455             $line = $this->readLine(1000);
1456             if ($line[0] == '*') {
1457                 $c++;
1458             }
1459         } while (!$this->startsWith($line, 'flg', true, true));
1460
1461         if ($this->parseResult($line) == 0) {
1462             return $c;
1463         }
1464
1465         $this->error = $line;
1466         return -1;
1467     }
1468
1469     function flag($mailbox, $messages, $flag) {
1470         return $this->modFlag($mailbox, $messages, $flag, '+');
1471     }
1472
1473     function unflag($mailbox, $messages, $flag) {
1474         return $this->modFlag($mailbox, $messages, $flag, '-');
1475     }
1476
1477     function delete($mailbox, $messages) {
1478         return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1479     }
1480
1481     function copy($messages, $from, $to)
1482     {
1483         if (empty($from) || empty($to)) {
1484             return -1;
1485         }
1d5165 1486
59c216 1487         if (!$this->select($from)) {
A 1488             return -1;
1489         }
1d5165 1490
59c216 1491         $this->putLine("cpy1 UID COPY $messages \"".$this->escape($to)."\"");
A 1492         $line = $this->readReply();
1493         return $this->parseResult($line);
1494     }
1495
1496     function countUnseen($folder)
1497     {
1498         $index = $this->search($folder, 'ALL UNSEEN');
1499         if (is_array($index))
1500             return count($index);
1501         return false;
1502     }
1503
1504     // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1505     // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1506     // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1507     private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1508     {
1509         $node = array();
1510         if ($str[$begin] != '(') {
0bc59e 1511             $stop = $begin + strspn($str, '1234567890', $begin, $end - $begin);
59c216 1512             $msg = substr($str, $begin, $stop - $begin);
A 1513             if ($msg == 0)
1514                 return $node;
1515             if (is_null($root))
1516                 $root = $msg;
1517             $depthmap[$msg] = $depth;
1518             $haschildren[$msg] = false;
1519             if (!is_null($parent))
1520                 $haschildren[$parent] = true;
1521             if ($stop + 1 < $end)
1522                 $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1523             else
1524                 $node[$msg] = array();
1525         } else {
1526             $off = $begin;
1527             while ($off < $end) {
1528                 $start = $off;
1529                 $off++;
1530                 $n = 1;
1531                 while ($n > 0) {
1532                     $p = strpos($str, ')', $off);
1533                     if ($p === false) {
1534                         error_log('Mismatched brackets parsing IMAP THREAD response:');
1535                         error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
1536                         error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
1537                         return $node;
1538                     }
1539                     $p1 = strpos($str, '(', $off);
1540                     if ($p1 !== false && $p1 < $p) {
1541                         $off = $p1 + 1;
1542                         $n++;
1543                     } else {
1544                         $off = $p + 1;
1545                         $n--;
1546                     }
1547                 }
1548                 $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
1549             }
1550         }
1d5165 1551
59c216 1552         return $node;
A 1553     }
1554
1555     function thread($folder, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
1556     {
ccf250 1557         $old_sel = $this->selected;
A 1558
59c216 1559         if (!$this->select($folder)) {
ccf250 1560             return false;
A 1561         }
1562
1563         // return empty result when folder is empty and we're just after SELECT
1564         if ($old_sel != $folder && !$this->exists) {
1565             return array(array(), array(), array());
59c216 1566         }
A 1567
1568         $encoding  = $encoding ? trim($encoding) : 'US-ASCII';
1569         $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1570         $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
0bc59e 1571         $data      = '';
1d5165 1572
59c216 1573         if (!$this->putLineC("thrd1 THREAD $algorithm $encoding $criteria")) {
A 1574             return false;
1575         }
1576         do {
0bc59e 1577             $line = trim($this->readLine());
A 1578             if ($this->startsWith($line, '* THREAD')) {
1579                 $data .= substr($line, 9);
1580             } else if (preg_match('/^[0-9() ]+$/', $line)) {
1581                 $data .= $line;
59c216 1582             }
A 1583         } while (!$this->startsWith($line, 'thrd1', true, true));
1584
1585         $result_code = $this->parseResult($line);
1586         if ($result_code == 0) {
0bc59e 1587             $depthmap    = array();
A 1588             $haschildren = array();
1589             $tree = $this->parseThread($data, 0, strlen($data), null, null, 0, $depthmap, $haschildren);
1590             return array($tree, $depthmap, $haschildren);
59c216 1591         }
A 1592
1593         $this->error = "Thread: $line";
1d5165 1594         return false;
59c216 1595     }
A 1596
6f31b3 1597     function search($folder, $criteria, $return_uid=false)
59c216 1598     {
309f49 1599         $old_sel = $this->selected;
A 1600
59c216 1601         if (!$this->select($folder)) {
A 1602             return false;
1603         }
1604
309f49 1605         // return empty result when folder is empty and we're just after SELECT
A 1606         if ($old_sel != $folder && !$this->exists) {
1607             return array();
1608         }
1609
59c216 1610         $data = '';
6f31b3 1611         $query = 'srch1 ' . ($return_uid ? 'UID ' : '') . 'SEARCH ' . chop($criteria);
59c216 1612
A 1613         if (!$this->putLineC($query)) {
1614             return false;
1615         }
6f31b3 1616
59c216 1617         do {
A 1618             $line = trim($this->readLine());
1619             if ($this->startsWith($line, '* SEARCH')) {
1620                 $data .= substr($line, 8);
1621             } else if (preg_match('/^[0-9 ]+$/', $line)) {
1622                 $data .= $line;
1623             }
1624         } while (!$this->startsWith($line, 'srch1', true, true));
1625
1626         $result_code = $this->parseResult($line);
1627         if ($result_code == 0) {
1628             return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
1629         }
1630
1631         $this->error = "Search: $line";
1d5165 1632         return false;
59c216 1633     }
A 1634
1635     function move($messages, $from, $to)
1636     {
1637         if (!$from || !$to) {
1638             return -1;
1639         }
1d5165 1640
59c216 1641         $r = $this->copy($messages, $from, $to);
A 1642
1643         if ($r==0) {
1644             return $this->delete($from, $messages);
1645         }
1646         return $r;
1647     }
1648
1649     function listMailboxes($ref, $mailbox)
1650     {
f0485a 1651         return $this->_listMailboxes($ref, $mailbox, false);
A 1652     }
1653
1654     function listSubscribed($ref, $mailbox)
1655     {
1656         return $this->_listMailboxes($ref, $mailbox, true);
1657     }
1658
1659     private function _listMailboxes($ref, $mailbox, $subscribed=false)
1660     {
59c216 1661         if (empty($mailbox)) {
A 1662             $mailbox = '*';
1663         }
1d5165 1664
59c216 1665         if (empty($ref) && $this->rootdir) {
A 1666             $ref = $this->rootdir;
1667         }
1d5165 1668
f0485a 1669         if ($subscribed) {
A 1670             $key     = 'lsb';
1671             $command = 'LSUB';
1672         }
1673         else {
1674             $key     = 'lmb';
1675             $command = 'LIST';
1676         }
1677
59c216 1678         // send command
f0485a 1679         if (!$this->putLine($key." ".$command." \"". $this->escape($ref) ."\" \"". $this->escape($mailbox) ."\"")) {
A 1680             $this->error = "Couldn't send $command command";
59c216 1681             return false;
A 1682         }
1d5165 1683
59c216 1684         // get folder list
A 1685         do {
1686             $line = $this->readLine(500);
1687             $line = $this->multLine($line, true);
f0485a 1688             $a    = explode(' ', $line);
59c216 1689
f0485a 1690             if (($line[0] == '*') && ($a[1] == $command)) {
59c216 1691                 $line = rtrim($line);
A 1692                 // split one line
1693                 $a = rcube_explode_quoted_string(' ', $line);
1694                 // last string is folder name
f0485a 1695                 $folders[] = preg_replace(array('/^"/', '/"$/'), '', $this->unEscape($a[count($a)-1]));
59c216 1696                 // second from last is delimiter
A 1697                 $delim = trim($a[count($a)-2], '"');
1698             }
f0485a 1699         } while (!$this->startsWith($line, $key, true));
59c216 1700
A 1701         if (is_array($folders)) {
1702             return $folders;
1703         } else if ($this->parseResult($line) == 0) {
f0485a 1704             return array();
59c216 1705         }
A 1706
1707         $this->error = $line;
1708         return false;
1709     }
1710
1711     function fetchMIMEHeaders($mailbox, $id, $parts, $mime=true)
1712     {
1713         if (!$this->select($mailbox)) {
1714             return false;
1715         }
1d5165 1716
59c216 1717         $result = false;
A 1718         $parts  = (array) $parts;
1719         $key    = 'fmh0';
1720         $peeks  = '';
1721         $idx    = 0;
1722         $type   = $mime ? 'MIME' : 'HEADER';
1723
1724         // format request
1725         foreach($parts as $part)
1726             $peeks[] = "BODY.PEEK[$part.$type]";
1d5165 1727
59c216 1728         $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
A 1729
1730         // send request
1731         if (!$this->putLine($request)) {
1732             return false;
1733         }
1d5165 1734
59c216 1735         do {
A 1736             $line = $this->readLine(1000);
1737             $line = $this->multLine($line);
1738
1739             if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
1740                 $idx = $matches[1];
1741                 $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.'.$type.'\]\s+/', '', $line);
1742                 $result[$idx] = trim($result[$idx], '"');
1743                 $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
1744             }
1745         } while (!$this->startsWith($line, $key, true));
1746
1747         return $result;
1748     }
1749
1750     function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
1751     {
1752         $part = empty($part) ? 'HEADER' : $part.'.MIME';
1753
1754         return $this->handlePartBody($mailbox, $id, $is_uid, $part);
1755     }
1756
1757     function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
1758     {
1759         if (!$this->select($mailbox)) {
1760             return false;
1761         }
1762
1763         switch ($encoding) {
1764             case 'base64':
1765                 $mode = 1;
1766             break;
1767             case 'quoted-printable':
1768                 $mode = 2;
1769             break;
1770             case 'x-uuencode':
1771             case 'x-uue':
1772             case 'uue':
1773             case 'uuencode':
1774                 $mode = 3;
1775             break;
1776             default:
1777                 $mode = 0;
1778         }
1d5165 1779
59c216 1780         // format request
64e3e8 1781            $reply_key = '* ' . $id;
A 1782         $key       = 'ftch0';
1783         $request   = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
1784
59c216 1785         // send request
A 1786         if (!$this->putLine($request)) {
1787             return false;
1788            }
1789
1790            // receive reply line
1791            do {
1792                $line = chop($this->readLine(1000));
1793                $a    = explode(' ', $line);
1794            } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
1795
64e3e8 1796            $len    = strlen($line);
A 1797         $result = false;
59c216 1798
A 1799         // handle empty "* X FETCH ()" response
1800         if ($line[$len-1] == ')' && $line[$len-2] != '(') {
1801             // one line response, get everything between first and last quotes
1802             if (substr($line, -4, 3) == 'NIL') {
1803                 // NIL response
1804                 $result = '';
1805             } else {
1806                 $from = strpos($line, '"') + 1;
1807                 $to   = strrpos($line, '"');
1808                 $len  = $to - $from;
1809                 $result = substr($line, $from, $len);
1810             }
1811
1812             if ($mode == 1)
1813                 $result = base64_decode($result);
1814             else if ($mode == 2)
1815                 $result = quoted_printable_decode($result);
1816             else if ($mode == 3)
1817                 $result = convert_uudecode($result);
1818
1819         } else if ($line[$len-1] == '}') {
1820             // multi-line request, find sizes of content and receive that many bytes
1821             $from     = strpos($line, '{') + 1;
1822             $to       = strrpos($line, '}');
1823             $len      = $to - $from;
1824             $sizeStr  = substr($line, $from, $len);
1825             $bytes    = (int)$sizeStr;
1826             $prev      = '';
1d5165 1827
59c216 1828             while ($bytes > 0) {
A 1829                 $line = $this->readLine(1024);
1830                 $len  = strlen($line);
1d5165 1831
59c216 1832                 if ($len > $bytes) {
A 1833                     $line = substr($line, 0, $bytes);
1834                     $len = strlen($line);
1835                 }
1836                 $bytes -= $len;
1837
1838                 if ($mode == 1) {
1839                     $line = rtrim($line, "\t\r\n\0\x0B");
1840                     // create chunks with proper length for base64 decoding
1841                     $line = $prev.$line;
1842                     $length = strlen($line);
1843                     if ($length % 4) {
1844                         $length = floor($length / 4) * 4;
1845                         $prev = substr($line, $length);
1846                         $line = substr($line, 0, $length);
1847                     }
1848                     else
1849                         $prev = '';
1d5165 1850
59c216 1851                     if ($file)
A 1852                         fwrite($file, base64_decode($line));
1853                     else if ($print)
1854                         echo base64_decode($line);
1855                     else
1856                         $result .= base64_decode($line);
1857                 } else if ($mode == 2) {
1858                     $line = rtrim($line, "\t\r\0\x0B");
1859                     if ($file)
1860                         fwrite($file, quoted_printable_decode($line));
1861                     else if ($print)
1862                         echo quoted_printable_decode($line);
1863                     else
1864                         $result .= quoted_printable_decode($line);
1865                 } else if ($mode == 3) {
1866                     $line = rtrim($line, "\t\r\n\0\x0B");
1867                     if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
1868                         continue;
1869                     if ($file)
1870                         fwrite($file, convert_uudecode($line));
1871                     else if ($print)
1872                         echo convert_uudecode($line);
1873                     else
1874                         $result .= convert_uudecode($line);
1875                 } else {
1876                     $line = rtrim($line, "\t\r\n\0\x0B");
1877                     if ($file)
1878                         fwrite($file, $line . "\n");
1879                     else if ($print)
1880                         echo $line . "\n";
1881                     else
1882                         $result .= $line . "\n";
1883                 }
1884             }
1885         }
1d5165 1886
59c216 1887         // read in anything up until last line
A 1888         if (!$end)
1889             do {
1890                     $line = $this->readLine(1024);
1891             } while (!$this->startsWith($line, $key, true));
1892
64e3e8 1893            if ($result !== false) {
59c216 1894             if ($file) {
A 1895                 fwrite($file, $result);
1896                } else if ($print) {
1897                 echo $result;
1898             } else
1899                 return $result;
1900                return true;
1901            }
1902
1903         return false;
1904     }
1905
1906     function createFolder($folder)
1907     {
1908         if ($this->putLine('c CREATE "' . $this->escape($folder) . '"')) {
1909             do {
1910                 $line = $this->readLine(300);
1911             } while (!$this->startsWith($line, 'c ', true, true));
1912             return ($this->parseResult($line) == 0);
1913         }
1914         return false;
1915     }
1916
1917     function renameFolder($from, $to)
1918     {
1919         if ($this->putLine('r RENAME "' . $this->escape($from) . '" "' . $this->escape($to) . '"')) {
1920             do {
1921                 $line = $this->readLine(300);
1922             } while (!$this->startsWith($line, 'r ', true, true));
1923             return ($this->parseResult($line) == 0);
1924         }
1925         return false;
1926     }
1927
1928     function deleteFolder($folder)
1929     {
1930         if ($this->putLine('d DELETE "' . $this->escape($folder). '"')) {
1931             do {
1932                 $line = $this->readLine(300);
1933             } while (!$this->startsWith($line, 'd ', true, true));
1934             return ($this->parseResult($line) == 0);
1935         }
1936         return false;
1937     }
1938
1939     function clearFolder($folder)
1940     {
1941         $num_in_trash = $this->countMessages($folder);
1942         if ($num_in_trash > 0) {
1943             $this->delete($folder, '1:*');
1944         }
1945         return ($this->expunge($folder) >= 0);
1946     }
1947
1948     function subscribe($folder)
1949     {
1950         $query = 'sub1 SUBSCRIBE "' . $this->escape($folder). '"';
1951         $this->putLine($query);
1952
1953         $line = trim($this->readLine(512));
1954         return ($this->parseResult($line) == 0);
1955     }
1956
1957     function unsubscribe($folder)
1958     {
1959         $query = 'usub1 UNSUBSCRIBE "' . $this->escape($folder) . '"';
1960         $this->putLine($query);
1d5165 1961
59c216 1962         $line = trim($this->readLine(512));
A 1963         return ($this->parseResult($line) == 0);
1964     }
1965
1966     function append($folder, &$message)
1967     {
1968         if (!$folder) {
1969             return false;
1970         }
1971
1972         $message = str_replace("\r", '', $message);
1973         $message = str_replace("\n", "\r\n", $message);
1974
1975         $len = strlen($message);
1976         if (!$len) {
1977             return false;
1978         }
1979
1980         $request = 'a APPEND "' . $this->escape($folder) .'" (\\Seen) {' . $len . '}';
1981
1982         if ($this->putLine($request)) {
1983             $line = $this->readLine(512);
1984
1985             if ($line[0] != '+') {
1986                 // $errornum = $this->parseResult($line);
1987                 $this->error = "Cannot write to folder: $line";
1988                 return false;
1989             }
1990
1991             if (!$this->putLine($message)) {
1992                 return false;
1993             }
1994
1995             do {
1996                 $line = $this->readLine();
1997             } while (!$this->startsWith($line, 'a ', true, true));
1d5165 1998
59c216 1999             $result = ($this->parseResult($line) == 0);
A 2000             if (!$result) {
2001                 $this->error = $line;
2002             }
2003             return $result;
2004         }
2005
2006         $this->error = "Couldn't send command \"$request\"";
2007         return false;
2008     }
2009
2010     function appendFromFile($folder, $path, $headers=null, $separator="\n\n")
2011     {
2012         if (!$folder) {
2013             return false;
2014         }
1d5165 2015
59c216 2016         // open message file
A 2017         $in_fp = false;
2018         if (file_exists(realpath($path))) {
2019             $in_fp = fopen($path, 'r');
2020         }
1d5165 2021         if (!$in_fp) {
59c216 2022             $this->error = "Couldn't open $path for reading";
A 2023             return false;
2024         }
1d5165 2025
59c216 2026         $len = filesize($path);
A 2027         if (!$len) {
2028             return false;
2029         }
2030
2031         if ($headers) {
2032             $headers = preg_replace('/[\r\n]+$/', '', $headers);
2033             $len += strlen($headers) + strlen($separator);
2034         }
2035
2036         // send APPEND command
2037         $request    = 'a APPEND "' . $this->escape($folder) . '" (\\Seen) {' . $len . '}';
2038         if ($this->putLine($request)) {
2039             $line = $this->readLine(512);
2040
2041             if ($line[0] != '+') {
2042                 //$errornum = $this->parseResult($line);
2043                 $this->error = "Cannot write to folder: $line";
2044                 return false;
2045             }
2046
2047             // send headers with body separator
2048             if ($headers) {
2049                 $this->putLine($headers . $separator, false);
2050             }
2051
2052             // send file
2053             while (!feof($in_fp) && $this->fp) {
2054                 $buffer = fgets($in_fp, 4096);
2055                 $this->putLine($buffer, false);
2056             }
2057             fclose($in_fp);
2058
2059             if (!$this->putLine('')) { // \r\n
2060                 return false;
2061             }
2062
2063             // read response
2064             do {
2065                 $line = $this->readLine();
2066             } while (!$this->startsWith($line, 'a ', true, true));
2067
2068             $result = ($this->parseResult($line) == 0);
2069             if (!$result) {
2070                 $this->error = $line;
2071             }
2072
2073             return $result;
2074         }
1d5165 2075
59c216 2076         $this->error = "Couldn't send command \"$request\"";
A 2077         return false;
2078     }
2079
2080     function fetchStructureString($folder, $id, $is_uid=false)
2081     {
2082         if (!$this->select($folder)) {
2083             return false;
2084         }
2085
2086         $key = 'F1247';
2087         $result = false;
2088
2089         if ($this->putLine($key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)")) {
2090             do {
2091                 $line = $this->readLine(5000);
2092                 $line = $this->multLine($line, true);
2093                 if (!preg_match("/^$key/", $line))
2094                     $result .= $line;
2095             } while (!$this->startsWith($line, $key, true, true));
2096
2097             $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2098         }
2099
2100         return $result;
2101     }
2102
2103     function getQuota()
2104     {
2105         /*
2106          * GETQUOTAROOT "INBOX"
2107          * QUOTAROOT INBOX user/rchijiiwa1
2108          * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2109          * OK Completed
2110          */
2111         $result      = false;
2112         $quota_lines = array();
1d5165 2113
59c216 2114         // get line(s) containing quota info
A 2115         if ($this->putLine('QUOT1 GETQUOTAROOT "INBOX"')) {
2116             do {
2117                 $line = chop($this->readLine(5000));
2118                 if ($this->startsWith($line, '* QUOTA ')) {
2119                     $quota_lines[] = $line;
2120                 }
2121             } while (!$this->startsWith($line, 'QUOT1', true, true));
2122         }
1d5165 2123
59c216 2124         // return false if not found, parse if found
A 2125         $min_free = PHP_INT_MAX;
2126         foreach ($quota_lines as $key => $quota_line) {
2127             $quota_line   = preg_replace('/[()]/', '', $quota_line);
2128             $parts        = explode(' ', $quota_line);
2129             $storage_part = array_search('STORAGE', $parts);
1d5165 2130
59c216 2131             if (!$storage_part)
A 2132                 continue;
1d5165 2133
59c216 2134             $used  = intval($parts[$storage_part+1]);
A 2135             $total = intval($parts[$storage_part+2]);
1d5165 2136             $free  = $total - $used;
A 2137
59c216 2138             // return lowest available space from all quotas
1d5165 2139             if ($free < $min_free) {
A 2140                 $min_free          = $free;
59c216 2141                 $result['used']    = $used;
A 2142                 $result['total']   = $total;
2143                 $result['percent'] = min(100, round(($used/max(1,$total))*100));
2144                 $result['free']    = 100 - $result['percent'];
2145             }
2146         }
2147
2148         return $result;
2149     }
2150
6f31b3 2151     private function _xor($string, $string2)
59c216 2152     {
A 2153         $result = '';
2154         $size = strlen($string);
2155         for ($i=0; $i<$size; $i++) {
2156             $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
2157         }
2158         return $result;
2159     }
2160
2161     private function strToTime($date)
2162     {
2163         // support non-standard "GMTXXXX" literal
2164         $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
2165         // if date parsing fails, we have a date in non-rfc format.
2166         // remove token from the end and try again
2167         while ((($ts = @strtotime($date))===false) || ($ts < 0)) {
2168             $d = explode(' ', $date);
2169             array_pop($d);
2170             if (!$d) break;
2171             $date = implode(' ', $d);
2172         }
2173
2174         $ts = (int) $ts;
2175
1d5165 2176         return $ts < 0 ? 0 : $ts;
59c216 2177     }
A 2178
2179     private function SplitHeaderLine($string)
2180     {
2181         $pos = strpos($string, ':');
2182         if ($pos>0) {
2183             $res[0] = substr($string, 0, $pos);
2184             $res[1] = trim(substr($string, $pos+1));
2185             return $res;
2186         }
2187         return $string;
2188     }
2189
2190     private function parseNamespace($str, &$i, $len=0, $l)
2191     {
2192         if (!$l) {
2193             $str = str_replace('NIL', '()', $str);
2194         }
2195         if (!$len) {
2196             $len = strlen($str);
2197         }
2198         $data      = array();
2199         $in_quotes = false;
2200         $elem      = 0;
1d5165 2201
59c216 2202         for ($i;$i<$len;$i++) {
A 2203             $c = (string)$str[$i];
2204             if ($c == '(' && !$in_quotes) {
2205                 $i++;
2206                 $data[$elem] = $this->parseNamespace($str, $i, $len, $l++);
2207                 $elem++;
2208             } else if ($c == ')' && !$in_quotes) {
2209                 return $data;
2210             } else if ($c == '\\') {
2211                 $i++;
2212                 if ($in_quotes) {
2213                     $data[$elem] .= $c.$str[$i];
2214                 }
2215             } else if ($c == '"') {
2216                 $in_quotes = !$in_quotes;
2217                 if (!$in_quotes) {
2218                     $elem++;
2219                 }
2220             } else if ($in_quotes) {
2221                 $data[$elem].=$c;
2222             }
2223         }
1d5165 2224
59c216 2225         return $data;
A 2226     }
2227
2228     private function escape($string)
2229     {
1d5165 2230         return strtr($string, array('"'=>'\\"', '\\' => '\\\\'));
59c216 2231     }
A 2232
2233     private function unEscape($string)
2234     {
1d5165 2235         return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
59c216 2236     }
A 2237
2238 }
2239
2240 ?>