128b27a1f2fa4c5d474a053e658f1af6e89c4e70
6 * This implements all functions that manipulate mailboxes
8 * @copyright © 1999-2005 The SquirrelMail Project Team
9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
11 * @package squirrelmail
16 if (! defined('SM_PATH')) define('SM_PATH','../');
19 require_once(SM_PATH
. 'functions/imap_utf7_local.php');
26 * FIXME. This class should be extracted and placed in a separate file that
27 * can be included before we start the session. That makes caching of the tree
28 * possible. On a refresh mailboxes from left_main.php the only function that
29 * should be called is the sqimap_get_status_mbx_tree. In case of subscribe
30 * / rename / delete / new we have to create methods for adding/changing the
31 * mailbox in the mbx_tree without the need for a refresh.
33 * Some code fragments are present in 1.3.0 - 1.4.4.
34 * @package squirrelmail
39 var $mailboxname_full = '', $mailboxname_sub= '', $is_noselect = false, $is_noinferiors = false,
40 $is_special = false, $is_root = false, $is_inbox = false, $is_sent = false,
41 $is_trash = false, $is_draft = false, $mbxs = array(),
42 $unseen = false, $total = false;
44 function addMbx($mbx, $delimiter, $start, $specialfirst) {
45 $ary = explode($delimiter, $mbx->mailboxname_full
);
47 for ($i = $start, $c = count($ary)-1; $i < $c; $i++
) {
48 $mbx_childs =& $mbx_parent->mbxs
;
51 foreach ($mbx_childs as $key => $parent) {
52 if ($parent->mailboxname_sub
== $ary[$i]) {
53 $mbx_parent =& $mbx_parent->mbxs
[$key];
60 $no_select_mbx = new mailboxes();
61 if (isset($mbx_parent->mailboxname_full
) && $mbx_parent->mailboxname_full
!= '') {
62 $no_select_mbx->mailboxname_full
= $mbx_parent->mailboxname_full
.$delimiter.$ary[$i];
64 $no_select_mbx->mailboxname_full
= $ary[$i];
66 $no_select_mbx->mailboxname_sub
= $ary[$i];
67 $no_select_mbx->is_noselect
= true;
68 $mbx_parent->mbxs
[] = $no_select_mbx;
72 $mbx_parent->mbxs
[] = $mbx;
73 if ($mbx->is_special
&& $specialfirst) {
74 usort($mbx_parent->mbxs
, 'sortSpecialMbx');
80 * array callback used for sorting in mailboxes class
83 * @return integer see php strnatcasecmp()
86 function sortSpecialMbx($a, $b) {
88 $acmp = '0'. $a->mailboxname_full
;
89 } else if ($a->is_special
) {
90 $acmp = '1'. $a->mailboxname_full
;
92 $acmp = '2' . $a->mailboxname_full
;
95 $bcmp = '0'. $b->mailboxname_full
;
96 }else if ($b->is_special
) {
97 $bcmp = '1' . $b->mailboxname_full
;
99 $bcmp = '2' . $b->mailboxname_full
;
101 return strnatcasecmp($acmp, $bcmp);
109 function compact_mailboxes_response($ary) {
111 * Workaround for mailboxes returned as literal
112 * FIXME : Doesn't work if the mailbox name is multiple lines
113 * (larger then fgets buffer)
115 for ($i = 0, $iCnt=count($ary); $i < $iCnt; $i++
) {
116 if (isset($ary[$i +
1]) && substr($ary[$i], -3) == "}\r\n") {
117 if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)$",
119 $ary[$i] = $regs[1] . '"' . addslashes(trim($ary[$i+
1])) . '"' . $regs[2];
120 array_splice($ary, $i+
1, 2);
124 /* remove duplicates and ensure array is contiguous */
125 return array_values(array_unique($ary));
129 * Extract the mailbox name from an untagged LIST (7.2.2) or LSUB (7.2.3) answer
130 * (LIST|LSUB) (<Flags list>) (NIL|"<separator atom>") <mailbox name string>\r\n
131 * mailbox name in quoted string MUST be unquoted and stripslashed (sm API)
133 * Originally stored in functions/strings.php. Since 1.2.6 stored in
134 * functions/imap_mailbox.php
135 * @param string $line imap LIST/LSUB response line
136 * @return string mailbox name
138 function find_mailbox_name($line) {
139 if (preg_match('/^\* (?:LIST|LSUB) \([^\)]*\) (?:NIL|\"[^\"]*\") ([^\r\n]*)[\r\n]*$/i', $line, $regs)) {
140 if (substr($regs[1], 0, 1) == '"')
141 return stripslashes(substr($regs[1], 1, -1));
148 * Detects if mailbox has noselect flag (can't store messages)
149 * In versions older than 1.4.5 function checks only LSUB responses
150 * and can produce pcre warnings.
151 * @param string $lsub_line mailbox line from untagged LIST or LSUB response
152 * @return bool whether this is a Noselect mailbox.
155 function check_is_noselect ($lsub_line) {
156 return preg_match("/^\* (LSUB|LIST) \([^\)]*\\\\Noselect[^\)]*\)/i", $lsub_line);
160 * Detects if mailbox has noinferiors flag (can't store subfolders)
161 * @param string $lsub_line mailbox line from untagged LIST or LSUB response
162 * @return bool whether this is a Noinferiors mailbox.
165 function check_is_noinferiors ($lsub_line) {
166 return preg_match("/^\* (LSUB|LIST) \([^\)]*\\\\Noinferiors[^\)]*\)/i", $lsub_line);
170 * Detects mailbox's parent folder
172 * If $haystack is a full mailbox name, and $needle is the mailbox
173 * separator character, returns the second last part of the full
174 * mailbox name (i.e. the mailbox's parent mailbox)
176 * Originally stored in functions/strings.php. Since 1.2.6 stored in
177 * functions/imap_mailbox.php
178 * @param string $haystack full mailbox name
179 * @param string $needle delimiter
180 * @return string parent mailbox
182 function readMailboxParent($haystack, $needle) {
186 $parts = explode($needle, $haystack);
187 $elem = array_pop($parts);
188 while ($elem == '' && count($parts)) {
189 $elem = array_pop($parts);
191 $ret = join($needle, $parts);
197 * Check if $subbox is below the specified $parentbox
198 * @param string $subbox potential sub folder
199 * @param string $parentbox potential parent
203 function isBoxBelow( $subbox, $parentbox ) {
206 * Eliminate the obvious mismatch, where the
207 * subfolder path is shorter than that of the potential parent
209 if ( strlen($subbox) < strlen($parentbox) ) {
212 /* check for delimiter */
213 if (substr($parentbox,-1) != $delimiter) {
214 $parentbox .= $delimiter;
217 return (substr($subbox,0,strlen($parentbox)) == $parentbox);
221 * Defines special mailboxes: given a mailbox name, it checks if this is a
222 * "special" one: INBOX, Trash, Sent or Draft.
224 * Since 1.2.5 function includes special_mailbox hook.<br>
225 * Since 1.4.3 hook supports more than one plugin.
226 * @param string $box mailbox name
230 function isSpecialMailbox( $box ) {
231 $ret = ( (strtolower($box) == 'inbox') ||
232 isTrashMailbox($box) ||
isSentMailbox($box) ||
isDraftMailbox($box) );
235 $ret = boolean_hook_function('special_mailbox',$box,1);
241 * Detects if mailbox is a Trash folder or subfolder of Trash
242 * @param string $box mailbox name
243 * @return bool whether this is a Trash folder
246 function isTrashMailbox ($box) {
247 global $trash_folder, $move_to_trash;
248 return $move_to_trash && $trash_folder &&
249 ( $box == $trash_folder ||
isBoxBelow($box, $trash_folder) );
253 * Detects if mailbox is a Sent folder or subfolder of Sent
254 * @param string $box mailbox name
255 * @return bool whether this is a Sent folder
258 function isSentMailbox($box) {
259 global $sent_folder, $move_to_sent;
260 return $move_to_sent && $sent_folder &&
261 ( $box == $sent_folder ||
isBoxBelow($box, $sent_folder) );
265 * Detects if mailbox is a Drafts folder or subfolder of Drafts
266 * @param string $box mailbox name
267 * @return bool whether this is a Draft folder
270 function isDraftMailbox($box) {
271 global $draft_folder, $save_as_draft;
272 return $save_as_draft &&
273 ( $box == $draft_folder ||
isBoxBelow($box, $draft_folder) );
279 * WARNING: Select mailbox before calling this function.
281 * permanently removes all messages that have the \Deleted flag
282 * set from the selected mailbox. See EXPUNGE command chapter in
284 * @param stream $imap_stream imap connection resource
285 * @param string $mailbox mailbox name (unused since 1.1.3).
286 * @param boolean $handle_errors error handling control (displays error_box on error).
287 * @param mixed $id (since 1.3.0) integer message id or array with integer ids
288 * @return integer number of expunged messages
289 * @since 1.0 or older
291 function sqimap_mailbox_expunge ($imap_stream, $mailbox, $handle_errors = true, $id='') {
294 $id = sqimap_message_list_squisher($id);
301 $read = sqimap_run_command($imap_stream, 'EXPUNGE'.$id, $handle_errors,
302 $response, $message, $uid);
305 if (is_array($read)) {
306 foreach ($read as $r) {
307 if (preg_match('/^\*\s[0-9]+\sEXPUNGE/AUi',$r,$regs)) {
316 * Checks whether or not the specified mailbox exists
317 * @param stream $imap_stream imap connection resource
318 * @param string $mailbox mailbox name
320 * @since 1.0 or older
322 function sqimap_mailbox_exists ($imap_stream, $mailbox) {
323 if (!isset($mailbox) ||
empty($mailbox)) {
326 $mbx = sqimap_run_command($imap_stream, 'LIST "" ' . sqimap_encode_mailbox_name($mailbox),
327 true, $response, $message);
328 return isset($mbx[0]);
333 * Before 1.3.0 used more arguments and returned data depended on those argumements.
334 * @param stream $imap_stream imap connection resource
335 * @param string $mailbox mailbox name
336 * @return array results of select command (on success - permanentflags, flags and rights)
337 * @since 1.0 or older
339 function sqimap_mailbox_select ($imap_stream, $mailbox) {
340 if ($mailbox == 'None') {
344 $read = sqimap_run_command($imap_stream, 'SELECT ' . sqimap_encode_mailbox_name($mailbox),
345 true, $response, $message);
347 for ($i = 0, $cnt = count($read); $i < $cnt; $i++
) {
348 if (preg_match('/^\*\s+OK\s\[(\w+)\s(\w+)\]/',$read[$i], $regs)) {
349 $result[strtoupper($regs[1])] = $regs[2];
350 } else if (preg_match('/^\*\s([0-9]+)\s(\w+)/',$read[$i], $regs)) {
351 $result[strtoupper($regs[2])] = $regs[1];
353 if (preg_match("/PERMANENTFLAGS(.*)/i",$read[$i], $regs)) {
354 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/","/\]/") ,'', $regs[1])) ;
355 $result['PERMANENTFLAGS'] = explode(' ',strtolower($regs[1]));
356 } else if (preg_match("/FLAGS(.*)/i",$read[$i], $regs)) {
357 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/") ,'', $regs[1])) ;
358 $result['FLAGS'] = explode(' ',strtolower($regs[1]));
362 if (!isset($result['PERMANENTFLAGS'])) {
363 $result['PERMANENTFLAGS'] = $result['FLAGS'];
365 if (preg_match('/^\[(.+)\]/',$message, $regs)) {
366 $result['RIGHTS']=strtoupper($regs[1]);
375 * Mailbox is automatically subscribed.
377 * Set $type to string that does not match 'noselect' (case insensitive),
378 * if you don't want to prepend delimiter to mailbox name. Please note
379 * that 'noinferiors' might be used someday as keyword for folders
380 * that store only messages.
381 * @param stream $imap_steam imap connection resource
382 * @param string $mailbox mailbox name
383 * @param string $type folder type.
384 * @since 1.0 or older
386 function sqimap_mailbox_create ($imap_stream, $mailbox, $type) {
388 if (strtolower($type) == 'noselect') {
389 $mailbox .= $delimiter;
392 $read_ary = sqimap_run_command($imap_stream, 'CREATE ' .
393 sqimap_encode_mailbox_name($mailbox),
394 true, $response, $message);
395 sqimap_subscribe ($imap_stream, $mailbox);
399 * Subscribes to an existing folder.
400 * @param stream $imap_stream imap connection resource
401 * @param string $mailbox mailbox name
402 * @param boolean $debug (since 1.5.1)
403 * @since 1.0 or older
405 function sqimap_subscribe ($imap_stream, $mailbox,$debug=true) {
406 $read_ary = sqimap_run_command($imap_stream, 'SUBSCRIBE ' .
407 sqimap_encode_mailbox_name($mailbox),
408 $debug, $response, $message);
412 * Unsubscribes from an existing folder
413 * @param stream $imap_stream imap connection resource
414 * @param string $mailbox mailbox name
415 * @since 1.0 or older
417 function sqimap_unsubscribe ($imap_stream, $mailbox) {
418 $read_ary = sqimap_run_command($imap_stream, 'UNSUBSCRIBE ' .
419 sqimap_encode_mailbox_name($mailbox),
420 false, $response, $message);
424 * Deletes the given folder
425 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
426 * @param stream $imap_stream imap connection resource
427 * @param string $mailbox mailbox name
428 * @since 1.0 or older
430 function sqimap_mailbox_delete ($imap_stream, $mailbox) {
431 global $data_dir, $username;
432 sqimap_unsubscribe ($imap_stream, $mailbox);
434 if (sqimap_mailbox_exists($imap_stream, $mailbox)) {
436 $read_ary = sqimap_run_command($imap_stream, 'DELETE ' .
437 sqimap_encode_mailbox_name($mailbox),
438 true, $response, $message);
439 if ($response !== 'OK') {
441 sqimap_subscribe ($imap_stream, $mailbox);
443 do_hook_function('rename_or_delete_folder', $args = array($mailbox, 'delete', ''));
444 removePref($data_dir, $username, "thread_$mailbox");
445 removePref($data_dir, $username, "collapse_folder_$mailbox");
451 * Determines if the user is subscribed to the folder or not
452 * @param stream $imap_stream imap connection resource
453 * @param string $mailbox mailbox name
457 function sqimap_mailbox_is_subscribed($imap_stream, $folder) {
458 $boxesall = sqimap_mailbox_list ($imap_stream);
459 foreach ($boxesall as $ref) {
460 if ($ref['unformatted'] == $folder) {
469 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
470 * @param stream $imap_stream imap connection resource
471 * @param string $old_name mailbox name
472 * @param string $new_name new mailbox name
475 function sqimap_mailbox_rename( $imap_stream, $old_name, $new_name ) {
476 if ( $old_name != $new_name ) {
477 global $delimiter, $imap_server_type, $data_dir, $username;
478 if ( substr( $old_name, -1 ) == $delimiter ) {
479 $old_name = substr( $old_name, 0, strlen( $old_name ) - 1 );
480 $new_name = substr( $new_name, 0, strlen( $new_name ) - 1 );
481 $postfix = $delimiter;
486 $boxesall = sqimap_mailbox_list_all($imap_stream);
487 $cmd = 'RENAME ' . sqimap_encode_mailbox_name($old_name) .
488 ' ' . sqimap_encode_mailbox_name($new_name);
489 $data = sqimap_run_command($imap_stream, $cmd, true, $response, $message);
490 sqimap_unsubscribe($imap_stream, $old_name.$postfix);
491 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$old_name.$postfix);
492 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
493 removePref($data_dir, $username, 'thread_'.$old_name.$postfix);
494 removePref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
495 sqimap_subscribe($imap_stream, $new_name.$postfix);
496 setPref($data_dir, $username, 'thread_'.$new_name.$postfix, $oldpref_thread);
497 setPref($data_dir, $username, 'collapse_folder_'.$new_name.$postfix, $oldpref_collapse);
498 do_hook_function('rename_or_delete_folder',$args = array($old_name, 'rename', $new_name));
499 $l = strlen( $old_name ) +
1;
502 foreach ($boxesall as $box) {
503 if (substr($box[$p], 0, $l) == $old_name . $delimiter) {
504 $new_sub = $new_name . $delimiter . substr($box[$p], $l);
505 /* With Cyrus IMAPd >= 2.0 rename is recursive, so don't check for errors here */
506 if ($imap_server_type == 'cyrus') {
507 $cmd = 'RENAME "' . $box[$p] . '" "' . $new_sub . '"';
508 $data = sqimap_run_command($imap_stream, $cmd, false,
509 $response, $message);
511 $was_subscribed = sqimap_mailbox_is_subscribed($imap_stream, $box[$p]);
512 if ( $was_subscribed ) {
513 sqimap_unsubscribe($imap_stream, $box[$p]);
515 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$box[$p]);
516 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$box[$p]);
517 removePref($data_dir, $username, 'thread_'.$box[$p]);
518 removePref($data_dir, $username, 'collapse_folder_'.$box[$p]);
519 if ( $was_subscribed ) {
520 sqimap_subscribe($imap_stream, $new_sub);
522 setPref($data_dir, $username, 'thread_'.$new_sub, $oldpref_thread);
523 setPref($data_dir, $username, 'collapse_folder_'.$new_sub, $oldpref_collapse);
524 do_hook_function('rename_or_delete_folder',
525 $args = array($box[$p], 'rename', $new_sub));
532 * Formats a mailbox into parts for the $boxesall array
536 * <li>raw - Raw LIST/LSUB response from the IMAP server
537 * <li>formatted - nicely formatted folder name
538 * <li>unformatted - unformatted, but with delimiter at end removed
539 * <li>unformatted-dm - folder name as it appears in raw response
540 * <li>unformatted-disp - unformatted without $folder_prefix
541 * <li>id - TODO: document me
542 * <li>flags - TODO: document me
544 * Before 1.2.0 used third argument for delimiter.
548 * @since 1.0 or older
549 * @todo document id and flags keys in boxes array and function arguments.
551 function sqimap_mailbox_parse ($line, $line_lsub) {
552 global $folder_prefix, $delimiter;
554 /* Process each folder line */
555 for ($g = 0, $cnt = count($line); $g < $cnt; ++
$g) {
556 /* Store the raw IMAP reply */
557 if (isset($line[$g])) {
558 $boxesall[$g]['raw'] = $line[$g];
560 $boxesall[$g]['raw'] = '';
563 /* Count number of delimiters ($delimiter) in folder name */
564 $mailbox = /*trim(*/$line_lsub[$g]/*)*/;
565 $dm_count = substr_count($mailbox, $delimiter);
566 if (substr($mailbox, -1) == $delimiter) {
567 /* If name ends in delimiter, decrement count by one */
571 /* Format folder name, but only if it's a INBOX.* or has a parent. */
572 $boxesallbyname[$mailbox] = $g;
573 $parentfolder = readMailboxParent($mailbox, $delimiter);
574 if ( (strtolower(substr($mailbox, 0, 5)) == "inbox") ||
575 (substr($mailbox, 0, strlen($folder_prefix)) == $folder_prefix) ||
576 (isset($boxesallbyname[$parentfolder]) &&
577 (strlen($parentfolder) > 0) ) ) {
578 $indent = $dm_count - (substr_count($folder_prefix, $delimiter));
580 $boxesall[$g]['formatted'] = str_repeat(' ', $indent);
582 $boxesall[$g]['formatted'] = '';
584 $boxesall[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
586 $boxesall[$g]['formatted'] = imap_utf7_decode_local($mailbox);
589 $boxesall[$g]['unformatted-dm'] = $mailbox;
590 if (substr($mailbox, -1) == $delimiter) {
591 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
593 $boxesall[$g]['unformatted'] = $mailbox;
594 if (substr($mailbox,0,strlen($folder_prefix))==$folder_prefix) {
595 $mailbox = substr($mailbox, strlen($folder_prefix));
597 $boxesall[$g]['unformatted-disp'] = $mailbox;
598 $boxesall[$g]['id'] = $g;
600 $boxesall[$g]['flags'] = array();
601 if (isset($line[$g])) {
602 ereg("\(([^)]*)\)",$line[$g],$regs);
603 // FIXME Flags do contain the \ character. \NoSelect \NoInferiors
604 // and $MDNSent <= last one doesn't have the \
605 // It's better to follow RFC3501 instead of using our own naming.
606 $flags = trim(strtolower(str_replace('\\', '',$regs[1])));
608 $boxesall[$g]['flags'] = explode(' ', $flags);
616 * Returns list of options (to be echoed into select statement
617 * based on available mailboxes and separators
618 * Caller should surround options with <select ...> </select> and
620 * @param stream $imap_stream imap connection resource to query for mailboxes
621 * @param array $show_selected array containing list of mailboxes to pre-select (0 if none)
622 * @param array $folder_skip array of folders to keep out of option list (compared in lower)
623 * @param $boxes list of already fetched boxes (for places like folder panel, where
624 * you know these options will be shown 3 times in a row.. (most often unset).
625 * @param string $flag (since 1.4.1) flag to check for in mailbox flags, used to filter out mailboxes.
626 * 'noselect' by default to remove unselectable mailboxes.
627 * 'noinferiors' used to filter out folders that can not contain subfolders.
628 * NULL to avoid flag check entirely.
629 * NOTE: noselect and noiferiors are used internally. The IMAP representation is
630 * \NoSelect and \NoInferiors
631 * @param boolean $use_long_format (since 1.4.1) override folder display preference and always show full folder name.
632 * @return string html formated mailbox selection options
635 function sqimap_mailbox_option_list($imap_stream, $show_selected = 0, $folder_skip = 0, $boxes = 0,
636 $flag = 'noselect', $use_long_format = false ) {
637 global $username, $data_dir;
639 if ( $use_long_format ) {
640 $shorten_box_names = 0;
642 $shorten_box_names = getPref($data_dir, $username, 'mailbox_select_style', SMPREF_OFF
);
646 $boxes = sqimap_mailbox_list($imap_stream);
649 foreach ($boxes as $boxes_part) {
650 if ($flag == NULL ||
(is_array($boxes_part['flags'])
651 && !in_array($flag, $boxes_part['flags']))) {
652 $box = $boxes_part['unformatted'];
654 if ($folder_skip != 0 && in_array($box, $folder_skip) ) {
657 $lowerbox = strtolower($box);
658 // mailboxes are casesensitive => inbox.sent != inbox.Sent
659 // nevermind, to many dependencies this should be fixed!
661 if (strtolower($box) == 'inbox') { // inbox is special and not casesensitive
664 switch ($shorten_box_names)
666 case 2: /* delimited, style = 2 */
667 $box2 = str_replace('&nbsp;&nbsp;', '. ', htmlspecialchars($boxes_part['formatted']));
669 case 1: /* indent, style = 1 */
670 $box2 = str_replace('&nbsp;&nbsp;', ' ', htmlspecialchars($boxes_part['formatted']));
672 default: /* default, long names, style = 0 */
673 $box2 = str_replace(' ', ' ', htmlspecialchars(imap_utf7_decode_local($boxes_part['unformatted-disp'])));
677 if ($show_selected != 0 && in_array($lowerbox, $show_selected) ) {
678 $mbox_options .= '<option value="' . htmlspecialchars($box) .'" selected="selected">'.$box2.'</option>' . "\n";
680 $mbox_options .= '<option value="' . htmlspecialchars($box) .'">'.$box2.'</option>' . "\n";
684 return $mbox_options;
688 * Returns sorted mailbox lists in several different ways.
689 * See comment on sqimap_mailbox_parse() for info about the returned array.
690 * @param resource $imap_stream imap connection resource
691 * @param boolean $force force update of mailbox listing. available since 1.4.2 and 1.5.0
692 * @return array list of mailboxes
693 * @since 1.0 or older
695 function sqimap_mailbox_list($imap_stream, $force=false) {
696 if (!sqgetGlobalVar('boxesnew',$boxesnew,SQ_SESSION
) ||
$force) {
697 global $data_dir, $username, $list_special_folders_first,
698 $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
699 $move_to_trash, $move_to_sent, $save_as_draft,
700 $delimiter, $noselect_fix_enable, $imap_server_type,
701 $show_only_subscribed_folders;
702 $inbox_subscribed = false;
703 $listsubscribed = sqimap_capability($imap_stream,'LIST-SUBSCRIBED');
705 require_once(SM_PATH
. 'include/load_prefs.php');
707 if (!$show_only_subscribed_folders) {
709 } elseif ($listsubscribed) {
710 $lsub = 'LIST (SUBSCRIBED)';
715 if ($noselect_fix_enable) {
716 $lsub_args = "$lsub \"$folder_prefix\" \"*%\"";
718 $lsub_args = "$lsub \"$folder_prefix\" \"*\"";
721 $lsub_ary = sqimap_run_command ($imap_stream, $lsub_args,
722 true, $response, $message);
723 $lsub_ary = compact_mailboxes_response($lsub_ary);
725 $sorted_lsub_ary = array();
726 for ($i = 0, $cnt = count($lsub_ary);$i < $cnt; $i++
) {
728 $temp_mailbox_name = find_mailbox_name($lsub_ary[$i]);
729 $sorted_lsub_ary[] = $temp_mailbox_name;
730 if (!$inbox_subscribed && strtoupper($temp_mailbox_name) == 'INBOX') {
731 $inbox_subscribed = true;
735 /* natural sort mailboxes */
736 if (isset($sorted_lsub_ary)) {
737 usort($sorted_lsub_ary, 'strnatcasecmp');
740 * The LSUB response doesn't provide us information about \Noselect
741 * mail boxes. The LIST response does, that's why we need to do a LIST
742 * call to retrieve the flags for the mailbox
743 * Note: according RFC2060 an imap server may provide \NoSelect flags in the LSUB response.
744 * in other words, we cannot rely on it.
746 $sorted_list_ary = array();
747 // if (!$listsubscribed) {
748 for ($i=0; $i < count($sorted_lsub_ary); $i++
) {
749 if (substr($sorted_lsub_ary[$i], -1) == $delimiter) {
750 $mbx = substr($sorted_lsub_ary[$i], 0, strlen($sorted_lsub_ary[$i])-1);
753 $mbx = $sorted_lsub_ary[$i];
756 $read = sqimap_run_command ($imap_stream, 'LIST "" ' . sqimap_encode_mailbox_name($mbx),
757 true, $response, $message);
759 $read = compact_mailboxes_response($read);
761 if (isset($read[0])) {
762 $sorted_list_ary[$i] = $read[0];
764 $sorted_list_ary[$i] = '';
769 * Just in case they're not subscribed to their inbox,
770 * we'll get it for them anyway
772 if (!$inbox_subscribed) {
773 $inbox_ary = sqimap_run_command ($imap_stream, 'LIST "" "INBOX"',
774 true, $response, $message);
775 $sorted_list_ary[] = implode('',compact_mailboxes_response($inbox_ary));
776 $sorted_lsub_ary[] = find_mailbox_name($inbox_ary[0]);
779 $boxesall = sqimap_mailbox_parse ($sorted_list_ary, $sorted_lsub_ary);
781 /* Now, lets sort for special folders */
782 $boxesnew = $used = array();
785 $cnt = count($boxesall);
786 $used = array_pad($used,$cnt,false);
787 for($k = 0; $k < $cnt; ++
$k) {
788 if (strtolower($boxesall[$k]['unformatted']) == 'inbox') {
789 $boxesnew[] = $boxesall[$k];
794 /* List special folders and their subfolders, if requested. */
795 if ($list_special_folders_first) {
796 for($k = 0; $k < $cnt; ++
$k) {
797 if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
798 $boxesnew[] = $boxesall[$k];
804 /* Find INBOX's children */
805 for($k = 0; $k < $cnt; ++
$k) {
806 if (!$used[$k] && isBoxBelow(strtolower($boxesall[$k]['unformatted']), 'inbox') &&
807 strtolower($boxesall[$k]['unformatted']) != 'inbox') {
808 $boxesnew[] = $boxesall[$k];
813 /* Rest of the folders */
814 for($k = 0; $k < $cnt; $k++
) {
816 $boxesnew[] = $boxesall[$k];
819 sqsession_register($boxesnew,'boxesnew');
825 * Returns a list of all folders, subscribed or not
826 * @param stream $imap_stream imap connection resource
827 * @return array see sqimap_mailbox_parse()
828 * @since 1.0 or older
830 function sqimap_mailbox_list_all($imap_stream) {
831 global $list_special_folders_first, $folder_prefix, $delimiter;
833 $read_ary = sqimap_run_command($imap_stream,"LIST \"$folder_prefix\" *",true,$response, $message,false);
834 $read_ary = compact_mailboxes_response($read_ary);
837 $fld_pre_length = strlen($folder_prefix);
838 for ($i = 0, $cnt = count($read_ary); $i < $cnt; $i++
) {
839 /* Store the raw IMAP reply */
840 $boxes[$g]['raw'] = $read_ary[$i];
842 /* Count number of delimiters ($delimiter) in folder name */
843 $mailbox = find_mailbox_name($read_ary[$i]);
844 $dm_count = substr_count($mailbox, $delimiter);
845 if (substr($mailbox, -1) == $delimiter) {
846 /* If name ends in delimiter - decrement count by one */
850 /* Format folder name, but only if it's a INBOX.* or has a parent. */
851 $boxesallbyname[$mailbox] = $g;
852 $parentfolder = readMailboxParent($mailbox, $delimiter);
853 if((eregi('^inbox'.quotemeta($delimiter), $mailbox)) ||
854 (ereg('^'.$folder_prefix, $mailbox)) ||
855 ( isset($boxesallbyname[$parentfolder]) && (strlen($parentfolder) > 0) ) ) {
857 $boxes[$g]['formatted'] = str_repeat(' ', $dm_count);
859 $boxes[$g]['formatted'] = '';
861 $boxes[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
863 $boxes[$g]['formatted'] = imap_utf7_decode_local($mailbox);
866 $boxes[$g]['unformatted-dm'] = $mailbox;
867 if (substr($mailbox, -1) == $delimiter) {
868 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
870 $boxes[$g]['unformatted'] = $mailbox;
871 $boxes[$g]['unformatted-disp'] = substr($mailbox,$fld_pre_length);
873 $boxes[$g]['id'] = $g;
875 /* Now lets get the flags for this mailbox */
876 $read_mlbx = $read_ary[$i];
877 $flags = substr($read_mlbx, strpos($read_mlbx, '(')+
1);
878 $flags = substr($flags, 0, strpos($flags, ')'));
879 $flags = str_replace('\\', '', $flags);
880 $flags = trim(strtolower($flags));
882 $boxes[$g]['flags'] = explode(' ', $flags);
884 $boxes[$g]['flags'] = array();
888 if(is_array($boxes)) {
896 * Fills mailbox object
898 * Some code fragments are present in 1.3.0 - 1.4.4.
899 * @param stream $imap_stream imap connection resource
900 * @return object see mailboxes class.
903 function sqimap_mailbox_tree($imap_stream) {
904 global $default_folder_prefix, $data_dir, $username, $list_special_folders_first,
905 $folder_prefix, $delimiter, $trash_folder, $move_to_trash,
906 $imap_server_type, $show_only_subscribed_folders;
908 // TODO: implement mailbox tree caching. maybe store object in session?
911 $noinferiors = false;
913 require_once(SM_PATH
. 'include/load_prefs.php');
915 if ($show_only_subscribed_folders) {
922 $lsub_ary = sqimap_run_command ($imap_stream, "$lsub_cmd \"$folder_prefix\" \"*\"",
923 true, $response, $message);
924 $lsub_ary = compact_mailboxes_response($lsub_ary);
926 /* Check to see if we have an INBOX */
929 for ($i = 0, $cnt = count($lsub_ary); $i < $cnt; $i++
) {
930 if (preg_match("/^\*\s+$lsub_cmd.*\s\"?INBOX\"?\s*$/i",$lsub_ary[$i])) {
931 $lsub_ary[$i] = strtoupper($lsub_ary[$i]);
932 // in case of an unsubscribed inbox an imap server can
933 // return the inbox in the lsub results with a \NoSelect
935 if (!preg_match("/\*\s+$lsub_cmd\s+\(.*\\\\NoSelect.*\).*/i",$lsub_ary[$i])) {
938 // remove the result and request it again with a list
939 // response at a later stage.
940 unset($lsub_ary[$i]);
941 // re-index the array otherwise the addition of the LIST
942 // response will fail in PHP 4.1.2 and probably other older versions
943 $lsub_ary = array_values($lsub_ary);
949 if ($has_inbox == false) {
950 // do a list request for inbox because we should always show
951 // inbox even if the user isn't subscribed to it.
952 $inbox_ary = sqimap_run_command ($imap_stream, 'LIST "" "INBOX"',
953 true, $response, $message);
954 $inbox_ary = compact_mailboxes_response($inbox_ary);
955 if (count($inbox_ary)) {
956 $lsub_ary[] = $inbox_ary[0];
961 * Section about removing the last element was removed
962 * We don't return "* OK" anymore from sqimap_read_data
965 $sorted_lsub_ary = array();
966 $cnt = count($lsub_ary);
967 for ($i = 0; $i < $cnt; $i++
) {
968 $mbx = find_mailbox_name($lsub_ary[$i]);
970 // only do the noselect test if !uw, is checked later. FIX ME see conf.pl setting
971 if ($imap_server_type != "uw") {
972 $noselect = check_is_noselect($lsub_ary[$i]);
973 $noinferiors = check_is_noinferiors($lsub_ary[$i]);
975 if (substr($mbx, -1) == $delimiter) {
976 $mbx = substr($mbx, 0, strlen($mbx) - 1);
978 $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
980 // FIX ME this requires a config setting inside conf.pl instead of checking on server type
981 if ($imap_server_type == "uw") {
984 // prepare an array with queries
985 foreach ($sorted_lsub_ary as $aMbx) {
986 $mbx = stripslashes($aMbx['mbx']);
987 sqimap_prepare_pipelined_query('LIST "" ' . sqimap_encode_mailbox_name($mbx), $tag, $aQuery, false);
990 $sorted_lsub_ary = array();
991 // execute all the queries at once
992 $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
993 foreach($aTag as $tag => $mbx) {
994 if ($aServerResponse[$tag] == 'OK') {
995 $sResponse = implode('', $aResponse[$tag]);
996 $noselect = check_is_noselect($sResponse);
997 $noinferiors = check_is_noinferiors($sResponse);
998 $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
1001 $cnt = count($sorted_lsub_ary);
1003 $sorted_lsub_ary = array_values($sorted_lsub_ary);
1004 usort($sorted_lsub_ary, 'mbxSort');
1005 $boxestree = sqimap_fill_mailbox_tree($sorted_lsub_ary,false,$imap_stream);
1010 * Callback function used for sorting mailboxes in sqimap_mailbox_tree
1013 * @return integer see php strnatcasecmp()
1016 function mbxSort($a, $b) {
1017 return strnatcasecmp($a['mbx'], $b['mbx']);
1021 * Fills mailbox object
1023 * Some code fragments are present in 1.3.0 - 1.4.4.
1024 * @param array $mbx_ary
1026 * @param stream $imap_stream imap connection resource
1027 * @return object see mailboxes class
1030 function sqimap_fill_mailbox_tree($mbx_ary, $mbxs=false,$imap_stream) {
1031 global $data_dir, $username, $list_special_folders_first,
1032 $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
1033 $move_to_trash, $move_to_sent, $save_as_draft,
1034 $delimiter, $imap_server_type;
1036 // $special_folders = array ('INBOX', $sent_folder, $draft_folder, $trash_folder);
1038 /* create virtual root node */
1039 $mailboxes= new mailboxes();
1040 $mailboxes->is_root
= true;
1045 if (isset($folder_prefix) && ($folder_prefix != '')) {
1046 $start = substr_count($folder_prefix,$delimiter);
1047 if (strrpos($folder_prefix, $delimiter) == (strlen($folder_prefix)-1)) {
1048 $mailboxes->mailboxname_full
= substr($folder_prefix,0, (strlen($folder_prefix)-1));
1050 $mailboxes->mailboxname_full
= $folder_prefix;
1053 $mailboxes->mailboxname_sub
= $mailboxes->mailboxname_full
;
1058 $cnt = count($mbx_ary);
1059 for ($i=0; $i < $cnt; $i++
) {
1060 if ($mbx_ary[$i]['mbx'] !='' ) {
1061 $mbx = new mailboxes();
1062 $mailbox = $mbx_ary[$i]['mbx'];
1065 * Set the is_special flag if it concerned a special mailbox.
1066 * Used for displaying the special folders on top in the mailbox
1067 * tree displaying code.
1069 $mbx->is_special |
= ($mbx->is_inbox
= (strtoupper($mailbox) == 'INBOX'));
1070 $mbx->is_special |
= ($mbx->is_trash
= isTrashMailbox($mailbox));
1071 $mbx->is_special |
= ($mbx->is_sent
= isSentMailbox($mailbox));
1072 $mbx->is_special |
= ($mbx->is_draft
= isDraftMailbox($mailbox));
1074 if (!$mbx->is_special
)
1075 $mbx->is_special
= boolean_hook_function('special_mailbox', $mailbox, 1);
1077 if (isset($mbx_ary[$i]['unseen'])) {
1078 $mbx->unseen
= $mbx_ary[$i]['unseen'];
1080 if (isset($mbx_ary[$i]['nummessages'])) {
1081 $mbx->total
= $mbx_ary[$i]['nummessages'];
1084 $mbx->is_noselect
= $mbx_ary[$i]['noselect'];
1085 $mbx->is_noinferiors
= $mbx_ary[$i]['noinferiors'];
1087 $r_del_pos = strrpos($mbx_ary[$i]['mbx'], $delimiter);
1089 $mbx->mailboxname_sub
= substr($mbx_ary[$i]['mbx'],$r_del_pos+
1);
1090 } else { /* mailbox is root folder */
1091 $mbx->mailboxname_sub
= $mbx_ary[$i]['mbx'];
1093 $mbx->mailboxname_full
= $mbx_ary[$i]['mbx'];
1095 $mailboxes->addMbx($mbx, $delimiter, $start, $list_special_folders_first);
1098 sqimap_utf7_decode_mbx_tree($mailboxes);
1099 sqimap_get_status_mbx_tree($imap_stream,$mailboxes);
1104 * @param object $mbx_tree
1107 function sqimap_utf7_decode_mbx_tree(&$mbx_tree) {
1108 if (strtoupper($mbx_tree->mailboxname_full
) == 'INBOX')
1109 $mbx_tree->mailboxname_sub
= _("INBOX");
1111 $mbx_tree->mailboxname_sub
= imap_utf7_decode_local($mbx_tree->mailboxname_sub
);
1112 if ($mbx_tree->mbxs
) {
1113 $iCnt = count($mbx_tree->mbxs
);
1114 for ($i=0;$i<$iCnt;++
$i) {
1115 $mbxs_tree->mbxs
[$i] = sqimap_utf7_decode_mbx_tree($mbx_tree->mbxs
[$i]);
1121 * @param object $mbx_tree
1122 * @param array $aMbxs
1125 function sqimap_tree_to_ref_array(&$mbx_tree,&$aMbxs) {
1127 $aMbxs[] =& $mbx_tree;
1128 if ($mbx_tree->mbxs
) {
1129 $iCnt = count($mbx_tree->mbxs
);
1130 for ($i=0;$i<$iCnt;++
$i) {
1131 sqimap_tree_to_ref_array($mbx_tree->mbxs
[$i],$aMbxs);
1137 * @param stream $imap_stream imap connection resource
1138 * @param object $mbx_tree
1139 * @since since 1.5.0
1141 function sqimap_get_status_mbx_tree($imap_stream,&$mbx_tree) {
1142 global $unseen_notify, $unseen_type, $trash_folder,$move_to_trash;
1143 $aMbxs = $aQuery = array();
1144 sqimap_tree_to_ref_array($mbx_tree,$aMbxs);
1145 // remove the root node
1146 array_shift($aMbxs);
1148 if($unseen_notify == 3) {
1149 $cnt = count($aMbxs);
1150 for($i=0;$i<$cnt;++
$i) {
1151 $oMbx =& $aMbxs[$i];
1152 if (!$oMbx->is_noselect
) {
1153 $mbx = $oMbx->mailboxname_full
;
1154 if ($unseen_type == 2 ||
1155 ($move_to_trash && $oMbx->mailboxname_full
== $trash_folder)) {
1156 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (MESSAGES UNSEEN)';
1158 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (UNSEEN)';
1160 sqimap_prepare_pipelined_query($query,$tag,$aQuery,false);
1162 $oMbx->unseen
= $oMbx->total
= false;
1166 $aMbxs[$i] =& $oMbx;
1168 // execute all the queries at once
1169 $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
1170 $cnt = count($aMbxs);
1171 for($i=0;$i<$cnt;++
$i) {
1172 $oMbx =& $aMbxs[$i];
1174 if ($tag && $aServerResponse[$tag] == 'OK') {
1175 $sResponse = implode('', $aResponse[$tag]);
1176 if (preg_match('/UNSEEN\s+([0-9]+)/i', $sResponse, $regs)) {
1177 $oMbx->unseen
= $regs[1];
1179 if (preg_match('/MESSAGES\s+([0-9]+)/i', $sResponse, $regs)) {
1180 $oMbx->total
= $regs[1];
1185 } else if ($unseen_notify == 2) { // INBOX only
1186 $cnt = count($aMbxs);
1187 for($i=0;$i<$cnt;++
$i) {
1188 $oMbx =& $aMbxs[$i];
1189 if (strtoupper($oMbx->mailboxname_full
) == 'INBOX' ||
1190 ($move_to_trash && $oMbx->mailboxname_full
== $trash_folder)) {
1191 if ($unseen_type == 2 ||
1192 ($oMbx->mailboxname_full
== $trash_folder && $move_to_trash)) {
1193 $aStatus = sqimap_status_messages($imap_stream,$oMbx->mailboxname_full
);
1194 $oMbx->unseen
= $aStatus['UNSEEN'];
1195 $oMbx->total
= $aStatus['MESSAGES'];
1197 $oMbx->unseen
= sqimap_unseen_messages($imap_stream,$oMbx->mailboxname_full
);
1199 $aMbxs[$i] =& $oMbx;
1200 if (!$move_to_trash && $trash_folder) {
1203 // trash comes after INBOX
1204 if ($oMbx->mailboxname_full
== $trash_folder) {