request LIST calls / mailbox and STATUS info by using pipelined imap-calls.
[squirrelmail.git] / functions / imap_mailbox.php
1 <?php
2
3 /**
4 * imap_mailbox.php
5 *
6 * Copyright (c) 1999-2003 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
8 *
9 * This impliments all functions that manipulate mailboxes
10 *
11 * $Id$
12 */
13 require_once(SM_PATH . 'functions/imap_utf7_local.php');
14
15 global $boxesnew;
16
17 class mailboxes {
18 var $mailboxname_full = '', $mailboxname_sub= '', $is_noselect = false,
19 $is_special = false, $is_root = false, $is_inbox = false, $is_sent = false,
20 $is_trash = false, $is_draft = false, $mbxs = array(),
21 $unseen = false, $total = false;
22
23 function addMbx($mbx, $delimiter, $start, $specialfirst) {
24 $ary = explode($delimiter, $mbx->mailboxname_full);
25 $mbx_parent =& $this;
26 for ($i = $start, $c = count($ary)-1; $i < $c; $i++) {
27 $mbx_childs =& $mbx_parent->mbxs;
28 $found = false;
29 if ($mbx_childs) {
30 foreach ($mbx_childs as $key => $parent) {
31 if ($parent->mailboxname_sub == $ary[$i]) {
32 $mbx_parent =& $mbx_parent->mbxs[$key];
33 $found = true;
34 break;
35 }
36 }
37 }
38 if (!$found) {
39 $no_select_mbx = new mailboxes();
40 if (isset($mbx_parent->mailboxname_full) && $mbx_parent->mailboxname_full != '') {
41 $no_select_mbx->mailboxname_full = $mbx_parent->mailboxname_full.$delimiter.$ary[$i];
42 } else {
43 $no_select_mbx->mailboxname_full = $ary[$i];
44 }
45 $no_select_mbx->mailboxname_sub = $ary[$i];
46 $no_select_mbx->is_noselect = true;
47 $mbx_parent->mbxs[] = $no_select_mbx;
48 $i--;
49 }
50 }
51 $mbx_parent->mbxs[] = $mbx;
52 if ($mbx->is_special && $specialfirst) {
53 usort($mbx_parent->mbxs, 'sortSpecialMbx');
54 }
55 }
56 }
57
58 function sortSpecialMbx($a, $b) {
59 if ($a->is_inbox) {
60 $acmp = '0'. $a->mailboxname_full;
61 } else if ($a->is_special) {
62 $acmp = '1'. $a->mailboxname_full;
63 } else {
64 $acmp = '2' . $a->mailboxname_full;
65 }
66 if ($b->is_inbox) {
67 $bcmp = '0'. $b->mailboxname_full;
68 }else if ($b->is_special) {
69 $bcmp = '1' . $b->mailboxname_full;
70 } else {
71 $bcmp = '2' . $b->mailboxname_full;
72 }
73 if ($acmp == $bcmp) return 0;
74 return ($acmp > $bcmp) ? 1: -1;
75 }
76
77 function find_mailbox_name ($mailbox) {
78 if (preg_match('/\*.+\"([^\r\n\"]*)\"[\s\r\n]*$/', $mailbox, $regs))
79 return $regs[1];
80 if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
81 return $regs[1];
82 ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
83 return $regs[1];
84 }
85
86 function check_is_noselect ($lsub_line) {
87 return preg_match("/^\* (LSUB|LIST) \([^\)]*\\Noselect[^\)]*\)/i", $lsub_line);
88 }
89
90 /**
91 * If $haystack is a full mailbox name, and $needle is the mailbox
92 * separator character, returns the second last part of the full
93 * mailbox name (i.e. the mailbox's parent mailbox)
94 */
95 function readMailboxParent($haystack, $needle) {
96 if ($needle == '') {
97 $ret = '';
98 } else {
99 $parts = explode($needle, $haystack);
100 $elem = array_pop($parts);
101 while ($elem == '' && count($parts)) {
102 $elem = array_pop($parts);
103 }
104 $ret = join($needle, $parts);
105 }
106 return( $ret );
107 }
108
109 /**
110 * Check if $subbox is below the specified $parentbox
111 */
112 function isBoxBelow( $subbox, $parentbox ) {
113 global $delimiter;
114 /*
115 * Eliminate the obvious mismatch, where the
116 * subfolder path is shorter than that of the potential parent
117 */
118 if ( strlen($subbox) < strlen($parentbox) ) {
119 return false;
120 }
121 /* check for delimiter */
122 if (!substr($parentbox,-1) == $delimiter) {
123 $parentbox.=$delimiter;
124 }
125 if (substr($subbox,0,strlen($parentbox)) == $parentbox) {
126 return true;
127 } else {
128 return false;
129 }
130 }
131
132 /* Defines special mailboxes */
133 function isSpecialMailbox( $box ) {
134 global $trash_folder, $sent_folder, $draft_folder,
135 $move_to_trash, $move_to_sent, $save_as_draft;
136
137 $ret = ( (strtolower($box) == 'inbox') ||
138 isTrashMailbox($box) || isSentMailbox($box) || isDraftMailbox($box) );
139
140 if ( !$ret ) {
141 $ret = do_hook_function( 'special_mailbox', $box );
142 }
143 return $ret;
144 }
145
146 function isTrashMailbox ($box) {
147 global $trash_folder, $move_to_trash;
148 return $move_to_trash && $trash_folder &&
149 ( $box == $trash_folder || isBoxBelow($box, $trash_folder) );
150 }
151
152 function isSentMailbox($box) {
153 global $sent_folder, $move_to_sent;
154 return $move_to_sent && $sent_folder &&
155 ( $box == $sent_folder || isBoxBelow($box, $sent_folder) );
156 }
157
158 function isDraftMailbox($box) {
159 global $draft_folder, $save_as_draft;
160 return $save_as_draft &&
161 ( $box == $draft_folder || isBoxBelow($box, $draft_folder) );
162 }
163
164 /* Expunges a mailbox */
165 function sqimap_mailbox_expunge ($imap_stream, $mailbox, $handle_errors = true, $id='') {
166 global $uid_support;
167 if ($id) {
168 if (is_array($id)) {
169 $id = sqimap_message_list_squisher($id);
170 }
171 $id = ' '.$id;
172 $uid = $uid_support;
173 } else {
174 $uid = false;
175 }
176 $read = sqimap_run_command($imap_stream, 'EXPUNGE'.$id, $handle_errors,
177 $response, $message, $uid);
178 $cnt = 0;
179
180 if (is_array($read)) {
181 foreach ($read as $r) {
182 if (preg_match('/^\*\s[0-9]+\sEXPUNGE/AUi',$r,$regs)) {
183 $cnt++;
184 }
185 }
186 }
187 return $cnt;
188 }
189
190 /* Checks whether or not the specified mailbox exists */
191 function sqimap_mailbox_exists ($imap_stream, $mailbox) {
192 if (!isset($mailbox) || empty($mailbox)) {
193 return false;
194 }
195 $mbx = sqimap_run_command($imap_stream, "LIST \"\" \"$mailbox\"",
196 true, $response, $message);
197 return isset($mbx[0]);
198 }
199
200 /* Selects a mailbox */
201 function sqimap_mailbox_select ($imap_stream, $mailbox) {
202 global $auto_expunge;
203
204 if ($mailbox == 'None') {
205 return;
206 }
207
208 $read = sqimap_run_command($imap_stream, "SELECT \"$mailbox\"",
209 true, $response, $message);
210 $result = array();
211 for ($i = 0, $cnt = count($read); $i < $cnt; $i++) {
212 if (preg_match('/^\*\s+OK\s\[(\w+)\s(\w+)\]/',$read[$i], $regs)) {
213 $result[strtoupper($regs[1])] = $regs[2];
214 } else if (preg_match('/^\*\s([0-9]+)\s(\w+)/',$read[$i], $regs)) {
215 $result[strtoupper($regs[2])] = $regs[1];
216 } else {
217 if (preg_match("/PERMANENTFLAGS(.*)/i",$read[$i], $regs)) {
218 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/","/\]/") ,'', $regs[1])) ;
219 $result['PERMANENTFLAGS'] = $regs[1];
220 } else if (preg_match("/FLAGS(.*)/i",$read[$i], $regs)) {
221 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/") ,'', $regs[1])) ;
222 $result['FLAGS'] = $regs[1];
223 }
224 }
225 }
226 if (preg_match('/^\[(.+)\]/',$message, $regs)) {
227 $result['RIGHTS']=$regs[1];
228 }
229
230 if ($auto_expunge) {
231 $tmp = sqimap_run_command($imap_stream, 'EXPUNGE', false, $a, $b);
232 }
233 return $result;
234 }
235
236 /* Creates a folder */
237 function sqimap_mailbox_create ($imap_stream, $mailbox, $type) {
238 global $delimiter;
239 if (strtolower($type) == 'noselect') {
240 $mailbox .= $delimiter;
241 }
242
243 $read_ary = sqimap_run_command($imap_stream, "CREATE \"$mailbox\"",
244 true, $response, $message);
245 sqimap_subscribe ($imap_stream, $mailbox);
246 }
247
248 /* Subscribes to an existing folder */
249 function sqimap_subscribe ($imap_stream, $mailbox) {
250 $read_ary = sqimap_run_command($imap_stream, "SUBSCRIBE \"$mailbox\"",
251 true, $response, $message);
252 }
253
254 /* Unsubscribes to an existing folder */
255 function sqimap_unsubscribe ($imap_stream, $mailbox) {
256 $read_ary = sqimap_run_command($imap_stream, "UNSUBSCRIBE \"$mailbox\"",
257 true, $response, $message);
258 }
259
260 /* Deletes the given folder */
261 function sqimap_mailbox_delete ($imap_stream, $mailbox) {
262 global $data_dir, $username;
263 $read_ary = sqimap_run_command($imap_stream, "DELETE \"$mailbox\"",
264 true, $response, $message);
265 sqimap_unsubscribe ($imap_stream, $mailbox);
266 do_hook_function('rename_or_delete_folder', $args = array($mailbox, 'delete', ''));
267 removePref($data_dir, $username, "thread_$mailbox");
268 }
269
270 /* Determines if the user is subscribed to the folder or not */
271 function sqimap_mailbox_is_subscribed($imap_stream, $folder) {
272 $boxesall = sqimap_mailbox_list ($imap_stream);
273 foreach ($boxesall as $ref) {
274 if ($ref['unformatted'] == $folder) {
275 return true;
276 }
277 }
278 return false;
279 }
280
281 /* Renames a mailbox */
282 function sqimap_mailbox_rename( $imap_stream, $old_name, $new_name ) {
283 if ( $old_name != $new_name ) {
284 global $delimiter, $imap_server_type, $data_dir, $username;
285 if ( substr( $old_name, -1 ) == $delimiter ) {
286 $old_name = substr( $old_name, 0, strlen( $old_name ) - 1 );
287 $new_name = substr( $new_name, 0, strlen( $new_name ) - 1 );
288 $postfix = $delimiter;
289 } else {
290 $postfix = '';
291 }
292
293 $boxesall = sqimap_mailbox_list($imap_stream);
294 $cmd = 'RENAME "' . $old_name . '" "' . $new_name . '"';
295 $data = sqimap_run_command($imap_stream, $cmd, true, $response, $message);
296 sqimap_unsubscribe($imap_stream, $old_name.$postfix);
297 $oldpref = getPref($data_dir, $username, 'thread_'.$old_name.$postfix);
298 removePref($data_dir, $username, 'thread_'.$old_name.$postfix);
299 sqimap_subscribe($imap_stream, $new_name.$postfix);
300 setPref($data_dir, $username, 'thread_'.$new_name.$postfix, $oldpref);
301 do_hook_function('rename_or_delete_folder',$args = array($old_name, 'rename', $new_name));
302 $l = strlen( $old_name ) + 1;
303 $p = 'unformatted';
304
305 foreach ($boxesall as $box) {
306 if (substr($box[$p], 0, $l) == $old_name . $delimiter) {
307 $new_sub = $new_name . $delimiter . substr($box[$p], $l);
308 if ($imap_server_type == 'cyrus') {
309 $cmd = 'RENAME "' . $box[$p] . '" "' . $new_sub . '"';
310 $data = sqimap_run_command($imap_stream, $cmd, true,
311 $response, $message);
312 }
313 sqimap_unsubscribe($imap_stream, $box[$p]);
314 $oldpref = getPref($data_dir, $username, 'thread_'.$box[$p]);
315 removePref($data_dir, $username, 'thread_'.$box[$p]);
316 sqimap_subscribe($imap_stream, $new_sub);
317 setPref($data_dir, $username, 'thread_'.$new_sub, $oldpref);
318 do_hook_function('rename_or_delete_folder',
319 $args = array($box[$p], 'rename', $new_sub));
320 }
321 }
322 }
323 }
324
325 /*
326 * Formats a mailbox into 4 parts for the $boxesall array
327 *
328 * The four parts are:
329 *
330 * raw - Raw LIST/LSUB response from the IMAP server
331 * formatted - nicely formatted folder name
332 * unformatted - unformatted, but with delimiter at end removed
333 * unformatted-dm - folder name as it appears in raw response
334 * unformatted-disp - unformatted without $folder_prefix
335 */
336 function sqimap_mailbox_parse ($line, $line_lsub) {
337 global $folder_prefix, $delimiter;
338
339 /* Process each folder line */
340 for ($g = 0, $cnt = count($line); $g < $cnt; ++$g) {
341 /* Store the raw IMAP reply */
342 if (isset($line[$g])) {
343 $boxesall[$g]['raw'] = $line[$g];
344 } else {
345 $boxesall[$g]['raw'] = '';
346 }
347
348 /* Count number of delimiters ($delimiter) in folder name */
349 $mailbox = trim($line_lsub[$g]);
350 $dm_count = substr_count($mailbox, $delimiter);
351 if (substr($mailbox, -1) == $delimiter) {
352 /* If name ends in delimiter, decrement count by one */
353 $dm_count--;
354 }
355
356 /* Format folder name, but only if it's a INBOX.* or has a parent. */
357 $boxesallbyname[$mailbox] = $g;
358 $parentfolder = readMailboxParent($mailbox, $delimiter);
359 if ( (strtolower(substr($mailbox, 0, 5)) == "inbox") ||
360 (substr($mailbox, 0, strlen($folder_prefix)) == $folder_prefix) ||
361 (isset($boxesallbyname[$parentfolder]) &&
362 (strlen($parentfolder) > 0) ) ) {
363 $indent = $dm_count - (substr_count($folder_prefix, $delimiter));
364 if ($indent > 0) {
365 $boxesall[$g]['formatted'] = str_repeat('&nbsp;&nbsp;', $indent);
366 } else {
367 $boxesall[$g]['formatted'] = '';
368 }
369 $boxesall[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
370 } else {
371 $boxesall[$g]['formatted'] = imap_utf7_decode_local($mailbox);
372 }
373
374 $boxesall[$g]['unformatted-dm'] = $mailbox;
375 if (substr($mailbox, -1) == $delimiter) {
376 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
377 }
378 $boxesall[$g]['unformatted'] = $mailbox;
379 if (substr($mailbox,0,strlen($folder_prefix))==$folder_prefix) {
380 $mailbox = substr($mailbox, strlen($folder_prefix));
381 }
382 $boxesall[$g]['unformatted-disp'] = $mailbox;
383 $boxesall[$g]['id'] = $g;
384
385 $boxesall[$g]['flags'] = array();
386 if (isset($line[$g])) {
387 ereg("\(([^)]*)\)",$line[$g],$regs);
388 // FIXME Flags do contain the \ character. \NoSelect \NoInferiors
389 // and $MDNSent <= last one doesn't have the \
390 // It's better to follow RFC3501 instead of using our own naming.
391 $flags = trim(strtolower(str_replace('\\', '',$regs[1])));
392 if ($flags) {
393 $boxesall[$g]['flags'] = explode(' ', $flags);
394 }
395 }
396 }
397 return $boxesall;
398 }
399
400 /*
401 * Sorting function used to sort mailbox names.
402 * + Original patch from dave_michmerhuizen@yahoo.com
403 * + Allows case insensitivity when sorting folders
404 * + Takes care of the delimiter being sorted to the end, causing
405 * subfolders to be listed in below folders that are prefixed
406 * with their parent folders name.
407 *
408 * For example: INBOX.foo, INBOX.foobar, and INBOX.foo.bar
409 * Without special sort function: foobar between foo and foo.bar
410 * With special sort function: foobar AFTER foo and foo.bar :)
411 */
412 function user_strcasecmp($a, $b) {
413 return strnatcasecmp($a, $b);
414 }
415
416 /*
417 * Returns list of options (to be echoed into select statement
418 * based on available mailboxes and separators
419 * Caller should surround options with <SELECT..> </SELECT> and
420 * any formatting.
421 * $imap_stream - $imapConnection to query for mailboxes
422 * $show_selected - array containing list of mailboxes to pre-select (0 if none)
423 * $folder_skip - array of folders to keep out of option list (compared in lower)
424 * $boxes - list of already fetched boxes (for places like folder panel, where
425 * you know these options will be shown 3 times in a row.. (most often unset).
426 * $flag - flag to check for in mailbox flags, used to filter out mailboxes.
427 * 'noselect' by default to remove unselectable mailboxes.
428 * 'noinferiors' used to filter out folders that can not contain subfolders.
429 * NULL to avoid flag check entirely.
430 * NOTE: noselect and noiferiors are used internally. The IMAP representation is
431 * \NoSelect and \NoInferiors
432 * $use_long_format - override folder display preference and always show full folder name.
433 */
434 function sqimap_mailbox_option_list($imap_stream, $show_selected = 0, $folder_skip = 0, $boxes = 0,
435 $flag = 'noselect', $use_long_format = false ) {
436 global $username, $data_dir;
437 $mbox_options = '';
438 if ( $use_long_format ) {
439 $shorten_box_names = 0;
440 } else {
441 $shorten_box_names = getPref($data_dir, $username, 'mailbox_select_style', SMPREF_OFF);
442 }
443
444 if ($boxes == 0) {
445 $boxes = sqimap_mailbox_list($imap_stream);
446 }
447
448 foreach ($boxes as $boxes_part) {
449 if ($flag == NULL || !in_array($flag, $boxes_part['flags'])) {
450 $box = $boxes_part['unformatted'];
451
452 if ($folder_skip != 0 && in_array($box, $folder_skip) ) {
453 continue;
454 }
455 $lowerbox = strtolower($box);
456 // mailboxes are casesensitive => inbox.sent != inbox.Sent
457 // nevermind, to many dependencies this should be fixed!
458
459 if (strtolower($box) == 'inbox') { // inbox is special and not casesensitive
460 $box2 = _("INBOX");
461 } else {
462 switch ($shorten_box_names)
463 {
464 case 2: /* delimited, style = 2 */
465 $box2 = str_replace('&nbsp;&nbsp;', '.&nbsp;', $boxes_part['formatted']);
466 break;
467 case 1: /* indent, style = 1 */
468 $box2 = $boxes_part['formatted'];
469 break;
470 default: /* default, long names, style = 0 */
471 $box2 = str_replace(' ', '&nbsp;', imap_utf7_decode_local($boxes_part['unformatted-disp']));
472 break;
473 }
474 }
475 if ($show_selected != 0 && in_array($lowerbox, $show_selected) ) {
476 $mbox_options .= '<OPTION VALUE="'.$box.'" SELECTED>'.$box2.'</OPTION>' . "\n";
477 } else {
478 $mbox_options .= '<OPTION VALUE="'.$box.'">'.$box2.'</OPTION>' . "\n";
479 }
480 }
481 }
482 return $mbox_options;
483 }
484
485 /*
486 * Returns sorted mailbox lists in several different ways.
487 * See comment on sqimap_mailbox_parse() for info about the returned array.
488 */
489 function sqimap_mailbox_list($imap_stream) {
490 global $default_folder_prefix;
491
492 if (!isset($boxesnew)) {
493 global $data_dir, $username, $list_special_folders_first,
494 $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
495 $move_to_trash, $move_to_sent, $save_as_draft,
496 $delimiter, $noselect_fix_enable;
497
498 $inbox_in_list = false;
499 $inbox_subscribed = false;
500
501 require_once(SM_PATH . 'include/load_prefs.php');
502
503 if ($noselect_fix_enable) {
504 $lsub_args = "LSUB \"$folder_prefix\" \"*%\"";
505 } else {
506 $lsub_args = "LSUB \"$folder_prefix\" \"*\"";
507 }
508 /* LSUB array */
509 $lsub_ary = sqimap_run_command ($imap_stream, $lsub_args,
510 true, $response, $message);
511
512 $sorted_lsub_ary = array();
513 for ($i = 0, $cnt = count($lsub_ary);$i < $cnt; $i++) {
514 /*
515 * Workaround for mailboxes returned as literal
516 * Doesn't work if the mailbox name is multiple lines
517 * (larger then fgets buffer)
518 */
519 if (isset($lsub_ary[$i + 1]) && substr($lsub_ary[$i],-3) == "}\r\n") {
520 if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)$",
521 $lsub_ary[$i], $regs)) {
522 $i++;
523 $lsub_ary[$i] = $regs[1] . '"' . addslashes(trim($lsub_ary[$i])) . '"' . $regs[2];
524 }
525 }
526 $temp_mailbox_name = find_mailbox_name($lsub_ary[$i]);
527 $sorted_lsub_ary[] = $temp_mailbox_name;
528 if (!$inbox_subscribed && strtoupper($temp_mailbox_name) == 'INBOX') {
529 $inbox_subscribed = true;
530 }
531 }
532 /* remove duplicates */
533 $sorted_lsub_ary = array_unique($sorted_lsub_ary);
534
535 /* natural sort mailboxes */
536 if (isset($sorted_lsub_ary)) {
537 usort($sorted_lsub_ary, 'user_strcasecmp');
538 }
539 /*
540 * The LSUB response doesn't provide us information about \Noselect
541 * mail boxes. The LIST response does, that's why we need to do a LIST
542 * call to retrieve the flags for the mailbox
543 * Note: according RFC2060 an imap server may provide \NoSelect flags in the LSUB response.
544 * in other words, we cannot rely on it.
545 */
546 $sorted_list_ary = array();
547 for ($i=0; $i < count($sorted_lsub_ary); $i++) {
548 if (substr($sorted_lsub_ary[$i], -1) == $delimiter) {
549 $mbx = substr($sorted_lsub_ary[$i], 0, strlen($sorted_lsub_ary[$i])-1);
550 }
551 else {
552 $mbx = $sorted_lsub_ary[$i];
553 }
554
555 $read = sqimap_run_command ($imap_stream, "LIST \"\" \"$mbx\"",
556 true, $response, $message);
557
558 /* Another workaround for literals */
559
560 if (isset($read[1]) && substr($read[1],-3) == "}\r\n") {
561 if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)$",
562 $read[0], $regs)) {
563 $read[0] = $regs[1] . '"' . addslashes(trim($read[1])) . '"' . $regs[2];
564 }
565 }
566
567 if (isset($read[0])) {
568 $sorted_list_ary[$i] = $read[0];
569 } else {
570 $sorted_list_ary[$i] = '';
571 }
572 }
573
574 /*
575 * Just in case they're not subscribed to their inbox,
576 * we'll get it for them anyway
577 */
578 if (!$inbox_subscribed) {
579 $inbox_ary = sqimap_run_command ($imap_stream, "LIST \"\" \"INBOX\"",
580 true, $response, $message);
581 /* Another workaround for literals */
582 if (isset($inbox_ary[1]) && substr($inbox_ary[0],-3) == "}\r\n") {
583 if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)$",
584 $inbox_ary[0], $regs)) {
585 $inbox_ary[0] = $regs[1] . '"' . addslashes(trim($inbox_ary[1])) .
586 '"' . $regs[2];
587 }
588 }
589 $sorted_list_ary[] = $inbox_ary[0];
590 $sorted_lsub_ary[] = find_mailbox_name($inbox_ary[0]);
591 }
592
593 $boxesall = sqimap_mailbox_parse ($sorted_list_ary, $sorted_lsub_ary);
594
595 /* Now, lets sort for special folders */
596 $boxesnew = $used = array();
597
598 /* Find INBOX */
599 $cnt = count($boxesall);
600 $used = array_pad($used,$cnt,false);
601 for($k = 0; $k < $cnt; ++$k) {
602 if (strtolower($boxesall[$k]['unformatted']) == 'inbox') {
603 $boxesnew[] = $boxesall[$k];
604 $used[$k] = true;
605 break;
606 }
607 }
608 /* List special folders and their subfolders, if requested. */
609 if ($list_special_folders_first) {
610 for($k = 0; $k < $cnt; ++$k) {
611 if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
612 $boxesnew[] = $boxesall[$k];
613 $used[$k] = true;
614 }
615 }
616 }
617
618 /* Rest of the folders */
619 for($k = 0; $k < $cnt; $k++) {
620 if (!$used[$k]) {
621 $boxesnew[] = $boxesall[$k];
622 }
623 }
624 }
625 return $boxesnew;
626 }
627
628 /*
629 * Returns a list of all folders, subscribed or not
630 */
631 function sqimap_mailbox_list_all($imap_stream) {
632 global $list_special_folders_first, $folder_prefix, $delimiter;
633 $read_ary = sqimap_run_command($imap_stream,"LIST \"$folder_prefix\" *",true,$response, $message,false);
634 $g = 0;
635 $phase = 'inbox';
636 $fld_pre_length = strlen($folder_prefix);
637 for ($i = 0, $cnt = count($read_ary); $i < $cnt; $i++) {
638 /* Another workaround for EIMS */
639 if (isset($read_ary[$i + 1]) &&
640 ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)$",
641 $read_ary[$i], $regs)) {
642 $i ++;
643 $read_ary[$i] = $regs[1] . '"' . addslashes(trim($read_ary[$i])) . '"' . $regs[2];
644 }
645 /* Store the raw IMAP reply */
646 $boxes[$g]['raw'] = $read_ary[$i];
647
648 /* Count number of delimiters ($delimiter) in folder name */
649 $mailbox = find_mailbox_name($read_ary[$i]);
650 $dm_count = substr_count($mailbox, $delimiter);
651 if (substr($mailbox, -1) == $delimiter) {
652 /* If name ends in delimiter - decrement count by one */
653 $dm_count--;
654 }
655
656 /* Format folder name, but only if it's a INBOX.* or has a parent. */
657 $boxesallbyname[$mailbox] = $g;
658 $parentfolder = readMailboxParent($mailbox, $delimiter);
659 if((eregi('^inbox'.quotemeta($delimiter), $mailbox)) ||
660 (ereg('^'.$folder_prefix, $mailbox)) ||
661 ( isset($boxesallbyname[$parentfolder]) && (strlen($parentfolder) > 0) ) ) {
662 if ($dm_count) {
663 $boxes[$g]['formatted'] = str_repeat('&nbsp;&nbsp;', $dm_count);
664 } else {
665 $boxes[$g]['formatted'] = '';
666 }
667 $boxes[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
668 } else {
669 $boxes[$g]['formatted'] = imap_utf7_decode_local($mailbox);
670 }
671
672 $boxes[$g]['unformatted-dm'] = $mailbox;
673 if (substr($mailbox, -1) == $delimiter) {
674 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
675 }
676 $boxes[$g]['unformatted'] = $mailbox;
677 $boxes[$g]['unformatted-disp'] = substr($mailbox,$fld_pre_length);
678
679 $boxes[$g]['id'] = $g;
680
681 /* Now lets get the flags for this mailbox */
682 $read_mlbx = $read_ary[$i];
683 $flags = substr($read_mlbx, strpos($read_mlbx, '(')+1);
684 $flags = substr($flags, 0, strpos($flags, ')'));
685 $flags = str_replace('\\', '', $flags);
686 $flags = trim(strtolower($flags));
687 if ($flags) {
688 $boxes[$g]['flags'] = explode(' ', $flags);
689 } else {
690 $boxes[$g]['flags'] = array();
691 }
692 $g++;
693 }
694 if(is_array($boxes)) {
695 sort ($boxes);
696 }
697
698 return $boxes;
699 }
700
701 function sqimap_mailbox_tree($imap_stream) {
702 global $boxesnew, $default_folder_prefix, $unseen_notify, $unseen_type;
703 if (!isset($boxesnew)) {
704
705 global $data_dir, $username, $list_special_folders_first,
706 $folder_prefix, $delimiter, $trash_folder, $move_to_trash,
707 $imap_server_type;
708
709
710 $inbox_in_list = false;
711 $inbox_subscribed = false;
712
713 require_once(SM_PATH . 'include/load_prefs.php');
714
715 /* LSUB array */
716 $lsub_ary = sqimap_run_command ($imap_stream, "LSUB \"$folder_prefix\" \"*\"",
717 true, $response, $message);
718
719 /* Check to see if we have an INBOX */
720 $has_inbox = false;
721
722 for ($i = 0, $cnt = count($lsub_ary); $i < $cnt; $i++) {
723 if (preg_match("/^\*\s+LSUB\s+(.*)\"?INBOX\"?[^(\/\.)].*$/",$lsub_ary[$i])) {
724 $has_inbox = true;
725 break;
726 }
727 }
728
729 if ($has_inbox == false) {
730 $lsub_ibx = sqimap_run_command( $imap_stream, "LSUB \"\" \"INBOX\"", true, $response, $message );
731 if (isset($lsub_ibx[0]) && (preg_match("/^\*\s+LSUB\s+(.*)\"?INBOX\"?[^(\/\.)].*$/",$lsub_ibx[0]))) {
732 $lsub_ary[] = $lsub_ibx[0];
733 } else {
734 $lsub_ibx = sqimap_run_command( $imap_stream, "LIST \"\" \"INBOX\"", true, $response, $message );
735 if (preg_match("/^\*\s+LIST\s+(.*)\"?INBOX\"?[^(\/\.)].*$/",$lsub_ibx[0])) {
736 sqimap_run_command( $imap_stream, "SUBSCRIBE \"INBOX\"", true, $response, $message );
737 $lsub_ibx[0] = str_replace("LIST","LSUB",$lsub_ibx[0]);
738 $lsub_ary[] = $lsub_ibx[0];
739 }
740 }
741 }
742
743 /*
744 * Section about removing the last element was removed
745 * We don't return "* OK" anymore from sqimap_read_data
746 */
747 $sorted_lsub_ary = array();
748 $cnt = count($lsub_ary);
749
750 for ($i = 0; $i < $cnt; $i++) {
751 /*
752 * Workaround for EIMS
753 * Doesn't work if the mailbox name is multiple lines
754 */
755 if (isset($lsub_ary[$i + 1]) &&
756 ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)$",
757 $lsub_ary[$i], $regs)) {
758 $i++;
759 $lsub_ary[$i] = $regs[1] . '"' . addslashes(trim($lsub_ary[$i])) . '"' . $regs[2];
760 }
761
762 $mbx = find_mailbox_name($lsub_ary[$i]);
763
764 // only do the noselect test if !uw, is checked later. FIX ME see conf.pl setting
765 if ($imap_server_type != "uw") {
766 $noselect = check_is_noselect($lsub_ary[$i]);
767 }
768 if (substr($mbx, -1) == $delimiter) {
769 $mbx = substr($mbx, 0, strlen($mbx) - 1);
770 }
771 $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect);
772 }
773 // FIX ME this requires a config setting inside conf.pl instead of checking on server type
774 if ($imap_server_type == "uw") {
775 $aQuery = array();
776 $aTag = array();
777 // prepare an array with queries
778 foreach ($sorted_lsub_ary as $aMbx) {
779 $mbx = $aMbx['mbx'];
780 $query = "LIST \"\" \"$mbx\"";
781 sqimap_prepare_pipelined_query($query,$tag,$aQuery,false);
782 $aTag[$tag] = $mbx;
783 }
784 $sorted_lsub_ary = array();
785 // execute all the queries at once
786 $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
787 foreach($aTag as $tag => $mbx) {
788 if ($aServerResponse[$tag] == 'OK') {
789 $sResponse = implode('', $aResponse[$tag]);
790 $noselect = check_is_noselect($sResponse);
791 $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect);
792 }
793 }
794 $cnt = count($sorted_lsub_ary);
795 }
796
797 $sorted_lsub_ary = array_values($sorted_lsub_ary);
798 array_multisort($sorted_lsub_ary, SORT_ASC, SORT_REGULAR);
799 $boxesnew = sqimap_fill_mailbox_tree($sorted_lsub_ary,false,$imap_stream);
800 return $boxesnew;
801 }
802 }
803
804 function sqimap_fill_mailbox_tree($mbx_ary, $mbxs=false,$imap_stream) {
805 global $data_dir, $username, $list_special_folders_first,
806 $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
807 $move_to_trash, $move_to_sent, $save_as_draft,
808 $delimiter, $imap_server_type;
809
810 $special_folders = array ('INBOX', $sent_folder, $draft_folder, $trash_folder);
811
812 /* create virtual root node */
813 $mailboxes= new mailboxes();
814 $mailboxes->is_root = true;
815 $trail_del = false;
816 $start = 0;
817
818
819 if (isset($folder_prefix) && ($folder_prefix != '')) {
820 $start = substr_count($folder_prefix,$delimiter);
821 if (strrpos($folder_prefix, $delimiter) == (strlen($folder_prefix)-1)) {
822 $trail_del = true;
823 $mailboxes->mailboxname_full = substr($folder_prefix,0, (strlen($folder_prefix)-1));
824 } else {
825 $mailboxes->mailboxname_full = $folder_prefix;
826 $start++;
827 }
828 $mailboxes->mailboxname_sub = $mailboxes->mailboxname_full;
829 } else {
830 $start = 0;
831 }
832
833 $cnt = count($mbx_ary);
834 for ($i=0; $i < $cnt; $i++) {
835 if ($mbx_ary[$i]['mbx'] !='' ) {
836 $mbx = new mailboxes();
837 $mailbox = $mbx_ary[$i]['mbx'];
838 switch ($mailbox) {
839 case 'INBOX':
840 $mbx->is_inbox = true;
841 $mbx->is_special = true;
842 break;
843 case $trash_folder:
844 $mbx->is_trash = true;
845 $mbx->is_special = true;
846 break;
847 case $sent_folder:
848 $mbx->is_sent = true;
849 $mbx->is_special = true;
850 break;
851 case $draft_folder:
852 $mbx->is_draft = true;
853 $mbx->is_special = true;
854 break;
855 }
856
857 if (isset($mbx_ary[$i]['unseen'])) {
858 $mbx->unseen = $mbx_ary[$i]['unseen'];
859 }
860 if (isset($mbx_ary[$i]['nummessages'])) {
861 $mbx->total = $mbx_ary[$i]['nummessages'];
862 }
863
864 $mbx->is_noselect = $mbx_ary[$i]['noselect'];
865
866 $r_del_pos = strrpos($mbx_ary[$i]['mbx'], $delimiter);
867 if ($r_del_pos) {
868 $mbx->mailboxname_sub = substr($mbx_ary[$i]['mbx'],$r_del_pos+1);
869 } else { /* mailbox is root folder */
870 $mbx->mailboxname_sub = $mbx_ary[$i]['mbx'];
871 }
872 $mbx->mailboxname_full = $mbx_ary[$i]['mbx'];
873
874 $mailboxes->addMbx($mbx, $delimiter, $start, $list_special_folders_first);
875 }
876 }
877 sqimap_utf7_decode_mbx_tree($mailboxes);
878 sqimap_get_status_mbx_tree($imap_stream,$mailboxes);
879 return $mailboxes;
880 }
881
882 function sqimap_utf7_decode_mbx_tree(&$mbx_tree) {
883 $mbx_tree->mailboxname_sub=imap_utf7_decode_local($mbx_tree->mailboxname_sub);
884 if ($mbx_tree->mbxs) {
885 $iCnt = count($mbx_tree->mbxs);
886 for ($i=0;$i<$iCnt;++$i) {
887 $mbxs_tree->mbxs[$i] = sqimap_utf7_decode_mbx_tree($mbx_tree->mbxs[$i]);
888 }
889 }
890 }
891
892
893 function sqimap_tree_to_ref_array(&$mbx_tree,&$aMbxs) {
894 $aMbxs[] =& $mbx_tree;
895 if ($mbx_tree->mbxs) {
896 $iCnt = count($mbx_tree->mbxs);
897 for ($i=0;$i<$iCnt;++$i) {
898 $aMbxs[] =& sqimap_tree_to_ref_array($mbx_tree->mbxs[$i],$aMbxs);
899 }
900 }
901 }
902
903
904 /* Define preferences for folder settings. */
905 /* FIXME, we should load constants.php
906 unseen_notify
907 define('SMPREF_UNSEEN_NONE', 1);
908 define('SMPREF_UNSEEN_INBOX', 2);
909 define('SMPREF_UNSEEN_ALL', 3);
910
911 define('SMPREF_UNSEEN_SPECIAL', 4); // Only special folders
912 define('SMPREF_UNSEEN_NORMAL', 5); // Only normal folders
913
914 unseen_type
915 define('SMPREF_UNSEEN_ONLY', 1);
916 define('SMPREF_UNSEEN_TOTAL', 2);
917 */
918
919 function sqimap_get_status_mbx_tree($imap_stream,&$mbx_tree) {
920 global $unseen_notify, $unseen_type, $trash_folder,$move_to_trash;
921 $aMbxs = $aQuery = $aTag = array();
922 sqimap_tree_to_ref_array($mbx_tree,$aMbxs);
923 // remove the root node
924 array_shift($aMbxs);
925
926 if($unseen_notify == 3) {
927 $cnt = count($aMbxs);
928 for($i=0;$i<$cnt;++$i) {
929 $oMbx =& $aMbxs[$i];
930 if (!$oMbx->is_noselect) {
931 $mbx = $oMbx->mailboxname_full;
932 if ($unseen_type == 2) {
933 $query = "STATUS \"$mbx\" (MESSAGES UNSEEN)";
934 } else {
935 $query = "STATUS \"$mbx\" (UNSEEN)";
936 }
937 sqimap_prepare_pipelined_query($query,$tag,$aQuery,false);
938 } else {
939 $oMbx->unseen = $oMbx->total = false;
940 $tag = false;
941 }
942 $oMbx->tag = $tag;
943 $aMbxs[$i] =& $oMbx;
944 }
945 // execute all the queries at once
946 $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
947 $cnt = count($aMbxs);
948 for($i=0;$i<$cnt;++$i) {
949 $oMbx =& $aMbxs[$i];
950 $tag = $oMbx->tag;
951 if ($tag && $aServerResponse[$tag] == 'OK') {
952 $sResponse = implode('', $aResponse[$tag]);
953 if (preg_match('/UNSEEN\s+([0-9]+)/i', $sResponse, $regs)) {
954 $oMbx->unseen = $regs[1];
955 }
956 if (preg_match('/MESSAGES\s+([0-9]+)/i', $sResponse, $regs)) {
957 $oMbx->total = $regs[1];
958 }
959 }
960 unset($oMbx->tag);
961 }
962 } else if ($unseen_notify == 2) { // INBOX only
963 $cnt = count($aMbxs);
964 for($i=0;$i<$cnt;++$i) {
965 $oMbx =& $aMbxs[$i];
966 if (strtoupper($oMbx->mailboxname_full) == 'INBOX' ||
967 ($move_to_trash && $oMbx->mailboxname_full == $trash_folder)) {
968 if ($unseen_type == 2) {
969 $aStatus = sqimap_status_messages($imap_stream,$oMbx->mailboxname_full);
970 $oMbx->unseen = $aStatus['UNSEEN'];
971 $oMbx->total = $aStatus['MESSAGES'];
972 } else {
973 $oMbx->unseen = sqimap_unseen_messages($imap_stream,$oMbx->mailboxname_full);
974 }
975 $aMbxs[$i] =& $oMbx;
976 if (!$move_to_trash && $trash_folder) {
977 break;
978 } else {
979 // trash comes after INBOX
980 if ($oMbx->mailboxname_full == $trash_folder) {
981 break;
982 }
983 }
984 }
985 }
986 }
987 }
988
989 ?>