alecpl
2010-06-04 f22b5439f2e783f47f61042bebb6cc53672568fd
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]));
648         }
649
650         $this->message .= $line;
651
652         // TLS connection
653         if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
654             if (version_compare(PHP_VERSION, '5.1.0', '>=')) {
655                    $this->putLine("tls0 STARTTLS");
656
657                 $line = $this->readLine(4096);
658                 if (!$this->startsWith($line, "tls0 OK")) {
659                     $this->error    = "Server responded to STARTTLS with: $line";
660                     $this->errornum = -2;
661                     return false;
662                 }
663
664                 if (!stream_socket_enable_crypto($this->fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
665                     $this->error    = "Unable to negotiate TLS";
666                     $this->errornum = -2;
667                     return false;
668                 }
1d5165 669
59c216 670                 // Now we're authenticated, capabilities need to be reread
A 671                 $this->clearCapability();
672             }
673         }
674
675         $orig_method = $auth_method;
676
677         if ($auth_method == 'CHECK') {
678             // check for supported auth methods
679             if ($this->getCapability('AUTH=CRAM-MD5') || $this->getCapability('AUTH=CRAM_MD5')) {
680                 $auth_method = 'AUTH';
681             }
682             else {
683                 // default to plain text auth
684                 $auth_method = 'PLAIN';
685             }
686         }
687
688         if ($auth_method == 'AUTH') {
689             // do CRAM-MD5 authentication
690             $this->putLine("a000 AUTHENTICATE CRAM-MD5");
691             $line = trim($this->readLine(1024));
692
693             if ($line[0] == '+') {
694                 // got a challenge string, try CRAM-MD5
695                 $result = $this->authenticate($user, $password, substr($line,2));
1d5165 696
59c216 697                 // stop if server sent BYE response
A 698                 if ($result == -3) {
699                     return false;
700                 }
701             }
1d5165 702
59c216 703             if (!is_resource($result) && $orig_method == 'CHECK') {
A 704                 $auth_method = 'PLAIN';
705             }
706         }
1d5165 707
59c216 708         if ($auth_method == 'PLAIN') {
A 709             // do plain text auth
710             $result = $this->login($user, $password);
711         }
712
713         if (is_resource($result)) {
714             if ($this->prefs['force_caps']) {
715                 $this->clearCapability();
716             }
c85424 717             $this->getNamespace();
59c216 718             $this->logged = true;
A 719             return true;
720         } else {
721             return false;
722         }
723     }
724
725     function connected()
726     {
727         return ($this->fp && $this->logged) ? true : false;
728     }
729
730     function close()
731     {
732         if ($this->putLine("I LOGOUT")) {
733             if (!feof($this->fp))
734                 fgets($this->fp, 1024);
735         }
736         @fclose($this->fp);
737         $this->fp = false;
738     }
739
740     function select($mailbox)
741     {
742         if (empty($mailbox)) {
743             return false;
744         }
745         if ($this->selected == $mailbox) {
746             return true;
747         }
1d5165 748
59c216 749         if ($this->putLine("sel1 SELECT \"".$this->escape($mailbox).'"')) {
A 750             do {
751                 $line = chop($this->readLine(300));
752                 $a = explode(' ', $line);
753                 if (count($a) == 3) {
754                     $token = strtoupper($a[2]);
755                     if ($token == 'EXISTS') {
756                         $this->exists = (int) $a[1];
757                     }
758                     else if ($token == 'RECENT') {
759                         $this->recent = (int) $a[1];
760                     }
761                 }
762                 else if (preg_match('/\[?PERMANENTFLAGS\s+\(([^\)]+)\)\]/U', $line, $match)) {
763                     $this->permanentflags = explode(' ', $match[1]);
764                 }
765             } while (!$this->startsWith($line, 'sel1', true, true));
766
767             if (strcasecmp($a[1], 'OK') == 0) {
768                 $this->selected = $mailbox;
769                 return true;
770             }
771             else {
772                 $this->error = "Couldn't select $mailbox";
773             }
774         }
775
776         return false;
777     }
778
779     function checkForRecent($mailbox)
780     {
781         if (empty($mailbox)) {
782             $mailbox = 'INBOX';
783         }
1d5165 784
59c216 785         $this->select($mailbox);
A 786         if ($this->selected == $mailbox) {
787             return $this->recent;
788         }
789
790         return false;
791     }
792
793     function countMessages($mailbox, $refresh = false)
794     {
795         if ($refresh) {
796             $this->selected = '';
797         }
1d5165 798
59c216 799         $this->select($mailbox);
A 800         if ($this->selected == $mailbox) {
801             return $this->exists;
802         }
803
804         return false;
805     }
806
807     function sort($mailbox, $field, $add='', $is_uid=FALSE, $encoding = 'US-ASCII')
808     {
809         $field = strtoupper($field);
810         if ($field == 'INTERNALDATE') {
811             $field = 'ARRIVAL';
812         }
1d5165 813
59c216 814         $fields = array('ARRIVAL' => 1,'CC' => 1,'DATE' => 1,
A 815             'FROM' => 1, 'SIZE' => 1, 'SUBJECT' => 1, 'TO' => 1);
816
817         if (!$fields[$field]) {
818             return false;
819         }
820
821         /*  Do "SELECT" command */
822         if (!$this->select($mailbox)) {
823             return false;
824         }
1d5165 825
59c216 826         $is_uid = $is_uid ? 'UID ' : '';
1d5165 827
59c216 828         // message IDs
A 829         if (is_array($add))
830             $add = $this->compressMessageSet(join(',', $add));
831
832         $command  = "s ".$is_uid."SORT ($field) $encoding ALL";
833         $line     = $data = '';
834
835         if (!empty($add))
836             $command .= ' '.$add;
837
838         if (!$this->putLineC($command)) {
839             return false;
840         }
841         do {
842             $line = chop($this->readLine());
843             if ($this->startsWith($line, '* SORT')) {
844                 $data .= substr($line, 7);
845             } else if (preg_match('/^[0-9 ]+$/', $line)) {
846                 $data .= $line;
847             }
848         } while (!$this->startsWith($line, 's ', true, true));
1d5165 849
59c216 850         $result_code = $this->parseResult($line);
1d5165 851
59c216 852         if ($result_code != 0) {
A 853             $this->error = "Sort: $line";
854             return false;
855         }
1d5165 856
59c216 857         return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
A 858     }
859
860     function fetchHeaderIndex($mailbox, $message_set, $index_field='', $skip_deleted=true, $uidfetch=false)
861     {
862         if (is_array($message_set)) {
863             if (!($message_set = $this->compressMessageSet(join(',', $message_set))))
864                 return false;
865         } else {
866             list($from_idx, $to_idx) = explode(':', $message_set);
867             if (empty($message_set) ||
868                 (isset($to_idx) && $to_idx != '*' && (int)$from_idx > (int)$to_idx)) {
869                 return false;
870             }
871         }
1d5165 872
59c216 873         $index_field = empty($index_field) ? 'DATE' : strtoupper($index_field);
1d5165 874
59c216 875         $fields_a['DATE']         = 1;
A 876         $fields_a['INTERNALDATE'] = 4;
877         $fields_a['ARRIVAL']       = 4;
878         $fields_a['FROM']         = 1;
879         $fields_a['REPLY-TO']     = 1;
880         $fields_a['SENDER']       = 1;
881         $fields_a['TO']           = 1;
882         $fields_a['CC']           = 1;
883         $fields_a['SUBJECT']      = 1;
884         $fields_a['UID']          = 2;
885         $fields_a['SIZE']         = 2;
886         $fields_a['SEEN']         = 3;
887         $fields_a['RECENT']       = 3;
888         $fields_a['DELETED']      = 3;
889
890         if (!($mode = $fields_a[$index_field])) {
891             return false;
892         }
893
894         /*  Do "SELECT" command */
895         if (!$this->select($mailbox)) {
896             return false;
897         }
1d5165 898
59c216 899         // build FETCH command string
A 900         $key     = 'fhi0';
901         $cmd     = $uidfetch ? 'UID FETCH' : 'FETCH';
902         $deleted = $skip_deleted ? ' FLAGS' : '';
903
904         if ($mode == 1 && $index_field == 'DATE')
905             $request = " $cmd $message_set (INTERNALDATE BODY.PEEK[HEADER.FIELDS (DATE)]$deleted)";
906         else if ($mode == 1)
907             $request = " $cmd $message_set (BODY.PEEK[HEADER.FIELDS ($index_field)]$deleted)";
908         else if ($mode == 2) {
909             if ($index_field == 'SIZE')
910                 $request = " $cmd $message_set (RFC822.SIZE$deleted)";
911             else
912                 $request = " $cmd $message_set ($index_field$deleted)";
913         } else if ($mode == 3)
914             $request = " $cmd $message_set (FLAGS)";
915         else // 4
916             $request = " $cmd $message_set (INTERNALDATE$deleted)";
917
918         $request = $key . $request;
919
920         if (!$this->putLine($request)) {
921             return false;
922         }
923
924         $result = array();
925
926         do {
927             $line = chop($this->readLine(200));
928             $line = $this->multLine($line);
929
930             if (preg_match('/^\* ([0-9]+) FETCH/', $line, $m)) {
931                 $id     = $m[1];
932                 $flags  = NULL;
1d5165 933
59c216 934                 if ($skip_deleted && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
A 935                     $flags = explode(' ', strtoupper($matches[1]));
936                     if (in_array('\\DELETED', $flags)) {
937                         $deleted[$id] = $id;
938                         continue;
939                     }
940                 }
941
942                 if ($mode == 1 && $index_field == 'DATE') {
943                     if (preg_match('/BODY\[HEADER\.FIELDS \("*DATE"*\)\] (.*)/', $line, $matches)) {
944                         $value = preg_replace(array('/^"*[a-z]+:/i'), '', $matches[1]);
945                         $value = trim($value);
946                         $result[$id] = $this->strToTime($value);
947                     }
948                     // non-existent/empty Date: header, use INTERNALDATE
949                     if (empty($result[$id])) {
950                         if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches))
951                             $result[$id] = $this->strToTime($matches[1]);
952                         else
953                             $result[$id] = 0;
954                     }
955                 } else if ($mode == 1) {
956                     if (preg_match('/BODY\[HEADER\.FIELDS \("?(FROM|REPLY-TO|SENDER|TO|SUBJECT)"?\)\] (.*)/', $line, $matches)) {
957                         $value = preg_replace(array('/^"*[a-z]+:/i', '/\s+$/sm'), array('', ''), $matches[2]);
958                         $result[$id] = trim($value);
959                     } else {
960                         $result[$id] = '';
961                     }
962                 } else if ($mode == 2) {
963                     if (preg_match('/\((UID|RFC822\.SIZE) ([0-9]+)/', $line, $matches)) {
964                         $result[$id] = trim($matches[2]);
965                     } else {
966                         $result[$id] = 0;
967                     }
968                 } else if ($mode == 3) {
969                     if (!$flags && preg_match('/FLAGS \(([^)]+)\)/', $line, $matches)) {
970                         $flags = explode(' ', $matches[1]);
971                     }
972                     $result[$id] = in_array('\\'.$index_field, $flags) ? 1 : 0;
973                 } else if ($mode == 4) {
974                     if (preg_match('/INTERNALDATE "([^"]+)"/', $line, $matches)) {
975                         $result[$id] = $this->strToTime($matches[1]);
976                     } else {
977                         $result[$id] = 0;
978                     }
979                 }
980             }
981         } while (!$this->startsWith($line, $key, true, true));
982
1d5165 983         return $result;
59c216 984     }
A 985
986     private function compressMessageSet($message_set)
987     {
1d5165 988         // given a comma delimited list of independent mid's,
59c216 989         // compresses by grouping sequences together
1d5165 990
59c216 991         // if less than 255 bytes long, let's not bother
A 992         if (strlen($message_set)<255) {
993             return $message_set;
994         }
1d5165 995
59c216 996         // see if it's already been compress
A 997         if (strpos($message_set, ':') !== false) {
998             return $message_set;
999         }
1d5165 1000
59c216 1001         // separate, then sort
A 1002         $ids = explode(',', $message_set);
1003         sort($ids);
1d5165 1004
59c216 1005         $result = array();
A 1006         $start  = $prev = $ids[0];
1007
1008         foreach ($ids as $id) {
1009             $incr = $id - $prev;
1010             if ($incr > 1) {            //found a gap
1011                 if ($start == $prev) {
1012                     $result[] = $prev;    //push single id
1013                 } else {
1014                     $result[] = $start . ':' . $prev;   //push sequence as start_id:end_id
1015                 }
1016                 $start = $id;            //start of new sequence
1017             }
1018             $prev = $id;
1019         }
1020
1021         // handle the last sequence/id
1022         if ($start==$prev) {
1023             $result[] = $prev;
1024         } else {
1025             $result[] = $start.':'.$prev;
1026         }
1d5165 1027
59c216 1028         // return as comma separated string
A 1029         return implode(',', $result);
1030     }
1031
1032     function UID2ID($folder, $uid)
1033     {
1034         if ($uid > 0) {
1035             $id_a = $this->search($folder, "UID $uid");
1036             if (is_array($id_a) && count($id_a) == 1) {
1037                 return $id_a[0];
1038             }
1039         }
1040         return false;
1041     }
1042
1043     function ID2UID($folder, $id)
1044     {
1045         if (empty($id)) {
1046             return     -1;
1047         }
1048
1049         if (!$this->select($folder)) {
1050             return -1;
1051         }
1052
1053         $result = -1;
1054         if ($this->putLine("fuid FETCH $id (UID)")) {
1055             do {
1056                 $line = chop($this->readLine(1024));
1057                 if (preg_match("/^\* $id FETCH \(UID (.*)\)/i", $line, $r)) {
1058                     $result = $r[1];
1059                 }
1060             } while (!$this->startsWith($line, 'fuid', true, true));
1061         }
1062
1063         return $result;
1064     }
1065
1066     function fetchUIDs($mailbox, $message_set=null)
1067     {
1068         if (is_array($message_set))
1069             $message_set = join(',', $message_set);
1070         else if (empty($message_set))
1071             $message_set = '1:*';
1d5165 1072
59c216 1073         return $this->fetchHeaderIndex($mailbox, $message_set, 'UID', false);
A 1074     }
1075
1076     function fetchHeaders($mailbox, $message_set, $uidfetch=false, $bodystr=false, $add='')
1077     {
1078         $result = array();
1d5165 1079
59c216 1080         if (!$this->select($mailbox)) {
A 1081             return false;
1082         }
1083
1084         if (is_array($message_set))
1085             $message_set = join(',', $message_set);
1086
1087         $message_set = $this->compressMessageSet($message_set);
1088
1089         if ($add)
1090             $add = ' '.strtoupper(trim($add));
1091
1092         /* FETCH uid, size, flags and headers */
1093         $key        = 'FH12';
1094         $request  = $key . ($uidfetch ? ' UID' : '') . " FETCH $message_set ";
1095         $request .= "(UID RFC822.SIZE FLAGS INTERNALDATE ";
1096         if ($bodystr)
1097             $request .= "BODYSTRUCTURE ";
1098         $request .= "BODY.PEEK[HEADER.FIELDS ";
1099         $request .= "(DATE FROM TO SUBJECT REPLY-TO IN-REPLY-TO CC BCC ";
1100         $request .= "CONTENT-TRANSFER-ENCODING CONTENT-TYPE MESSAGE-ID ";
1101         $request .= "REFERENCES DISPOSITION-NOTIFICATION-TO X-PRIORITY ";
1102         $request .= "X-DRAFT-INFO".$add.")])";
1103
1104         if (!$this->putLine($request)) {
1105             return false;
1106         }
1107         do {
1108             $line = $this->readLine(1024);
1109             $line = $this->multLine($line);
1d5165 1110
59c216 1111             if (!$line)
A 1112                 break;
1d5165 1113
59c216 1114             $a    = explode(' ', $line);
A 1115
1116             if (($line[0] == '*') && ($a[2] == 'FETCH')) {
1117                 $id = $a[1];
1d5165 1118
59c216 1119                 $result[$id]            = new rcube_mail_header;
A 1120                 $result[$id]->id        = $id;
1121                 $result[$id]->subject   = '';
1122                 $result[$id]->messageID = 'mid:' . $id;
1123
1124                 $lines = array();
1125                 $ln = 0;
1126
1127                 // Sample reply line:
1128                 // * 321 FETCH (UID 2417 RFC822.SIZE 2730 FLAGS (\Seen)
1129                 // INTERNALDATE "16-Nov-2008 21:08:46 +0100" BODYSTRUCTURE (...)
1130                 // BODY[HEADER.FIELDS ...
1131
1132                 if (preg_match('/^\* [0-9]+ FETCH \((.*) BODY/s', $line, $matches)) {
1133                     $str = $matches[1];
1134
1135                     // swap parents with quotes, then explode
1136                     $str = preg_replace('/[()]/', '"', $str);
1137                     $a = rcube_explode_quoted_string(' ', $str);
1138
1139                     // did we get the right number of replies?
1140                     $parts_count = count($a);
1141                     if ($parts_count>=6) {
1142                         for ($i=0; $i<$parts_count; $i=$i+2) {
1143                             if ($a[$i] == 'UID')
1144                                 $result[$id]->uid = $a[$i+1];
1145                             else if ($a[$i] == 'RFC822.SIZE')
1146                                 $result[$id]->size = $a[$i+1];
1147                             else if ($a[$i] == 'INTERNALDATE')
1148                                 $time_str = $a[$i+1];
1149                             else if ($a[$i] == 'FLAGS')
1150                                 $flags_str = $a[$i+1];
1151                         }
1152
1153                         $time_str = str_replace('"', '', $time_str);
1d5165 1154
59c216 1155                         // if time is gmt...
A 1156                         $time_str = str_replace('GMT','+0000',$time_str);
1d5165 1157
59c216 1158                         $result[$id]->internaldate = $time_str;
A 1159                         $result[$id]->timestamp = $this->StrToTime($time_str);
1160                         $result[$id]->date = $time_str;
1161                     }
1162
1d5165 1163                     // BODYSTRUCTURE
59c216 1164                     if($bodystr) {
A 1165                         while (!preg_match('/ BODYSTRUCTURE (.*) BODY\[HEADER.FIELDS/s', $line, $m)) {
1166                             $line2 = $this->readLine(1024);
1167                             $line .= $this->multLine($line2, true);
1168                         }
1169                         $result[$id]->body_structure = $m[1];
1170                     }
1171
1172                     // the rest of the result
1173                     preg_match('/ BODY\[HEADER.FIELDS \(.*?\)\]\s*(.*)$/s', $line, $m);
1174                     $reslines = explode("\n", trim($m[1], '"'));
1175                     // re-parse (see below)
1176                     foreach ($reslines as $resln) {
1177                         if (ord($resln[0])<=32) {
1178                             $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($resln);
1179                         } else {
1180                             $lines[++$ln] = trim($resln);
1181                         }
1182                     }
1183                 }
1184
1185                 // Start parsing headers.  The problem is, some header "lines" take up multiple lines.
1186                 // So, we'll read ahead, and if the one we're reading now is a valid header, we'll
1187                 // process the previous line.  Otherwise, we'll keep adding the strings until we come
1188                 // to the next valid header line.
1d5165 1189
59c216 1190                 do {
A 1191                     $line = chop($this->readLine(300), "\r\n");
1192
1193                     // The preg_match below works around communigate imap, which outputs " UID <number>)".
1194                     // Without this, the while statement continues on and gets the "FH0 OK completed" message.
1d5165 1195                     // If this loop gets the ending message, then the outer loop does not receive it from radline on line 1249.
59c216 1196                     // This in causes the if statement on line 1278 to never be true, which causes the headers to end up missing
A 1197                     // If the if statement was changed to pick up the fh0 from this loop, then it causes the outer loop to spin
1198                     // An alternative might be:
1199                     // if (!preg_match("/:/",$line) && preg_match("/\)$/",$line)) break;
1200                     // however, unsure how well this would work with all imap clients.
1201                     if (preg_match("/^\s*UID [0-9]+\)$/", $line)) {
1202                         break;
1203                     }
1204
1205                     // handle FLAGS reply after headers (AOL, Zimbra?)
1206                     if (preg_match('/\s+FLAGS \((.*)\)\)$/', $line, $matches)) {
1207                         $flags_str = $matches[1];
1208                         break;
1209                     }
1210
1211                     if (ord($line[0])<=32) {
1212                         $lines[$ln] .= (empty($lines[$ln])?'':"\n").trim($line);
1213                     } else {
1214                         $lines[++$ln] = trim($line);
1215                     }
1216                 // patch from "Maksim Rubis" <siburny@hotmail.com>
1217                 } while ($line[0] != ')' && !$this->startsWith($line, $key, true));
1218
1d5165 1219                 if (strncmp($line, $key, strlen($key))) {
59c216 1220                     // process header, fill rcube_mail_header obj.
A 1221                     // initialize
1222                     if (is_array($headers)) {
1223                         reset($headers);
1224                         while (list($k, $bar) = each($headers)) {
1225                             $headers[$k] = '';
1226                         }
1227                     }
1228
1229                     // create array with header field:data
1230                     while ( list($lines_key, $str) = each($lines) ) {
1231                         list($field, $string) = $this->splitHeaderLine($str);
1d5165 1232
59c216 1233                         $field  = strtolower($field);
A 1234                         $string = preg_replace('/\n\s*/', ' ', $string);
1d5165 1235
59c216 1236                         switch ($field) {
A 1237                         case 'date';
1238                             $result[$id]->date = $string;
1239                             $result[$id]->timestamp = $this->strToTime($string);
1240                             break;
1241                         case 'from':
1242                             $result[$id]->from = $string;
1243                             break;
1244                         case 'to':
1245                             $result[$id]->to = preg_replace('/undisclosed-recipients:[;,]*/', '', $string);
1246                             break;
1247                         case 'subject':
1248                             $result[$id]->subject = $string;
1249                             break;
1250                         case 'reply-to':
1251                             $result[$id]->replyto = $string;
1252                             break;
1253                         case 'cc':
1254                             $result[$id]->cc = $string;
1255                             break;
1256                         case 'bcc':
1257                             $result[$id]->bcc = $string;
1258                             break;
1259                         case 'content-transfer-encoding':
1260                             $result[$id]->encoding = $string;
1261                             break;
1262                         case 'content-type':
1263                             $ctype_parts = preg_split('/[; ]/', $string);
1264                             $result[$id]->ctype = array_shift($ctype_parts);
1265                             if (preg_match('/charset\s*=\s*"?([a-z0-9\-\.\_]+)"?/i', $string, $regs)) {
1266                                 $result[$id]->charset = $regs[1];
1267                             }
1268                             break;
1269                         case 'in-reply-to':
1270                             $result[$id]->in_reply_to = preg_replace('/[\n<>]/', '', $string);
1271                             break;
1272                         case 'references':
1273                             $result[$id]->references = $string;
1274                             break;
1275                         case 'return-receipt-to':
1276                         case 'disposition-notification-to':
1277                         case 'x-confirm-reading-to':
1278                             $result[$id]->mdn_to = $string;
1279                             break;
1280                         case 'message-id':
1281                             $result[$id]->messageID = $string;
1282                             break;
1283                         case 'x-priority':
1284                             if (preg_match('/^(\d+)/', $string, $matches))
1285                                 $result[$id]->priority = intval($matches[1]);
1286                             break;
1287                         default:
1288                             if (strlen($field) > 2)
1289                                 $result[$id]->others[$field] = $string;
1290                             break;
1291                         } // end switch ()
1292                     } // end while ()
1293                 } else {
1294                     $a = explode(' ', $line);
1295                 }
1296
1297                 // process flags
1298                 if (!empty($flags_str)) {
1299                     $flags_str = preg_replace('/[\\\"]/', '', $flags_str);
1300                     $flags_a   = explode(' ', $flags_str);
1d5165 1301
59c216 1302                     if (is_array($flags_a)) {
A 1303                     //    reset($flags_a);
1304                         foreach($flags_a as $flag) {
1305                             $flag = strtoupper($flag);
1306                             if ($flag == 'SEEN') {
1307                                 $result[$id]->seen = true;
1308                             } else if ($flag == 'DELETED') {
1309                                 $result[$id]->deleted = true;
1310                             } else if ($flag == 'RECENT') {
1311                                 $result[$id]->recent = true;
1312                             } else if ($flag == 'ANSWERED') {
1313                                 $result[$id]->answered = true;
1314                             } else if ($flag == '$FORWARDED') {
1315                                 $result[$id]->forwarded = true;
1316                             } else if ($flag == 'DRAFT') {
1317                                 $result[$id]->is_draft = true;
1318                             } else if ($flag == '$MDNSENT') {
1319                                 $result[$id]->mdn_sent = true;
1320                             } else if ($flag == 'FLAGGED') {
1321                                      $result[$id]->flagged = true;
1322                             }
1323                         }
1324                         $result[$id]->flags = $flags_a;
1325                     }
1326                 }
1327             }
1328         } while (!$this->startsWith($line, $key, true));
1329
1330         return $result;
1331     }
1332
1333     function fetchHeader($mailbox, $id, $uidfetch=false, $bodystr=false, $add='')
1334     {
1335         $a  = $this->fetchHeaders($mailbox, $id, $uidfetch, $bodystr, $add);
1336         if (is_array($a)) {
1337             return array_shift($a);
1338         }
1339         return false;
1340     }
1341
1342     function sortHeaders($a, $field, $flag)
1343     {
1344         if (empty($field)) {
1345             $field = 'uid';
1346         }
1347         else {
1348             $field = strtolower($field);
1349         }
1350
1351         if ($field == 'date' || $field == 'internaldate') {
1352             $field = 'timestamp';
1353         }
1354         if (empty($flag)) {
1355             $flag = 'ASC';
1356         } else {
1357             $flag = strtoupper($flag);
1358         }
1359
1360         $stripArr = ($field=='subject') ? array('Re: ','Fwd: ','Fw: ','"') : array('"');
1361
1362         $c = count($a);
1363         if ($c > 0) {
1d5165 1364
59c216 1365             // Strategy:
A 1366             // First, we'll create an "index" array.
1d5165 1367             // Then, we'll use sort() on that array,
59c216 1368             // and use that to sort the main array.
1d5165 1369
59c216 1370             // create "index" array
A 1371             $index = array();
1372             reset($a);
1373             while (list($key, $val) = each($a)) {
1374                 if ($field == 'timestamp') {
1375                     $data = $this->strToTime($val->date);
1376                     if (!$data) {
1377                         $data = $val->timestamp;
1378                     }
1379                 } else {
1380                     $data = $val->$field;
1381                     if (is_string($data)) {
1382                         $data = strtoupper(str_replace($stripArr, '', $data));
1383                     }
1384                 }
1385                 $index[$key]=$data;
1386             }
1d5165 1387
59c216 1388             // sort index
A 1389             $i = 0;
1390             if ($flag == 'ASC') {
1391                 asort($index);
1392             } else {
1393                 arsort($index);
1394             }
1395
1d5165 1396             // form new array based on index
59c216 1397             $result = array();
A 1398             reset($index);
1399             while (list($key, $val) = each($index)) {
1400                 $result[$key]=$a[$key];
1401                 $i++;
1402             }
1403         }
1d5165 1404
59c216 1405         return $result;
A 1406     }
1407
1408     function expunge($mailbox, $messages=NULL)
1409     {
1410         if (!$this->select($mailbox)) {
1411             return -1;
1412         }
1d5165 1413
59c216 1414         $c = 0;
A 1415         $command = $messages ? "UID EXPUNGE $messages" : "EXPUNGE";
1416
1417         if (!$this->putLine("exp1 $command")) {
1418             return -1;
1419         }
1420
1421         do {
1422             $line = $this->readLine(100);
1423             if ($line[0] == '*') {
1424                 $c++;
1425             }
1426         } while (!$this->startsWith($line, 'exp1', true, true));
1d5165 1427
59c216 1428         if ($this->parseResult($line) == 0) {
A 1429             $this->selected = ''; // state has changed, need to reselect
1430             return $c;
1431         }
1432         $this->error = $line;
1433         return -1;
1434     }
1435
1436     function modFlag($mailbox, $messages, $flag, $mod)
1437     {
1438         if ($mod != '+' && $mod != '-') {
1439             return -1;
1440         }
1d5165 1441
59c216 1442         $flag = $this->flags[strtoupper($flag)];
1d5165 1443
59c216 1444         if (!$this->select($mailbox)) {
A 1445             return -1;
1446         }
1d5165 1447
59c216 1448         $c = 0;
A 1449         if (!$this->putLine("flg UID STORE $messages {$mod}FLAGS ($flag)")) {
1450             return false;
1451         }
1452
1453         do {
1454             $line = $this->readLine(1000);
1455             if ($line[0] == '*') {
1456                 $c++;
1457             }
1458         } while (!$this->startsWith($line, 'flg', true, true));
1459
1460         if ($this->parseResult($line) == 0) {
1461             return $c;
1462         }
1463
1464         $this->error = $line;
1465         return -1;
1466     }
1467
1468     function flag($mailbox, $messages, $flag) {
1469         return $this->modFlag($mailbox, $messages, $flag, '+');
1470     }
1471
1472     function unflag($mailbox, $messages, $flag) {
1473         return $this->modFlag($mailbox, $messages, $flag, '-');
1474     }
1475
1476     function delete($mailbox, $messages) {
1477         return $this->modFlag($mailbox, $messages, 'DELETED', '+');
1478     }
1479
1480     function copy($messages, $from, $to)
1481     {
1482         if (empty($from) || empty($to)) {
1483             return -1;
1484         }
1d5165 1485
59c216 1486         if (!$this->select($from)) {
A 1487             return -1;
1488         }
1d5165 1489
59c216 1490         $this->putLine("cpy1 UID COPY $messages \"".$this->escape($to)."\"");
A 1491         $line = $this->readReply();
1492         return $this->parseResult($line);
1493     }
1494
1495     function countUnseen($folder)
1496     {
1497         $index = $this->search($folder, 'ALL UNSEEN');
1498         if (is_array($index))
1499             return count($index);
1500         return false;
1501     }
1502
1503     // Don't be tempted to change $str to pass by reference to speed this up - it will slow it down by about
1504     // 7 times instead :-) See comments on http://uk2.php.net/references and this article:
1505     // http://derickrethans.nl/files/phparch-php-variables-article.pdf
1506     private function parseThread($str, $begin, $end, $root, $parent, $depth, &$depthmap, &$haschildren)
1507     {
1508         $node = array();
1509         if ($str[$begin] != '(') {
1510             $stop = $begin + strspn($str, "1234567890", $begin, $end - $begin);
1511             $msg = substr($str, $begin, $stop - $begin);
1512             if ($msg == 0)
1513                 return $node;
1514             if (is_null($root))
1515                 $root = $msg;
1516             $depthmap[$msg] = $depth;
1517             $haschildren[$msg] = false;
1518             if (!is_null($parent))
1519                 $haschildren[$parent] = true;
1520             if ($stop + 1 < $end)
1521                 $node[$msg] = $this->parseThread($str, $stop + 1, $end, $root, $msg, $depth + 1, $depthmap, $haschildren);
1522             else
1523                 $node[$msg] = array();
1524         } else {
1525             $off = $begin;
1526             while ($off < $end) {
1527                 $start = $off;
1528                 $off++;
1529                 $n = 1;
1530                 while ($n > 0) {
1531                     $p = strpos($str, ')', $off);
1532                     if ($p === false) {
1533                         error_log('Mismatched brackets parsing IMAP THREAD response:');
1534                         error_log(substr($str, ($begin < 10) ? 0 : ($begin - 10), $end - $begin + 20));
1535                         error_log(str_repeat(' ', $off - (($begin < 10) ? 0 : ($begin - 10))));
1536                         return $node;
1537                     }
1538                     $p1 = strpos($str, '(', $off);
1539                     if ($p1 !== false && $p1 < $p) {
1540                         $off = $p1 + 1;
1541                         $n++;
1542                     } else {
1543                         $off = $p + 1;
1544                         $n--;
1545                     }
1546                 }
1547                 $node += $this->parseThread($str, $start + 1, $off - 1, $root, $parent, $depth, $depthmap, $haschildren);
1548             }
1549         }
1d5165 1550
59c216 1551         return $node;
A 1552     }
1553
1554     function thread($folder, $algorithm='REFERENCES', $criteria='', $encoding='US-ASCII')
1555     {
1556         if (!$this->select($folder)) {
1557             return false;
1558         }
1559
1560         $encoding  = $encoding ? trim($encoding) : 'US-ASCII';
1561         $algorithm = $algorithm ? trim($algorithm) : 'REFERENCES';
1562         $criteria  = $criteria ? 'ALL '.trim($criteria) : 'ALL';
1d5165 1563
59c216 1564         if (!$this->putLineC("thrd1 THREAD $algorithm $encoding $criteria")) {
A 1565             return false;
1566         }
1567         do {
1568             $line = trim($this->readLine(10000));
1569             if (preg_match('/^\* THREAD/', $line)) {
1570                 $str         = trim(substr($line, 8));
1571                 $depthmap    = array();
1572                 $haschildren = array();
1573                 $tree = $this->parseThread($str, 0, strlen($str), null, null, 0, $depthmap, $haschildren);
1574             }
1575         } while (!$this->startsWith($line, 'thrd1', true, true));
1576
1577         $result_code = $this->parseResult($line);
1578         if ($result_code == 0) {
1579             return array($tree, $depthmap, $haschildren);
1580         }
1581
1582         $this->error = "Thread: $line";
1d5165 1583         return false;
59c216 1584     }
A 1585
6f31b3 1586     function search($folder, $criteria, $return_uid=false)
59c216 1587     {
A 1588         if (!$this->select($folder)) {
1589             return false;
1590         }
1591
1592         $data = '';
6f31b3 1593         $query = 'srch1 ' . ($return_uid ? 'UID ' : '') . 'SEARCH ' . chop($criteria);
59c216 1594
A 1595         if (!$this->putLineC($query)) {
1596             return false;
1597         }
6f31b3 1598
59c216 1599         do {
A 1600             $line = trim($this->readLine());
1601             if ($this->startsWith($line, '* SEARCH')) {
1602                 $data .= substr($line, 8);
1603             } else if (preg_match('/^[0-9 ]+$/', $line)) {
1604                 $data .= $line;
1605             }
1606         } while (!$this->startsWith($line, 'srch1', true, true));
1607
1608         $result_code = $this->parseResult($line);
1609         if ($result_code == 0) {
1610             return preg_split('/\s+/', $data, -1, PREG_SPLIT_NO_EMPTY);
1611         }
1612
1613         $this->error = "Search: $line";
1d5165 1614         return false;
59c216 1615     }
A 1616
1617     function move($messages, $from, $to)
1618     {
1619         if (!$from || !$to) {
1620             return -1;
1621         }
1d5165 1622
59c216 1623         $r = $this->copy($messages, $from, $to);
A 1624
1625         if ($r==0) {
1626             return $this->delete($from, $messages);
1627         }
1628         return $r;
1629     }
1630
1631     function listMailboxes($ref, $mailbox)
1632     {
f0485a 1633         return $this->_listMailboxes($ref, $mailbox, false);
A 1634     }
1635
1636     function listSubscribed($ref, $mailbox)
1637     {
1638         return $this->_listMailboxes($ref, $mailbox, true);
1639     }
1640
1641     private function _listMailboxes($ref, $mailbox, $subscribed=false)
1642     {
59c216 1643         if (empty($mailbox)) {
A 1644             $mailbox = '*';
1645         }
1d5165 1646
59c216 1647         if (empty($ref) && $this->rootdir) {
A 1648             $ref = $this->rootdir;
1649         }
1d5165 1650
f0485a 1651         if ($subscribed) {
A 1652             $key     = 'lsb';
1653             $command = 'LSUB';
1654         }
1655         else {
1656             $key     = 'lmb';
1657             $command = 'LIST';
1658         }
1659
59c216 1660         // send command
f0485a 1661         if (!$this->putLine($key." ".$command." \"". $this->escape($ref) ."\" \"". $this->escape($mailbox) ."\"")) {
A 1662             $this->error = "Couldn't send $command command";
59c216 1663             return false;
A 1664         }
1d5165 1665
59c216 1666         // get folder list
A 1667         do {
1668             $line = $this->readLine(500);
1669             $line = $this->multLine($line, true);
f0485a 1670             $a    = explode(' ', $line);
59c216 1671
f0485a 1672             if (($line[0] == '*') && ($a[1] == $command)) {
59c216 1673                 $line = rtrim($line);
A 1674                 // split one line
1675                 $a = rcube_explode_quoted_string(' ', $line);
1676                 // last string is folder name
f0485a 1677                 $folders[] = preg_replace(array('/^"/', '/"$/'), '', $this->unEscape($a[count($a)-1]));
59c216 1678                 // second from last is delimiter
A 1679                 $delim = trim($a[count($a)-2], '"');
1680             }
f0485a 1681         } while (!$this->startsWith($line, $key, true));
59c216 1682
A 1683         if (is_array($folders)) {
1684             return $folders;
1685         } else if ($this->parseResult($line) == 0) {
f0485a 1686             return array();
59c216 1687         }
A 1688
1689         $this->error = $line;
1690         return false;
1691     }
1692
1693     function fetchMIMEHeaders($mailbox, $id, $parts, $mime=true)
1694     {
1695         if (!$this->select($mailbox)) {
1696             return false;
1697         }
1d5165 1698
59c216 1699         $result = false;
A 1700         $parts  = (array) $parts;
1701         $key    = 'fmh0';
1702         $peeks  = '';
1703         $idx    = 0;
1704         $type   = $mime ? 'MIME' : 'HEADER';
1705
1706         // format request
1707         foreach($parts as $part)
1708             $peeks[] = "BODY.PEEK[$part.$type]";
1d5165 1709
59c216 1710         $request = "$key FETCH $id (" . implode(' ', $peeks) . ')';
A 1711
1712         // send request
1713         if (!$this->putLine($request)) {
1714             return false;
1715         }
1d5165 1716
59c216 1717         do {
A 1718             $line = $this->readLine(1000);
1719             $line = $this->multLine($line);
1720
1721             if (preg_match('/BODY\[([0-9\.]+)\.'.$type.'\]/', $line, $matches)) {
1722                 $idx = $matches[1];
1723                 $result[$idx] = preg_replace('/^(\* '.$id.' FETCH \()?\s*BODY\['.$idx.'\.'.$type.'\]\s+/', '', $line);
1724                 $result[$idx] = trim($result[$idx], '"');
1725                 $result[$idx] = rtrim($result[$idx], "\t\r\n\0\x0B");
1726             }
1727         } while (!$this->startsWith($line, $key, true));
1728
1729         return $result;
1730     }
1731
1732     function fetchPartHeader($mailbox, $id, $is_uid=false, $part=NULL)
1733     {
1734         $part = empty($part) ? 'HEADER' : $part.'.MIME';
1735
1736         return $this->handlePartBody($mailbox, $id, $is_uid, $part);
1737     }
1738
1739     function handlePartBody($mailbox, $id, $is_uid=false, $part='', $encoding=NULL, $print=NULL, $file=NULL)
1740     {
1741         if (!$this->select($mailbox)) {
1742             return false;
1743         }
1744
1745         switch ($encoding) {
1746             case 'base64':
1747                 $mode = 1;
1748             break;
1749             case 'quoted-printable':
1750                 $mode = 2;
1751             break;
1752             case 'x-uuencode':
1753             case 'x-uue':
1754             case 'uue':
1755             case 'uuencode':
1756                 $mode = 3;
1757             break;
1758             default:
1759                 $mode = 0;
1760         }
1d5165 1761
59c216 1762            $reply_key = '* ' . $id;
A 1763         $result = false;
1764
1765         // format request
1766         $key     = 'ftch0';
1767         $request = $key . ($is_uid ? ' UID' : '') . " FETCH $id (BODY.PEEK[$part])";
1768         // send request
1769         if (!$this->putLine($request)) {
1770             return false;
1771            }
1772
1773            // receive reply line
1774            do {
1775                $line = chop($this->readLine(1000));
1776                $a    = explode(' ', $line);
1777            } while (!($end = $this->startsWith($line, $key, true)) && $a[2] != 'FETCH');
1778
1779            $len = strlen($line);
1780
1781         // handle empty "* X FETCH ()" response
1782         if ($line[$len-1] == ')' && $line[$len-2] != '(') {
1783             // one line response, get everything between first and last quotes
1784             if (substr($line, -4, 3) == 'NIL') {
1785                 // NIL response
1786                 $result = '';
1787             } else {
1788                 $from = strpos($line, '"') + 1;
1789                 $to   = strrpos($line, '"');
1790                 $len  = $to - $from;
1791                 $result = substr($line, $from, $len);
1792             }
1793
1794             if ($mode == 1)
1795                 $result = base64_decode($result);
1796             else if ($mode == 2)
1797                 $result = quoted_printable_decode($result);
1798             else if ($mode == 3)
1799                 $result = convert_uudecode($result);
1800
1801         } else if ($line[$len-1] == '}') {
1802             // multi-line request, find sizes of content and receive that many bytes
1803             $from     = strpos($line, '{') + 1;
1804             $to       = strrpos($line, '}');
1805             $len      = $to - $from;
1806             $sizeStr  = substr($line, $from, $len);
1807             $bytes    = (int)$sizeStr;
1808             $prev      = '';
1d5165 1809
59c216 1810             while ($bytes > 0) {
A 1811                 $line = $this->readLine(1024);
1812                 $len  = strlen($line);
1d5165 1813
59c216 1814                 if ($len > $bytes) {
A 1815                     $line = substr($line, 0, $bytes);
1816                     $len = strlen($line);
1817                 }
1818                 $bytes -= $len;
1819
1820                 if ($mode == 1) {
1821                     $line = rtrim($line, "\t\r\n\0\x0B");
1822                     // create chunks with proper length for base64 decoding
1823                     $line = $prev.$line;
1824                     $length = strlen($line);
1825                     if ($length % 4) {
1826                         $length = floor($length / 4) * 4;
1827                         $prev = substr($line, $length);
1828                         $line = substr($line, 0, $length);
1829                     }
1830                     else
1831                         $prev = '';
1d5165 1832
59c216 1833                     if ($file)
A 1834                         fwrite($file, base64_decode($line));
1835                     else if ($print)
1836                         echo base64_decode($line);
1837                     else
1838                         $result .= base64_decode($line);
1839                 } else if ($mode == 2) {
1840                     $line = rtrim($line, "\t\r\0\x0B");
1841                     if ($file)
1842                         fwrite($file, quoted_printable_decode($line));
1843                     else if ($print)
1844                         echo quoted_printable_decode($line);
1845                     else
1846                         $result .= quoted_printable_decode($line);
1847                 } else if ($mode == 3) {
1848                     $line = rtrim($line, "\t\r\n\0\x0B");
1849                     if ($line == 'end' || preg_match('/^begin\s+[0-7]+\s+.+$/', $line))
1850                         continue;
1851                     if ($file)
1852                         fwrite($file, convert_uudecode($line));
1853                     else if ($print)
1854                         echo convert_uudecode($line);
1855                     else
1856                         $result .= convert_uudecode($line);
1857                 } else {
1858                     $line = rtrim($line, "\t\r\n\0\x0B");
1859                     if ($file)
1860                         fwrite($file, $line . "\n");
1861                     else if ($print)
1862                         echo $line . "\n";
1863                     else
1864                         $result .= $line . "\n";
1865                 }
1866             }
1867         }
1d5165 1868
59c216 1869         // read in anything up until last line
A 1870         if (!$end)
1871             do {
1872                     $line = $this->readLine(1024);
1873             } while (!$this->startsWith($line, $key, true));
1874
1875            if ($result) {
1876             if ($file) {
1877                 fwrite($file, $result);
1878                } else if ($print) {
1879                 echo $result;
1880             } else
1881                 return $result;
1882                return true;
1883            }
1884
1885         return false;
1886     }
1887
1888     function createFolder($folder)
1889     {
1890         if ($this->putLine('c CREATE "' . $this->escape($folder) . '"')) {
1891             do {
1892                 $line = $this->readLine(300);
1893             } while (!$this->startsWith($line, 'c ', true, true));
1894             return ($this->parseResult($line) == 0);
1895         }
1896         return false;
1897     }
1898
1899     function renameFolder($from, $to)
1900     {
1901         if ($this->putLine('r RENAME "' . $this->escape($from) . '" "' . $this->escape($to) . '"')) {
1902             do {
1903                 $line = $this->readLine(300);
1904             } while (!$this->startsWith($line, 'r ', true, true));
1905             return ($this->parseResult($line) == 0);
1906         }
1907         return false;
1908     }
1909
1910     function deleteFolder($folder)
1911     {
1912         if ($this->putLine('d DELETE "' . $this->escape($folder). '"')) {
1913             do {
1914                 $line = $this->readLine(300);
1915             } while (!$this->startsWith($line, 'd ', true, true));
1916             return ($this->parseResult($line) == 0);
1917         }
1918         return false;
1919     }
1920
1921     function clearFolder($folder)
1922     {
1923         $num_in_trash = $this->countMessages($folder);
1924         if ($num_in_trash > 0) {
1925             $this->delete($folder, '1:*');
1926         }
1927         return ($this->expunge($folder) >= 0);
1928     }
1929
1930     function subscribe($folder)
1931     {
1932         $query = 'sub1 SUBSCRIBE "' . $this->escape($folder). '"';
1933         $this->putLine($query);
1934
1935         $line = trim($this->readLine(512));
1936         return ($this->parseResult($line) == 0);
1937     }
1938
1939     function unsubscribe($folder)
1940     {
1941         $query = 'usub1 UNSUBSCRIBE "' . $this->escape($folder) . '"';
1942         $this->putLine($query);
1d5165 1943
59c216 1944         $line = trim($this->readLine(512));
A 1945         return ($this->parseResult($line) == 0);
1946     }
1947
1948     function append($folder, &$message)
1949     {
1950         if (!$folder) {
1951             return false;
1952         }
1953
1954         $message = str_replace("\r", '', $message);
1955         $message = str_replace("\n", "\r\n", $message);
1956
1957         $len = strlen($message);
1958         if (!$len) {
1959             return false;
1960         }
1961
1962         $request = 'a APPEND "' . $this->escape($folder) .'" (\\Seen) {' . $len . '}';
1963
1964         if ($this->putLine($request)) {
1965             $line = $this->readLine(512);
1966
1967             if ($line[0] != '+') {
1968                 // $errornum = $this->parseResult($line);
1969                 $this->error = "Cannot write to folder: $line";
1970                 return false;
1971             }
1972
1973             if (!$this->putLine($message)) {
1974                 return false;
1975             }
1976
1977             do {
1978                 $line = $this->readLine();
1979             } while (!$this->startsWith($line, 'a ', true, true));
1d5165 1980
59c216 1981             $result = ($this->parseResult($line) == 0);
A 1982             if (!$result) {
1983                 $this->error = $line;
1984             }
1985             return $result;
1986         }
1987
1988         $this->error = "Couldn't send command \"$request\"";
1989         return false;
1990     }
1991
1992     function appendFromFile($folder, $path, $headers=null, $separator="\n\n")
1993     {
1994         if (!$folder) {
1995             return false;
1996         }
1d5165 1997
59c216 1998         // open message file
A 1999         $in_fp = false;
2000         if (file_exists(realpath($path))) {
2001             $in_fp = fopen($path, 'r');
2002         }
1d5165 2003         if (!$in_fp) {
59c216 2004             $this->error = "Couldn't open $path for reading";
A 2005             return false;
2006         }
1d5165 2007
59c216 2008         $len = filesize($path);
A 2009         if (!$len) {
2010             return false;
2011         }
2012
2013         if ($headers) {
2014             $headers = preg_replace('/[\r\n]+$/', '', $headers);
2015             $len += strlen($headers) + strlen($separator);
2016         }
2017
2018         // send APPEND command
2019         $request    = 'a APPEND "' . $this->escape($folder) . '" (\\Seen) {' . $len . '}';
2020         if ($this->putLine($request)) {
2021             $line = $this->readLine(512);
2022
2023             if ($line[0] != '+') {
2024                 //$errornum = $this->parseResult($line);
2025                 $this->error = "Cannot write to folder: $line";
2026                 return false;
2027             }
2028
2029             // send headers with body separator
2030             if ($headers) {
2031                 $this->putLine($headers . $separator, false);
2032             }
2033
2034             // send file
2035             while (!feof($in_fp) && $this->fp) {
2036                 $buffer = fgets($in_fp, 4096);
2037                 $this->putLine($buffer, false);
2038             }
2039             fclose($in_fp);
2040
2041             if (!$this->putLine('')) { // \r\n
2042                 return false;
2043             }
2044
2045             // read response
2046             do {
2047                 $line = $this->readLine();
2048             } while (!$this->startsWith($line, 'a ', true, true));
2049
2050             $result = ($this->parseResult($line) == 0);
2051             if (!$result) {
2052                 $this->error = $line;
2053             }
2054
2055             return $result;
2056         }
1d5165 2057
59c216 2058         $this->error = "Couldn't send command \"$request\"";
A 2059         return false;
2060     }
2061
2062     function fetchStructureString($folder, $id, $is_uid=false)
2063     {
2064         if (!$this->select($folder)) {
2065             return false;
2066         }
2067
2068         $key = 'F1247';
2069         $result = false;
2070
2071         if ($this->putLine($key . ($is_uid ? ' UID' : '') ." FETCH $id (BODYSTRUCTURE)")) {
2072             do {
2073                 $line = $this->readLine(5000);
2074                 $line = $this->multLine($line, true);
2075                 if (!preg_match("/^$key/", $line))
2076                     $result .= $line;
2077             } while (!$this->startsWith($line, $key, true, true));
2078
2079             $result = trim(substr($result, strpos($result, 'BODYSTRUCTURE')+13, -1));
2080         }
2081
2082         return $result;
2083     }
2084
2085     function getQuota()
2086     {
2087         /*
2088          * GETQUOTAROOT "INBOX"
2089          * QUOTAROOT INBOX user/rchijiiwa1
2090          * QUOTA user/rchijiiwa1 (STORAGE 654 9765)
2091          * OK Completed
2092          */
2093         $result      = false;
2094         $quota_lines = array();
1d5165 2095
59c216 2096         // get line(s) containing quota info
A 2097         if ($this->putLine('QUOT1 GETQUOTAROOT "INBOX"')) {
2098             do {
2099                 $line = chop($this->readLine(5000));
2100                 if ($this->startsWith($line, '* QUOTA ')) {
2101                     $quota_lines[] = $line;
2102                 }
2103             } while (!$this->startsWith($line, 'QUOT1', true, true));
2104         }
1d5165 2105
59c216 2106         // return false if not found, parse if found
A 2107         $min_free = PHP_INT_MAX;
2108         foreach ($quota_lines as $key => $quota_line) {
2109             $quota_line   = preg_replace('/[()]/', '', $quota_line);
2110             $parts        = explode(' ', $quota_line);
2111             $storage_part = array_search('STORAGE', $parts);
1d5165 2112
59c216 2113             if (!$storage_part)
A 2114                 continue;
1d5165 2115
59c216 2116             $used  = intval($parts[$storage_part+1]);
A 2117             $total = intval($parts[$storage_part+2]);
1d5165 2118             $free  = $total - $used;
A 2119
59c216 2120             // return lowest available space from all quotas
1d5165 2121             if ($free < $min_free) {
A 2122                 $min_free          = $free;
59c216 2123                 $result['used']    = $used;
A 2124                 $result['total']   = $total;
2125                 $result['percent'] = min(100, round(($used/max(1,$total))*100));
2126                 $result['free']    = 100 - $result['percent'];
2127             }
2128         }
2129
2130         return $result;
2131     }
2132
6f31b3 2133     private function _xor($string, $string2)
59c216 2134     {
A 2135         $result = '';
2136         $size = strlen($string);
2137         for ($i=0; $i<$size; $i++) {
2138             $result .= chr(ord($string[$i]) ^ ord($string2[$i]));
2139         }
2140         return $result;
2141     }
2142
2143     private function strToTime($date)
2144     {
2145         // support non-standard "GMTXXXX" literal
2146         $date = preg_replace('/GMT\s*([+-][0-9]+)/', '\\1', $date);
2147         // if date parsing fails, we have a date in non-rfc format.
2148         // remove token from the end and try again
2149         while ((($ts = @strtotime($date))===false) || ($ts < 0)) {
2150             $d = explode(' ', $date);
2151             array_pop($d);
2152             if (!$d) break;
2153             $date = implode(' ', $d);
2154         }
2155
2156         $ts = (int) $ts;
2157
1d5165 2158         return $ts < 0 ? 0 : $ts;
59c216 2159     }
A 2160
2161     private function SplitHeaderLine($string)
2162     {
2163         $pos = strpos($string, ':');
2164         if ($pos>0) {
2165             $res[0] = substr($string, 0, $pos);
2166             $res[1] = trim(substr($string, $pos+1));
2167             return $res;
2168         }
2169         return $string;
2170     }
2171
2172     private function parseNamespace($str, &$i, $len=0, $l)
2173     {
2174         if (!$l) {
2175             $str = str_replace('NIL', '()', $str);
2176         }
2177         if (!$len) {
2178             $len = strlen($str);
2179         }
2180         $data      = array();
2181         $in_quotes = false;
2182         $elem      = 0;
1d5165 2183
59c216 2184         for ($i;$i<$len;$i++) {
A 2185             $c = (string)$str[$i];
2186             if ($c == '(' && !$in_quotes) {
2187                 $i++;
2188                 $data[$elem] = $this->parseNamespace($str, $i, $len, $l++);
2189                 $elem++;
2190             } else if ($c == ')' && !$in_quotes) {
2191                 return $data;
2192             } else if ($c == '\\') {
2193                 $i++;
2194                 if ($in_quotes) {
2195                     $data[$elem] .= $c.$str[$i];
2196                 }
2197             } else if ($c == '"') {
2198                 $in_quotes = !$in_quotes;
2199                 if (!$in_quotes) {
2200                     $elem++;
2201                 }
2202             } else if ($in_quotes) {
2203                 $data[$elem].=$c;
2204             }
2205         }
1d5165 2206
59c216 2207         return $data;
A 2208     }
2209
2210     private function escape($string)
2211     {
1d5165 2212         return strtr($string, array('"'=>'\\"', '\\' => '\\\\'));
59c216 2213     }
A 2214
2215     private function unEscape($string)
2216     {
1d5165 2217         return strtr($string, array('\\"'=>'"', '\\\\' => '\\'));
59c216 2218     }
A 2219
2220 }
2221
2222 ?>