3be48cdd436964c73a3e8a0e0a65db1df2fdb8dd
6 * Copyright (c) 1999-2005 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This implements all functions that manipulate mailboxes
12 * @package squirrelmail
17 if (! defined('SM_PATH')) define('SM_PATH','../');
20 require_once(SM_PATH
. 'functions/imap_utf7_local.php');
27 * FIXME. This class should be extracted and placed in a separate file that
28 * can be included before we start the session. That makes caching of the tree
29 * possible. On a refresh mailboxes from left_main.php the only function that
30 * should be called is the sqimap_get_status_mbx_tree. In case of subscribe
31 * / rename / delete / new we have to create methods for adding/changing the
32 * mailbox in the mbx_tree without the need for a refresh.
34 * Some code fragments are present in 1.3.0 - 1.4.4.
35 * @package squirrelmail
40 var $mailboxname_full = '', $mailboxname_sub= '', $is_noselect = false, $is_noinferiors = false,
41 $is_special = false, $is_root = false, $is_inbox = false, $is_sent = false,
42 $is_trash = false, $is_draft = false, $mbxs = array(),
43 $unseen = false, $total = false;
45 function addMbx($mbx, $delimiter, $start, $specialfirst) {
46 $ary = explode($delimiter, $mbx->mailboxname_full
);
48 for ($i = $start, $c = count($ary)-1; $i < $c; $i++
) {
49 $mbx_childs =& $mbx_parent->mbxs
;
52 foreach ($mbx_childs as $key => $parent) {
53 if ($parent->mailboxname_sub
== $ary[$i]) {
54 $mbx_parent =& $mbx_parent->mbxs
[$key];
61 $no_select_mbx = new mailboxes();
62 if (isset($mbx_parent->mailboxname_full
) && $mbx_parent->mailboxname_full
!= '') {
63 $no_select_mbx->mailboxname_full
= $mbx_parent->mailboxname_full
.$delimiter.$ary[$i];
65 $no_select_mbx->mailboxname_full
= $ary[$i];
67 $no_select_mbx->mailboxname_sub
= $ary[$i];
68 $no_select_mbx->is_noselect
= true;
69 $mbx_parent->mbxs
[] = $no_select_mbx;
73 $mbx_parent->mbxs
[] = $mbx;
74 if ($mbx->is_special
&& $specialfirst) {
75 usort($mbx_parent->mbxs
, 'sortSpecialMbx');
81 * array callback used for sorting in mailboxes class
84 * @return integer see php strnatcasecmp()
87 function sortSpecialMbx($a, $b) {
89 $acmp = '0'. $a->mailboxname_full
;
90 } else if ($a->is_special
) {
91 $acmp = '1'. $a->mailboxname_full
;
93 $acmp = '2' . $a->mailboxname_full
;
96 $bcmp = '0'. $b->mailboxname_full
;
97 }else if ($b->is_special
) {
98 $bcmp = '1' . $b->mailboxname_full
;
100 $bcmp = '2' . $b->mailboxname_full
;
102 return strnatcasecmp($acmp, $bcmp);
110 function compact_mailboxes_response($ary) {
112 * Workaround for mailboxes returned as literal
113 * FIXME : Doesn't work if the mailbox name is multiple lines
114 * (larger then fgets buffer)
116 for ($i = 0, $iCnt=count($ary); $i < $iCnt; $i++
) {
117 if (isset($ary[$i +
1]) && substr($ary[$i], -3) == "}\r\n") {
118 if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)$",
120 $ary[$i] = $regs[1] . '"' . addslashes(trim($ary[$i+
1])) . '"' . $regs[2];
121 array_splice($ary, $i+
1, 2);
125 /* remove duplicates and ensure array is contiguous */
126 return array_values(array_unique($ary));
130 * Extract the mailbox name from an untagged LIST (7.2.2) or LSUB (7.2.3) answer
131 * (LIST|LSUB) (<Flags list>) (NIL|"<separator atom>") <mailbox name string>\r\n
132 * mailbox name in quoted string MUST be unquoted and stripslashed (sm API)
134 * Originally stored in functions/strings.php. Since 1.2.6 stored in
135 * functions/imap_mailbox.php
136 * @param string $line imap LIST/LSUB response line
137 * @return string mailbox name
139 function find_mailbox_name($line) {
140 if (preg_match('/^\* (?:LIST|LSUB) \([^\)]*\) (?:NIL|\"[^\"]*\") ([^\r\n]*)[\r\n]*$/i', $line, $regs)) {
141 if (substr($regs[1], 0, 1) == '"')
142 return stripslashes(substr($regs[1], 1, -1));
149 * Detects if mailbox has noselect flag (can't store messages)
150 * In versions older than 1.4.5 function checks only LSUB responses
151 * and can produce pcre warnings.
152 * @param string $lsub_line mailbox line from untagged LIST or LSUB response
153 * @return bool whether this is a Noselect mailbox.
156 function check_is_noselect ($lsub_line) {
157 return preg_match("/^\* (LSUB|LIST) \([^\)]*\\\\Noselect[^\)]*\)/i", $lsub_line);
161 * Detects if mailbox has noinferiors flag (can't store subfolders)
162 * @param string $lsub_line mailbox line from untagged LIST or LSUB response
163 * @return bool whether this is a Noinferiors mailbox.
166 function check_is_noinferiors ($lsub_line) {
167 return preg_match("/^\* (LSUB|LIST) \([^\)]*\\\\Noinferiors[^\)]*\)/i", $lsub_line);
171 * Detects mailbox's parent folder
173 * If $haystack is a full mailbox name, and $needle is the mailbox
174 * separator character, returns the second last part of the full
175 * mailbox name (i.e. the mailbox's parent mailbox)
177 * Originally stored in functions/strings.php. Since 1.2.6 stored in
178 * functions/imap_mailbox.php
179 * @param string $haystack full mailbox name
180 * @param string $needle delimiter
181 * @return string parent mailbox
183 function readMailboxParent($haystack, $needle) {
187 $parts = explode($needle, $haystack);
188 $elem = array_pop($parts);
189 while ($elem == '' && count($parts)) {
190 $elem = array_pop($parts);
192 $ret = join($needle, $parts);
198 * Check if $subbox is below the specified $parentbox
199 * @param string $subbox potential sub folder
200 * @param string $parentbox potential parent
204 function isBoxBelow( $subbox, $parentbox ) {
207 * Eliminate the obvious mismatch, where the
208 * subfolder path is shorter than that of the potential parent
210 if ( strlen($subbox) < strlen($parentbox) ) {
213 /* check for delimiter */
214 if (substr($parentbox,-1) != $delimiter) {
215 $parentbox .= $delimiter;
218 return (substr($subbox,0,strlen($parentbox)) == $parentbox);
222 * Defines special mailboxes: given a mailbox name, it checks if this is a
223 * "special" one: INBOX, Trash, Sent or Draft.
225 * Since 1.2.5 function includes special_mailbox hook.<br>
226 * Since 1.4.3 hook supports more than one plugin.
227 * @param string $box mailbox name
231 function isSpecialMailbox( $box ) {
232 $ret = ( (strtolower($box) == 'inbox') ||
233 isTrashMailbox($box) ||
isSentMailbox($box) ||
isDraftMailbox($box) );
236 $ret = boolean_hook_function('special_mailbox',$box,1);
242 * Detects if mailbox is a Trash folder or subfolder of Trash
243 * @param string $box mailbox name
244 * @return bool whether this is a Trash folder
247 function isTrashMailbox ($box) {
248 global $trash_folder, $move_to_trash;
249 return $move_to_trash && $trash_folder &&
250 ( $box == $trash_folder ||
isBoxBelow($box, $trash_folder) );
254 * Detects if mailbox is a Sent folder or subfolder of Sent
255 * @param string $box mailbox name
256 * @return bool whether this is a Sent folder
259 function isSentMailbox($box) {
260 global $sent_folder, $move_to_sent;
261 return $move_to_sent && $sent_folder &&
262 ( $box == $sent_folder ||
isBoxBelow($box, $sent_folder) );
266 * Detects if mailbox is a Drafts folder or subfolder of Drafts
267 * @param string $box mailbox name
268 * @return bool whether this is a Draft folder
271 function isDraftMailbox($box) {
272 global $draft_folder, $save_as_draft;
273 return $save_as_draft &&
274 ( $box == $draft_folder ||
isBoxBelow($box, $draft_folder) );
280 * WARNING: Select mailbox before calling this function.
282 * permanently removes all messages that have the \Deleted flag
283 * set from the selected mailbox. See EXPUNGE command chapter in
285 * @param stream $imap_stream imap connection resource
286 * @param string $mailbox mailbox name (unused since 1.1.3).
287 * @param boolean $handle_errors error handling control (displays error_box on error).
288 * @param mixed $id (since 1.3.0) integer message id or array with integer ids
289 * @return integer number of expunged messages
290 * @since 1.0 or older
292 function sqimap_mailbox_expunge ($imap_stream, $mailbox, $handle_errors = true, $id='') {
295 $id = sqimap_message_list_squisher($id);
302 $read = sqimap_run_command($imap_stream, 'EXPUNGE'.$id, $handle_errors,
303 $response, $message, $uid);
306 if (is_array($read)) {
307 foreach ($read as $r) {
308 if (preg_match('/^\*\s[0-9]+\sEXPUNGE/AUi',$r,$regs)) {
317 * Checks whether or not the specified mailbox exists
318 * @param stream $imap_stream imap connection resource
319 * @param string $mailbox mailbox name
321 * @since 1.0 or older
323 function sqimap_mailbox_exists ($imap_stream, $mailbox) {
324 if (!isset($mailbox) ||
empty($mailbox)) {
327 $mbx = sqimap_run_command($imap_stream, 'LIST "" ' . sqimap_encode_mailbox_name($mailbox),
328 true, $response, $message);
329 return isset($mbx[0]);
334 * Before 1.3.0 used more arguments and returned data depended on those argumements.
335 * @param stream $imap_stream imap connection resource
336 * @param string $mailbox mailbox name
337 * @return array results of select command (on success - permanentflags, flags and rights)
338 * @since 1.0 or older
340 function sqimap_mailbox_select ($imap_stream, $mailbox) {
341 if ($mailbox == 'None') {
345 $read = sqimap_run_command($imap_stream, 'SELECT ' . sqimap_encode_mailbox_name($mailbox),
346 true, $response, $message);
348 for ($i = 0, $cnt = count($read); $i < $cnt; $i++
) {
349 if (preg_match('/^\*\s+OK\s\[(\w+)\s(\w+)\]/',$read[$i], $regs)) {
350 $result[strtoupper($regs[1])] = $regs[2];
351 } else if (preg_match('/^\*\s([0-9]+)\s(\w+)/',$read[$i], $regs)) {
352 $result[strtoupper($regs[2])] = $regs[1];
354 if (preg_match("/PERMANENTFLAGS(.*)/i",$read[$i], $regs)) {
355 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/","/\]/") ,'', $regs[1])) ;
356 $result['PERMANENTFLAGS'] = explode(' ',strtolower($regs[1]));
357 } else if (preg_match("/FLAGS(.*)/i",$read[$i], $regs)) {
358 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/") ,'', $regs[1])) ;
359 $result['FLAGS'] = explode(' ',strtolower($regs[1]));
363 if (!isset($result['PERMANENTFLAGS'])) {
364 $result['PERMANENTFLAGS'] = $result['FLAGS'];
366 if (preg_match('/^\[(.+)\]/',$message, $regs)) {
367 $result['RIGHTS']=strtoupper($regs[1]);
376 * Mailbox is automatically subscribed.
378 * Set $type to string that does not match 'noselect' (case insensitive),
379 * if you don't want to prepend delimiter to mailbox name. Please note
380 * that 'noinferiors' might be used someday as keyword for folders
381 * that store only messages.
382 * @param stream $imap_steam imap connection resource
383 * @param string $mailbox mailbox name
384 * @param string $type folder type.
385 * @since 1.0 or older
387 function sqimap_mailbox_create ($imap_stream, $mailbox, $type) {
389 if (strtolower($type) == 'noselect') {
390 $mailbox .= $delimiter;
393 $read_ary = sqimap_run_command($imap_stream, 'CREATE ' .
394 sqimap_encode_mailbox_name($mailbox),
395 true, $response, $message);
396 sqimap_subscribe ($imap_stream, $mailbox);
400 * Subscribes to an existing folder.
401 * @param stream $imap_stream imap connection resource
402 * @param string $mailbox mailbox name
403 * @param boolean $debug (since 1.5.1)
404 * @since 1.0 or older
406 function sqimap_subscribe ($imap_stream, $mailbox,$debug=true) {
407 $read_ary = sqimap_run_command($imap_stream, 'SUBSCRIBE ' .
408 sqimap_encode_mailbox_name($mailbox),
409 $debug, $response, $message);
413 * Unsubscribes from an existing folder
414 * @param stream $imap_stream imap connection resource
415 * @param string $mailbox mailbox name
416 * @since 1.0 or older
418 function sqimap_unsubscribe ($imap_stream, $mailbox) {
419 $read_ary = sqimap_run_command($imap_stream, 'UNSUBSCRIBE ' .
420 sqimap_encode_mailbox_name($mailbox),
421 false, $response, $message);
425 * Deletes the given folder
426 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
427 * @param stream $imap_stream imap connection resource
428 * @param string $mailbox mailbox name
429 * @since 1.0 or older
431 function sqimap_mailbox_delete ($imap_stream, $mailbox) {
432 global $data_dir, $username;
433 sqimap_unsubscribe ($imap_stream, $mailbox);
435 if (sqimap_mailbox_exists($imap_stream, $mailbox)) {
437 $read_ary = sqimap_run_command($imap_stream, 'DELETE ' .
438 sqimap_encode_mailbox_name($mailbox),
439 true, $response, $message);
440 if ($response !== 'OK') {
442 sqimap_subscribe ($imap_stream, $mailbox);
444 do_hook_function('rename_or_delete_folder', $args = array($mailbox, 'delete', ''));
445 removePref($data_dir, $username, "thread_$mailbox");
446 removePref($data_dir, $username, "collapse_folder_$mailbox");
452 * Determines if the user is subscribed to the folder or not
453 * @param stream $imap_stream imap connection resource
454 * @param string $mailbox mailbox name
458 function sqimap_mailbox_is_subscribed($imap_stream, $folder) {
459 $boxesall = sqimap_mailbox_list ($imap_stream);
460 foreach ($boxesall as $ref) {
461 if ($ref['unformatted'] == $folder) {
470 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
471 * @param stream $imap_stream imap connection resource
472 * @param string $old_name mailbox name
473 * @param string $new_name new mailbox name
476 function sqimap_mailbox_rename( $imap_stream, $old_name, $new_name ) {
477 if ( $old_name != $new_name ) {
478 global $delimiter, $imap_server_type, $data_dir, $username;
479 if ( substr( $old_name, -1 ) == $delimiter ) {
480 $old_name = substr( $old_name, 0, strlen( $old_name ) - 1 );
481 $new_name = substr( $new_name, 0, strlen( $new_name ) - 1 );
482 $postfix = $delimiter;
487 $boxesall = sqimap_mailbox_list_all($imap_stream);
488 $cmd = 'RENAME ' . sqimap_encode_mailbox_name($old_name) .
489 ' ' . sqimap_encode_mailbox_name($new_name);
490 $data = sqimap_run_command($imap_stream, $cmd, true, $response, $message);
491 sqimap_unsubscribe($imap_stream, $old_name.$postfix);
492 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$old_name.$postfix);
493 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
494 removePref($data_dir, $username, 'thread_'.$old_name.$postfix);
495 removePref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
496 sqimap_subscribe($imap_stream, $new_name.$postfix);
497 setPref($data_dir, $username, 'thread_'.$new_name.$postfix, $oldpref_thread);
498 setPref($data_dir, $username, 'collapse_folder_'.$new_name.$postfix, $oldpref_collapse);
499 do_hook_function('rename_or_delete_folder',$args = array($old_name, 'rename', $new_name));
500 $l = strlen( $old_name ) +
1;
503 foreach ($boxesall as $box) {
504 if (substr($box[$p], 0, $l) == $old_name . $delimiter) {
505 $new_sub = $new_name . $delimiter . substr($box[$p], $l);
506 /* With Cyrus IMAPd >= 2.0 rename is recursive, so don't check for errors here */
507 if ($imap_server_type == 'cyrus') {
508 $cmd = 'RENAME "' . $box[$p] . '" "' . $new_sub . '"';
509 $data = sqimap_run_command($imap_stream, $cmd, false,
510 $response, $message);
512 $was_subscribed = sqimap_mailbox_is_subscribed($imap_stream, $box[$p]);
513 if ( $was_subscribed ) {
514 sqimap_unsubscribe($imap_stream, $box[$p]);
516 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$box[$p]);
517 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$box[$p]);
518 removePref($data_dir, $username, 'thread_'.$box[$p]);
519 removePref($data_dir, $username, 'collapse_folder_'.$box[$p]);
520 if ( $was_subscribed ) {
521 sqimap_subscribe($imap_stream, $new_sub);
523 setPref($data_dir, $username, 'thread_'.$new_sub, $oldpref_thread);
524 setPref($data_dir, $username, 'collapse_folder_'.$new_sub, $oldpref_collapse);
525 do_hook_function('rename_or_delete_folder',
526 $args = array($box[$p], 'rename', $new_sub));
533 * Formats a mailbox into parts for the $boxesall array
537 * <li>raw - Raw LIST/LSUB response from the IMAP server
538 * <li>formatted - nicely formatted folder name
539 * <li>unformatted - unformatted, but with delimiter at end removed
540 * <li>unformatted-dm - folder name as it appears in raw response
541 * <li>unformatted-disp - unformatted without $folder_prefix
542 * <li>id - TODO: document me
543 * <li>flags - TODO: document me
545 * Before 1.2.0 used third argument for delimiter.
549 * @since 1.0 or older
550 * @todo document id and flags keys in boxes array and function arguments.
552 function sqimap_mailbox_parse ($line, $line_lsub) {
553 global $folder_prefix, $delimiter;
555 /* Process each folder line */
556 for ($g = 0, $cnt = count($line); $g < $cnt; ++
$g) {
557 /* Store the raw IMAP reply */
558 if (isset($line[$g])) {
559 $boxesall[$g]['raw'] = $line[$g];
561 $boxesall[$g]['raw'] = '';
564 /* Count number of delimiters ($delimiter) in folder name */
565 $mailbox = /*trim(*/$line_lsub[$g]/*)*/;
566 $dm_count = substr_count($mailbox, $delimiter);
567 if (substr($mailbox, -1) == $delimiter) {
568 /* If name ends in delimiter, decrement count by one */
572 /* Format folder name, but only if it's a INBOX.* or has a parent. */
573 $boxesallbyname[$mailbox] = $g;
574 $parentfolder = readMailboxParent($mailbox, $delimiter);
575 if ( (strtolower(substr($mailbox, 0, 5)) == "inbox") ||
576 (substr($mailbox, 0, strlen($folder_prefix)) == $folder_prefix) ||
577 (isset($boxesallbyname[$parentfolder]) &&
578 (strlen($parentfolder) > 0) ) ) {
579 $indent = $dm_count - (substr_count($folder_prefix, $delimiter));
581 $boxesall[$g]['formatted'] = str_repeat(' ', $indent);
583 $boxesall[$g]['formatted'] = '';
585 $boxesall[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
587 $boxesall[$g]['formatted'] = imap_utf7_decode_local($mailbox);
590 $boxesall[$g]['unformatted-dm'] = $mailbox;
591 if (substr($mailbox, -1) == $delimiter) {
592 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
594 $boxesall[$g]['unformatted'] = $mailbox;
595 if (substr($mailbox,0,strlen($folder_prefix))==$folder_prefix) {
596 $mailbox = substr($mailbox, strlen($folder_prefix));
598 $boxesall[$g]['unformatted-disp'] = $mailbox;
599 $boxesall[$g]['id'] = $g;
601 $boxesall[$g]['flags'] = array();
602 if (isset($line[$g])) {
603 ereg("\(([^)]*)\)",$line[$g],$regs);
604 // FIXME Flags do contain the \ character. \NoSelect \NoInferiors
605 // and $MDNSent <= last one doesn't have the \
606 // It's better to follow RFC3501 instead of using our own naming.
607 $flags = trim(strtolower(str_replace('\\', '',$regs[1])));
609 $boxesall[$g]['flags'] = explode(' ', $flags);
617 * Returns list of options (to be echoed into select statement
618 * based on available mailboxes and separators
619 * Caller should surround options with <select ...> </select> and
621 * @param stream $imap_stream imap connection resource to query for mailboxes
622 * @param array $show_selected array containing list of mailboxes to pre-select (0 if none)
623 * @param array $folder_skip array of folders to keep out of option list (compared in lower)
624 * @param $boxes list of already fetched boxes (for places like folder panel, where
625 * you know these options will be shown 3 times in a row.. (most often unset).
626 * @param string $flag (since 1.4.1) flag to check for in mailbox flags, used to filter out mailboxes.
627 * 'noselect' by default to remove unselectable mailboxes.
628 * 'noinferiors' used to filter out folders that can not contain subfolders.
629 * NULL to avoid flag check entirely.
630 * NOTE: noselect and noiferiors are used internally. The IMAP representation is
631 * \NoSelect and \NoInferiors
632 * @param boolean $use_long_format (since 1.4.1) override folder display preference and always show full folder name.
633 * @return string html formated mailbox selection options
636 function sqimap_mailbox_option_list($imap_stream, $show_selected = 0, $folder_skip = 0, $boxes = 0,
637 $flag = 'noselect', $use_long_format = false ) {
638 global $username, $data_dir;
640 if ( $use_long_format ) {
641 $shorten_box_names = 0;
643 $shorten_box_names = getPref($data_dir, $username, 'mailbox_select_style', SMPREF_OFF
);
647 $boxes = sqimap_mailbox_list($imap_stream);
650 foreach ($boxes as $boxes_part) {
651 if ($flag == NULL ||
(is_array($boxes_part['flags'])
652 && !in_array($flag, $boxes_part['flags']))) {
653 $box = $boxes_part['unformatted'];
655 if ($folder_skip != 0 && in_array($box, $folder_skip) ) {
658 $lowerbox = strtolower($box);
659 // mailboxes are casesensitive => inbox.sent != inbox.Sent
660 // nevermind, to many dependencies this should be fixed!
662 if (strtolower($box) == 'inbox') { // inbox is special and not casesensitive
665 switch ($shorten_box_names)
667 case 2: /* delimited, style = 2 */
668 $box2 = str_replace('&nbsp;&nbsp;', '. ', htmlspecialchars($boxes_part['formatted']));
670 case 1: /* indent, style = 1 */
671 $box2 = str_replace('&nbsp;&nbsp;', ' ', htmlspecialchars($boxes_part['formatted']));
673 default: /* default, long names, style = 0 */
674 $box2 = str_replace(' ', ' ', htmlspecialchars(imap_utf7_decode_local($boxes_part['unformatted-disp'])));
678 if ($show_selected != 0 && in_array($lowerbox, $show_selected) ) {
679 $mbox_options .= '<option value="' . htmlspecialchars($box) .'" selected="selected">'.$box2.'</option>' . "\n";
681 $mbox_options .= '<option value="' . htmlspecialchars($box) .'">'.$box2.'</option>' . "\n";
685 return $mbox_options;
689 * Returns sorted mailbox lists in several different ways.
690 * See comment on sqimap_mailbox_parse() for info about the returned array.
691 * @param resource $imap_stream imap connection resource
692 * @param boolean $force force update of mailbox listing. available since 1.4.2 and 1.5.0
693 * @return array list of mailboxes
694 * @since 1.0 or older
696 function sqimap_mailbox_list($imap_stream, $force=false) {
697 if (!sqgetGlobalVar('boxesnew',$boxesnew,SQ_SESSION
) ||
$force) {
698 global $data_dir, $username, $list_special_folders_first,
699 $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
700 $move_to_trash, $move_to_sent, $save_as_draft,
701 $delimiter, $noselect_fix_enable, $imap_server_type,
702 $show_only_subscribed_folders;
703 $inbox_subscribed = false;
704 $listsubscribed = sqimap_capability($imap_stream,'LIST-SUBSCRIBED');
706 require_once(SM_PATH
. 'include/load_prefs.php');
708 if (!$show_only_subscribed_folders) {
710 } elseif ($listsubscribed) {
711 $lsub = 'LIST (SUBSCRIBED)';
716 if ($noselect_fix_enable) {
717 $lsub_args = "$lsub \"$folder_prefix\" \"*%\"";
719 $lsub_args = "$lsub \"$folder_prefix\" \"*\"";
722 $lsub_ary = sqimap_run_command ($imap_stream, $lsub_args,
723 true, $response, $message);
724 $lsub_ary = compact_mailboxes_response($lsub_ary);
726 $sorted_lsub_ary = array();
727 for ($i = 0, $cnt = count($lsub_ary);$i < $cnt; $i++
) {
729 $temp_mailbox_name = find_mailbox_name($lsub_ary[$i]);
730 $sorted_lsub_ary[] = $temp_mailbox_name;
731 if (!$inbox_subscribed && strtoupper($temp_mailbox_name) == 'INBOX') {
732 $inbox_subscribed = true;
736 /* natural sort mailboxes */
737 if (isset($sorted_lsub_ary)) {
738 usort($sorted_lsub_ary, 'strnatcasecmp');
741 * The LSUB response doesn't provide us information about \Noselect
742 * mail boxes. The LIST response does, that's why we need to do a LIST
743 * call to retrieve the flags for the mailbox
744 * Note: according RFC2060 an imap server may provide \NoSelect flags in the LSUB response.
745 * in other words, we cannot rely on it.
747 $sorted_list_ary = array();
748 // if (!$listsubscribed) {
749 for ($i=0; $i < count($sorted_lsub_ary); $i++
) {
750 if (substr($sorted_lsub_ary[$i], -1) == $delimiter) {
751 $mbx = substr($sorted_lsub_ary[$i], 0, strlen($sorted_lsub_ary[$i])-1);
754 $mbx = $sorted_lsub_ary[$i];
757 $read = sqimap_run_command ($imap_stream, 'LIST "" ' . sqimap_encode_mailbox_name($mbx),
758 true, $response, $message);
760 $read = compact_mailboxes_response($read);
762 if (isset($read[0])) {
763 $sorted_list_ary[$i] = $read[0];
765 $sorted_list_ary[$i] = '';
770 * Just in case they're not subscribed to their inbox,
771 * we'll get it for them anyway
773 if (!$inbox_subscribed) {
774 $inbox_ary = sqimap_run_command ($imap_stream, 'LIST "" "INBOX"',
775 true, $response, $message);
776 $sorted_list_ary[] = implode('',compact_mailboxes_response($inbox_ary));
777 $sorted_lsub_ary[] = find_mailbox_name($inbox_ary[0]);
780 $boxesall = sqimap_mailbox_parse ($sorted_list_ary, $sorted_lsub_ary);
782 /* Now, lets sort for special folders */
783 $boxesnew = $used = array();
786 $cnt = count($boxesall);
787 $used = array_pad($used,$cnt,false);
788 for($k = 0; $k < $cnt; ++
$k) {
789 if (strtolower($boxesall[$k]['unformatted']) == 'inbox') {
790 $boxesnew[] = $boxesall[$k];
795 /* List special folders and their subfolders, if requested. */
796 if ($list_special_folders_first) {
797 for($k = 0; $k < $cnt; ++
$k) {
798 if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
799 $boxesnew[] = $boxesall[$k];
805 /* Find INBOX's children */
806 for($k = 0; $k < $cnt; ++
$k) {
807 if (!$used[$k] && isBoxBelow(strtolower($boxesall[$k]['unformatted']), 'inbox') &&
808 strtolower($boxesall[$k]['unformatted']) != 'inbox') {
809 $boxesnew[] = $boxesall[$k];
814 /* Rest of the folders */
815 for($k = 0; $k < $cnt; $k++
) {
817 $boxesnew[] = $boxesall[$k];
820 sqsession_register($boxesnew,'boxesnew');
826 * Returns a list of all folders, subscribed or not
827 * @param stream $imap_stream imap connection resource
828 * @return array see sqimap_mailbox_parse()
829 * @since 1.0 or older
831 function sqimap_mailbox_list_all($imap_stream) {
832 global $list_special_folders_first, $folder_prefix, $delimiter;
834 $read_ary = sqimap_run_command($imap_stream,"LIST \"$folder_prefix\" *",true,$response, $message,false);
835 $read_ary = compact_mailboxes_response($read_ary);
838 $fld_pre_length = strlen($folder_prefix);
839 for ($i = 0, $cnt = count($read_ary); $i < $cnt; $i++
) {
840 /* Store the raw IMAP reply */
841 $boxes[$g]['raw'] = $read_ary[$i];
843 /* Count number of delimiters ($delimiter) in folder name */
844 $mailbox = find_mailbox_name($read_ary[$i]);
845 $dm_count = substr_count($mailbox, $delimiter);
846 if (substr($mailbox, -1) == $delimiter) {
847 /* If name ends in delimiter - decrement count by one */
851 /* Format folder name, but only if it's a INBOX.* or has a parent. */
852 $boxesallbyname[$mailbox] = $g;
853 $parentfolder = readMailboxParent($mailbox, $delimiter);
854 if((eregi('^inbox'.quotemeta($delimiter), $mailbox)) ||
855 (ereg('^'.$folder_prefix, $mailbox)) ||
856 ( isset($boxesallbyname[$parentfolder]) && (strlen($parentfolder) > 0) ) ) {
858 $boxes[$g]['formatted'] = str_repeat(' ', $dm_count);
860 $boxes[$g]['formatted'] = '';
862 $boxes[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
864 $boxes[$g]['formatted'] = imap_utf7_decode_local($mailbox);
867 $boxes[$g]['unformatted-dm'] = $mailbox;
868 if (substr($mailbox, -1) == $delimiter) {
869 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
871 $boxes[$g]['unformatted'] = $mailbox;
872 $boxes[$g]['unformatted-disp'] = substr($mailbox,$fld_pre_length);
874 $boxes[$g]['id'] = $g;
876 /* Now lets get the flags for this mailbox */
877 $read_mlbx = $read_ary[$i];
878 $flags = substr($read_mlbx, strpos($read_mlbx, '(')+
1);
879 $flags = substr($flags, 0, strpos($flags, ')'));
880 $flags = str_replace('\\', '', $flags);
881 $flags = trim(strtolower($flags));
883 $boxes[$g]['flags'] = explode(' ', $flags);
885 $boxes[$g]['flags'] = array();
889 if(is_array($boxes)) {
897 * Fills mailbox object
899 * Some code fragments are present in 1.3.0 - 1.4.4.
900 * @param stream $imap_stream imap connection resource
901 * @return object see mailboxes class.
904 function sqimap_mailbox_tree($imap_stream) {
905 global $default_folder_prefix, $data_dir, $username, $list_special_folders_first,
906 $folder_prefix, $delimiter, $trash_folder, $move_to_trash,
907 $imap_server_type, $show_only_subscribed_folders;
909 // TODO: implement mailbox tree caching. maybe store object in session?
912 $noinferiors = false;
914 require_once(SM_PATH
. 'include/load_prefs.php');
916 if ($show_only_subscribed_folders) {
923 $lsub_ary = sqimap_run_command ($imap_stream, "$lsub_cmd \"$folder_prefix\" \"*\"",
924 true, $response, $message);
925 $lsub_ary = compact_mailboxes_response($lsub_ary);
927 /* Check to see if we have an INBOX */
930 for ($i = 0, $cnt = count($lsub_ary); $i < $cnt; $i++
) {
931 if (preg_match("/^\*\s+$lsub_cmd.*\s\"?INBOX\"?\s*$/i",$lsub_ary[$i])) {
932 $lsub_ary[$i] = strtoupper($lsub_ary[$i]);
933 // in case of an unsubscribed inbox an imap server can
934 // return the inbox in the lsub results with a \NoSelect
936 if (!preg_match("/\*\s+$lsub_cmd\s+\(.*\\\\NoSelect.*\).*/i",$lsub_ary[$i])) {
939 // remove the result and request it again with a list
940 // response at a later stage.
941 unset($lsub_ary[$i]);
942 // re-index the array otherwise the addition of the LIST
943 // response will fail in PHP 4.1.2 and probably other older versions
944 $lsub_ary = array_values($lsub_ary);
950 if ($has_inbox == false) {
951 // do a list request for inbox because we should always show
952 // inbox even if the user isn't subscribed to it.
953 $inbox_ary = sqimap_run_command ($imap_stream, 'LIST "" "INBOX"',
954 true, $response, $message);
955 $inbox_ary = compact_mailboxes_response($inbox_ary);
956 if (count($inbox_ary)) {
957 $lsub_ary[] = $inbox_ary[0];
962 * Section about removing the last element was removed
963 * We don't return "* OK" anymore from sqimap_read_data
966 $sorted_lsub_ary = array();
967 $cnt = count($lsub_ary);
968 for ($i = 0; $i < $cnt; $i++
) {
969 $mbx = find_mailbox_name($lsub_ary[$i]);
971 // only do the noselect test if !uw, is checked later. FIX ME see conf.pl setting
972 if ($imap_server_type != "uw") {
973 $noselect = check_is_noselect($lsub_ary[$i]);
974 $noinferiors = check_is_noinferiors($lsub_ary[$i]);
976 if (substr($mbx, -1) == $delimiter) {
977 $mbx = substr($mbx, 0, strlen($mbx) - 1);
979 $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
981 // FIX ME this requires a config setting inside conf.pl instead of checking on server type
982 if ($imap_server_type == "uw") {
985 // prepare an array with queries
986 foreach ($sorted_lsub_ary as $aMbx) {
987 $mbx = stripslashes($aMbx['mbx']);
988 sqimap_prepare_pipelined_query('LIST "" ' . sqimap_encode_mailbox_name($mbx), $tag, $aQuery, false);
991 $sorted_lsub_ary = array();
992 // execute all the queries at once
993 $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
994 foreach($aTag as $tag => $mbx) {
995 if ($aServerResponse[$tag] == 'OK') {
996 $sResponse = implode('', $aResponse[$tag]);
997 $noselect = check_is_noselect($sResponse);
998 $noinferiors = check_is_noinferiors($sResponse);
999 $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
1002 $cnt = count($sorted_lsub_ary);
1004 $sorted_lsub_ary = array_values($sorted_lsub_ary);
1005 usort($sorted_lsub_ary, 'mbxSort');
1006 $boxestree = sqimap_fill_mailbox_tree($sorted_lsub_ary,false,$imap_stream);
1011 * Callback function used for sorting mailboxes in sqimap_mailbox_tree
1014 * @return integer see php strnatcasecmp()
1017 function mbxSort($a, $b) {
1018 return strnatcasecmp($a['mbx'], $b['mbx']);
1022 * Fills mailbox object
1024 * Some code fragments are present in 1.3.0 - 1.4.4.
1025 * @param array $mbx_ary
1027 * @param stream $imap_stream imap connection resource
1028 * @return object see mailboxes class
1031 function sqimap_fill_mailbox_tree($mbx_ary, $mbxs=false,$imap_stream) {
1032 global $data_dir, $username, $list_special_folders_first,
1033 $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
1034 $move_to_trash, $move_to_sent, $save_as_draft,
1035 $delimiter, $imap_server_type;
1037 // $special_folders = array ('INBOX', $sent_folder, $draft_folder, $trash_folder);
1039 /* create virtual root node */
1040 $mailboxes= new mailboxes();
1041 $mailboxes->is_root
= true;
1046 if (isset($folder_prefix) && ($folder_prefix != '')) {
1047 $start = substr_count($folder_prefix,$delimiter);
1048 if (strrpos($folder_prefix, $delimiter) == (strlen($folder_prefix)-1)) {
1049 $mailboxes->mailboxname_full
= substr($folder_prefix,0, (strlen($folder_prefix)-1));
1051 $mailboxes->mailboxname_full
= $folder_prefix;
1054 $mailboxes->mailboxname_sub
= $mailboxes->mailboxname_full
;
1059 $cnt = count($mbx_ary);
1060 for ($i=0; $i < $cnt; $i++
) {
1061 if ($mbx_ary[$i]['mbx'] !='' ) {
1062 $mbx = new mailboxes();
1063 $mailbox = $mbx_ary[$i]['mbx'];
1066 * Set the is_special flag if it concerned a special mailbox.
1067 * Used for displaying the special folders on top in the mailbox
1068 * tree displaying code.
1070 $mbx->is_special |
= ($mbx->is_inbox
= (strtoupper($mailbox) == 'INBOX'));
1071 $mbx->is_special |
= ($mbx->is_trash
= isTrashMailbox($mailbox));
1072 $mbx->is_special |
= ($mbx->is_sent
= isSentMailbox($mailbox));
1073 $mbx->is_special |
= ($mbx->is_draft
= isDraftMailbox($mailbox));
1075 if (!$mbx->is_special
)
1076 $mbx->is_special
= boolean_hook_function('special_mailbox', $mailbox, 1);
1078 if (isset($mbx_ary[$i]['unseen'])) {
1079 $mbx->unseen
= $mbx_ary[$i]['unseen'];
1081 if (isset($mbx_ary[$i]['nummessages'])) {
1082 $mbx->total
= $mbx_ary[$i]['nummessages'];
1085 $mbx->is_noselect
= $mbx_ary[$i]['noselect'];
1086 $mbx->is_noinferiors
= $mbx_ary[$i]['noinferiors'];
1088 $r_del_pos = strrpos($mbx_ary[$i]['mbx'], $delimiter);
1090 $mbx->mailboxname_sub
= substr($mbx_ary[$i]['mbx'],$r_del_pos+
1);
1091 } else { /* mailbox is root folder */
1092 $mbx->mailboxname_sub
= $mbx_ary[$i]['mbx'];
1094 $mbx->mailboxname_full
= $mbx_ary[$i]['mbx'];
1096 $mailboxes->addMbx($mbx, $delimiter, $start, $list_special_folders_first);
1099 sqimap_utf7_decode_mbx_tree($mailboxes);
1100 sqimap_get_status_mbx_tree($imap_stream,$mailboxes);
1105 * @param object $mbx_tree
1108 function sqimap_utf7_decode_mbx_tree(&$mbx_tree) {
1109 if (strtoupper($mbx_tree->mailboxname_full
) == 'INBOX')
1110 $mbx_tree->mailboxname_sub
= _("INBOX");
1112 $mbx_tree->mailboxname_sub
= imap_utf7_decode_local($mbx_tree->mailboxname_sub
);
1113 if ($mbx_tree->mbxs
) {
1114 $iCnt = count($mbx_tree->mbxs
);
1115 for ($i=0;$i<$iCnt;++
$i) {
1116 $mbxs_tree->mbxs
[$i] = sqimap_utf7_decode_mbx_tree($mbx_tree->mbxs
[$i]);
1122 * @param object $mbx_tree
1123 * @param array $aMbxs
1126 function sqimap_tree_to_ref_array(&$mbx_tree,&$aMbxs) {
1128 $aMbxs[] =& $mbx_tree;
1129 if ($mbx_tree->mbxs
) {
1130 $iCnt = count($mbx_tree->mbxs
);
1131 for ($i=0;$i<$iCnt;++
$i) {
1132 sqimap_tree_to_ref_array($mbx_tree->mbxs
[$i],$aMbxs);
1138 * @param stream $imap_stream imap connection resource
1139 * @param object $mbx_tree
1140 * @since since 1.5.0
1142 function sqimap_get_status_mbx_tree($imap_stream,&$mbx_tree) {
1143 global $unseen_notify, $unseen_type, $trash_folder,$move_to_trash;
1144 $aMbxs = $aQuery = array();
1145 sqimap_tree_to_ref_array($mbx_tree,$aMbxs);
1146 // remove the root node
1147 array_shift($aMbxs);
1149 if($unseen_notify == 3) {
1150 $cnt = count($aMbxs);
1151 for($i=0;$i<$cnt;++
$i) {
1152 $oMbx =& $aMbxs[$i];
1153 if (!$oMbx->is_noselect
) {
1154 $mbx = $oMbx->mailboxname_full
;
1155 if ($unseen_type == 2 ||
1156 ($move_to_trash && $oMbx->mailboxname_full
== $trash_folder)) {
1157 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (MESSAGES UNSEEN)';
1159 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (UNSEEN)';
1161 sqimap_prepare_pipelined_query($query,$tag,$aQuery,false);
1163 $oMbx->unseen
= $oMbx->total
= false;
1167 $aMbxs[$i] =& $oMbx;
1169 // execute all the queries at once
1170 $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
1171 $cnt = count($aMbxs);
1172 for($i=0;$i<$cnt;++
$i) {
1173 $oMbx =& $aMbxs[$i];
1175 if ($tag && $aServerResponse[$tag] == 'OK') {
1176 $sResponse = implode('', $aResponse[$tag]);
1177 if (preg_match('/UNSEEN\s+([0-9]+)/i', $sResponse, $regs)) {
1178 $oMbx->unseen
= $regs[1];
1180 if (preg_match('/MESSAGES\s+([0-9]+)/i', $sResponse, $regs)) {
1181 $oMbx->total
= $regs[1];
1186 } else if ($unseen_notify == 2) { // INBOX only
1187 $cnt = count($aMbxs);
1188 for($i=0;$i<$cnt;++
$i) {
1189 $oMbx =& $aMbxs[$i];
1190 if (strtoupper($oMbx->mailboxname_full
) == 'INBOX' ||
1191 ($move_to_trash && $oMbx->mailboxname_full
== $trash_folder)) {
1192 if ($unseen_type == 2 ||
1193 ($oMbx->mailboxname_full
== $trash_folder && $move_to_trash)) {
1194 $aStatus = sqimap_status_messages($imap_stream,$oMbx->mailboxname_full
);
1195 $oMbx->unseen
= $aStatus['UNSEEN'];
1196 $oMbx->total
= $aStatus['MESSAGES'];
1198 $oMbx->unseen
= sqimap_unseen_messages($imap_stream,$oMbx->mailboxname_full
);
1200 $aMbxs[$i] =& $oMbx;
1201 if (!$move_to_trash && $trash_folder) {
1204 // trash comes after INBOX
1205 if ($oMbx->mailboxname_full
== $trash_folder) {