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