6 * This implements all functions that manipulate mailboxes
8 * @copyright © 1999-2006 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, $recent = 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
318 * @param stream $imap_stream imap connection resource
319 * @param string $mailbox mailbox name
320 * @param array $mailboxlist (since 1.5.1) optional array of mailboxes from
321 * sqimap_get_mailboxes() (to avoid having to talk to imap server)
323 * @since 1.0 or older
325 function sqimap_mailbox_exists ($imap_stream, $mailbox, $mailboxlist=null) {
326 if (!isset($mailbox) ||
empty($mailbox)) {
330 if (is_array($mailboxlist)) {
331 // use previously retrieved mailbox list
332 foreach ($mailboxlist as $mbox) {
333 if ($mbox['unformatted-dm'] == $mailbox) { return true; }
338 $mbx = sqimap_run_command($imap_stream, 'LIST "" ' . sqimap_encode_mailbox_name($mailbox),
339 true, $response, $message);
340 return isset($mbx[0]);
346 * Before 1.3.0 used more arguments and returned data depended on those argumements.
347 * @param stream $imap_stream imap connection resource
348 * @param string $mailbox mailbox name
349 * @return array results of select command (on success - permanentflags, flags and rights)
350 * @since 1.0 or older
352 function sqimap_mailbox_select ($imap_stream, $mailbox) {
353 // FIX ME: WHAAAA DO NOT USE "None" for something that does not exist. Use false or NULL instead
354 if ($mailbox == 'None') {
357 // cleanup $mailbox in order to prevent IMAP injection attacks
358 $mailbox = str_replace(array("\r","\n"), array("",""),$mailbox);
359 $read = sqimap_run_command($imap_stream, 'SELECT ' . sqimap_encode_mailbox_name($mailbox),
360 true, $response, $message);
362 for ($i = 0, $cnt = count($read); $i < $cnt; $i++
) {
363 if (preg_match('/^\*\s+OK\s\[(\w+)\s(\w+)\]/',$read[$i], $regs)) {
364 $result[strtoupper($regs[1])] = $regs[2];
365 } else if (preg_match('/^\*\s([0-9]+)\s(\w+)/',$read[$i], $regs)) {
366 $result[strtoupper($regs[2])] = $regs[1];
368 if (preg_match("/PERMANENTFLAGS(.*)/i",$read[$i], $regs)) {
369 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/","/\]/") ,'', $regs[1])) ;
370 $result['PERMANENTFLAGS'] = explode(' ',strtolower($regs[1]));
371 } else if (preg_match("/FLAGS(.*)/i",$read[$i], $regs)) {
372 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/") ,'', $regs[1])) ;
373 $result['FLAGS'] = explode(' ',strtolower($regs[1]));
377 if (!isset($result['PERMANENTFLAGS'])) {
378 $result['PERMANENTFLAGS'] = $result['FLAGS'];
380 if (preg_match('/^\[(.+)\]/',$message, $regs)) {
381 $result['RIGHTS']=strtoupper($regs[1]);
390 * Mailbox is automatically subscribed.
392 * Set $type to string that does not match 'noselect' (case insensitive),
393 * if you don't want to prepend delimiter to mailbox name. Please note
394 * that 'noinferiors' might be used someday as keyword for folders
395 * that store only messages.
396 * @param stream $imap_steam imap connection resource
397 * @param string $mailbox mailbox name
398 * @param string $type folder type.
399 * @since 1.0 or older
401 function sqimap_mailbox_create ($imap_stream, $mailbox, $type) {
403 if (strtolower($type) == 'noselect') {
404 $create_mailbox = $mailbox . $delimiter;
406 $create_mailbox = $mailbox;
409 $read_ary = sqimap_run_command($imap_stream, 'CREATE ' .
410 sqimap_encode_mailbox_name($create_mailbox),
411 true, $response, $message);
412 sqimap_subscribe ($imap_stream, $mailbox);
416 * Subscribes to an existing folder.
417 * @param stream $imap_stream imap connection resource
418 * @param string $mailbox mailbox name
419 * @param boolean $debug (since 1.5.1)
420 * @since 1.0 or older
422 function sqimap_subscribe ($imap_stream, $mailbox,$debug=true) {
423 $read_ary = sqimap_run_command($imap_stream, 'SUBSCRIBE ' .
424 sqimap_encode_mailbox_name($mailbox),
425 $debug, $response, $message);
429 * Unsubscribes from an existing folder
430 * @param stream $imap_stream imap connection resource
431 * @param string $mailbox mailbox name
432 * @since 1.0 or older
434 function sqimap_unsubscribe ($imap_stream, $mailbox) {
435 $read_ary = sqimap_run_command($imap_stream, 'UNSUBSCRIBE ' .
436 sqimap_encode_mailbox_name($mailbox),
437 false, $response, $message);
441 * Deletes the given folder
442 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
443 * @param stream $imap_stream imap connection resource
444 * @param string $mailbox mailbox name
445 * @since 1.0 or older
447 function sqimap_mailbox_delete ($imap_stream, $mailbox) {
448 global $data_dir, $username;
449 sqimap_unsubscribe ($imap_stream, $mailbox);
451 if (sqimap_mailbox_exists($imap_stream, $mailbox)) {
453 $read_ary = sqimap_run_command($imap_stream, 'DELETE ' .
454 sqimap_encode_mailbox_name($mailbox),
455 true, $response, $message);
456 if ($response !== 'OK') {
458 sqimap_subscribe ($imap_stream, $mailbox);
460 do_hook_function('rename_or_delete_folder', $args = array($mailbox, 'delete', ''));
461 removePref($data_dir, $username, "thread_$mailbox");
462 removePref($data_dir, $username, "collapse_folder_$mailbox");
468 * Determines if the user is subscribed to the folder or not
469 * @param stream $imap_stream imap connection resource
470 * @param string $mailbox mailbox name
474 function sqimap_mailbox_is_subscribed($imap_stream, $folder) {
475 $boxesall = sqimap_mailbox_list ($imap_stream);
476 foreach ($boxesall as $ref) {
477 if ($ref['unformatted'] == $folder) {
486 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
487 * @param stream $imap_stream imap connection resource
488 * @param string $old_name mailbox name
489 * @param string $new_name new mailbox name
492 function sqimap_mailbox_rename( $imap_stream, $old_name, $new_name ) {
493 if ( $old_name != $new_name ) {
494 global $delimiter, $imap_server_type, $data_dir, $username;
495 if ( substr( $old_name, -1 ) == $delimiter ) {
496 $old_name = substr( $old_name, 0, strlen( $old_name ) - 1 );
497 $new_name = substr( $new_name, 0, strlen( $new_name ) - 1 );
498 $postfix = $delimiter;
503 $boxesall = sqimap_mailbox_list_all($imap_stream);
504 $cmd = 'RENAME ' . sqimap_encode_mailbox_name($old_name) .
505 ' ' . sqimap_encode_mailbox_name($new_name);
506 $data = sqimap_run_command($imap_stream, $cmd, true, $response, $message);
507 sqimap_unsubscribe($imap_stream, $old_name.$postfix);
508 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$old_name.$postfix);
509 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
510 removePref($data_dir, $username, 'thread_'.$old_name.$postfix);
511 removePref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
512 sqimap_subscribe($imap_stream, $new_name.$postfix);
513 setPref($data_dir, $username, 'thread_'.$new_name.$postfix, $oldpref_thread);
514 setPref($data_dir, $username, 'collapse_folder_'.$new_name.$postfix, $oldpref_collapse);
515 do_hook_function('rename_or_delete_folder',$args = array($old_name, 'rename', $new_name));
516 $l = strlen( $old_name ) +
1;
519 foreach ($boxesall as $box) {
520 if (substr($box[$p], 0, $l) == $old_name . $delimiter) {
521 $new_sub = $new_name . $delimiter . substr($box[$p], $l);
522 /* With Cyrus IMAPd >= 2.0 rename is recursive, so don't check for errors here */
523 if ($imap_server_type == 'cyrus') {
524 $cmd = 'RENAME "' . $box[$p] . '" "' . $new_sub . '"';
525 $data = sqimap_run_command($imap_stream, $cmd, false,
526 $response, $message);
528 $was_subscribed = sqimap_mailbox_is_subscribed($imap_stream, $box[$p]);
529 if ( $was_subscribed ) {
530 sqimap_unsubscribe($imap_stream, $box[$p]);
532 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$box[$p]);
533 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$box[$p]);
534 removePref($data_dir, $username, 'thread_'.$box[$p]);
535 removePref($data_dir, $username, 'collapse_folder_'.$box[$p]);
536 if ( $was_subscribed ) {
537 sqimap_subscribe($imap_stream, $new_sub);
539 setPref($data_dir, $username, 'thread_'.$new_sub, $oldpref_thread);
540 setPref($data_dir, $username, 'collapse_folder_'.$new_sub, $oldpref_collapse);
541 do_hook_function('rename_or_delete_folder',
542 $args = array($box[$p], 'rename', $new_sub));
549 * Formats a mailbox into parts for the $boxesall array
553 * <li>raw - Raw LIST/LSUB response from the IMAP server
554 * <li>formatted - nicely formatted folder name
555 * <li>unformatted - unformatted, but with delimiter at end removed
556 * <li>unformatted-dm - folder name as it appears in raw response
557 * <li>unformatted-disp - unformatted without $folder_prefix
558 * <li>id - TODO: document me
559 * <li>flags - TODO: document me
561 * Before 1.2.0 used third argument for delimiter.
563 * Before 1.5.1 used second argument for lsub line. Argument was removed in order to use
564 * find_mailbox_name() on the raw input. Since 1.5.1 includes RFC3501 names in flags
565 * array (for example, "\NoSelect" in addition to "noselect")
568 * @since 1.0 or older
569 * @todo document id and flags keys in boxes array and function arguments.
571 function sqimap_mailbox_parse ($line) {
572 global $folder_prefix, $delimiter;
574 /* Process each folder line */
575 for ($g = 0, $cnt = count($line); $g < $cnt; ++
$g) {
576 /* Store the raw IMAP reply */
577 if (isset($line[$g])) {
578 $boxesall[$g]['raw'] = $line[$g];
580 $boxesall[$g]['raw'] = '';
583 /* Count number of delimiters ($delimiter) in folder name */
584 $mailbox = find_mailbox_name($line[$g]);
585 $dm_count = substr_count($mailbox, $delimiter);
586 if (substr($mailbox, -1) == $delimiter) {
587 /* If name ends in delimiter, decrement count by one */
591 /* Format folder name, but only if it's a INBOX.* or has a parent. */
592 $boxesallbyname[$mailbox] = $g;
593 $parentfolder = readMailboxParent($mailbox, $delimiter);
594 if ( (strtolower(substr($mailbox, 0, 5)) == "inbox") ||
595 (substr($mailbox, 0, strlen($folder_prefix)) == $folder_prefix) ||
596 (isset($boxesallbyname[$parentfolder]) &&
597 (strlen($parentfolder) > 0) ) ) {
598 $indent = $dm_count - (substr_count($folder_prefix, $delimiter));
600 $boxesall[$g]['formatted'] = str_repeat(' ', $indent);
602 $boxesall[$g]['formatted'] = '';
604 $boxesall[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
606 $boxesall[$g]['formatted'] = imap_utf7_decode_local($mailbox);
609 $boxesall[$g]['unformatted-dm'] = $mailbox;
610 if (substr($mailbox, -1) == $delimiter) {
611 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
613 $boxesall[$g]['unformatted'] = $mailbox;
614 if (substr($mailbox,0,strlen($folder_prefix))==$folder_prefix) {
615 $mailbox = substr($mailbox, strlen($folder_prefix));
617 $boxesall[$g]['unformatted-disp'] = $mailbox;
618 $boxesall[$g]['id'] = $g;
620 $boxesall[$g]['flags'] = array();
621 if (isset($line[$g])) {
622 ereg("\(([^)]*)\)",$line[$g],$regs);
624 * Since 1.5.1 flags are stored with RFC3501 naming
625 * and also the old way for backwards compatibility
626 * so for example "\NoSelect" and "noselect"
628 $flags = trim($regs[1]);
630 $flagsarr = explode(' ',$flags);
631 $flagsarrnew=$flagsarr;
633 foreach ($flagsarr as $flag) {
634 $flagsarrnew[]=strtolower(str_replace('\\', '',$flag));
636 $boxesall[$g]['flags']=$flagsarrnew;
644 * Returns list of options (to be echoed into select statement
645 * based on available mailboxes and separators
646 * Caller should surround options with <select ...> </select> and
648 * @param stream $imap_stream imap connection resource to query for mailboxes
649 * @param array $show_selected array containing list of mailboxes to pre-select (0 if none)
650 * @param array $folder_skip array of folders to keep out of option list (compared in lower)
651 * @param $boxes list of already fetched boxes (for places like folder panel, where
652 * you know these options will be shown 3 times in a row.. (most often unset).
653 * @param string $flag (since 1.4.1) flag to check for in mailbox flags, used to filter out mailboxes.
654 * 'noselect' by default to remove unselectable mailboxes.
655 * 'noinferiors' used to filter out folders that can not contain subfolders.
656 * NULL to avoid flag check entirely.
657 * NOTE: noselect and noiferiors are used internally. The IMAP representation is
658 * \NoSelect and \NoInferiors
659 * @param boolean $use_long_format (since 1.4.1) override folder display preference and always show full folder name.
660 * @return string html formated mailbox selection options
663 function sqimap_mailbox_option_list($imap_stream, $show_selected = 0, $folder_skip = 0, $boxes = 0,
664 $flag = 'noselect', $use_long_format = false ) {
665 global $username, $data_dir;
667 if ( $use_long_format ) {
668 $shorten_box_names = 0;
670 $shorten_box_names = getPref($data_dir, $username, 'mailbox_select_style', SMPREF_OFF
);
674 $boxes = sqimap_mailbox_list($imap_stream);
677 foreach ($boxes as $boxes_part) {
678 if ($flag == NULL ||
(is_array($boxes_part['flags'])
679 && !in_array($flag, $boxes_part['flags']))) {
680 $box = $boxes_part['unformatted'];
682 if ($folder_skip != 0 && in_array($box, $folder_skip) ) {
685 $lowerbox = strtolower($box);
686 // mailboxes are casesensitive => inbox.sent != inbox.Sent
687 // nevermind, to many dependencies this should be fixed!
689 if (strtolower($box) == 'inbox') { // inbox is special and not casesensitive
692 switch ($shorten_box_names)
694 case 2: /* delimited, style = 2 */
695 $box2 = str_replace('&nbsp;&nbsp;', '. ', htmlspecialchars($boxes_part['formatted']));
697 case 1: /* indent, style = 1 */
698 $box2 = str_replace('&nbsp;&nbsp;', ' ', htmlspecialchars($boxes_part['formatted']));
700 default: /* default, long names, style = 0 */
701 $box2 = str_replace(' ', ' ', htmlspecialchars(imap_utf7_decode_local($boxes_part['unformatted-disp'])));
705 if ($show_selected != 0 && in_array($lowerbox, $show_selected) ) {
706 $mbox_options .= '<option value="' . htmlspecialchars($box) .'" selected="selected">'.$box2.'</option>' . "\n";
708 $mbox_options .= '<option value="' . htmlspecialchars($box) .'">'.$box2.'</option>' . "\n";
712 return $mbox_options;
716 * Returns sorted mailbox lists in several different ways.
718 * Since 1.5.1 most of the functionality has been moved to new function sqimap_get_mailboxes
720 * See comment on sqimap_mailbox_parse() for info about the returned array.
721 * @param resource $imap_stream imap connection resource
722 * @param boolean $force force update of mailbox listing. available since 1.4.2 and 1.5.0
723 * @return array list of mailboxes
724 * @since 1.0 or older
726 function sqimap_mailbox_list($imap_stream, $force=false) {
727 global $boxesnew,$show_only_subscribed_folders;
728 if (!sqgetGlobalVar('boxesnew',$boxesnew,SQ_SESSION
) ||
$force) {
729 $boxesnew=sqimap_get_mailboxes($imap_stream,$force,$show_only_subscribed_folders);
735 * Returns a list of all folders, subscribed or not
737 * Since 1.5.1 code moved to sqimap_get_mailboxes()
739 * @param stream $imap_stream imap connection resource
740 * @return array see sqimap_mailbox_parse()
741 * @since 1.0 or older
743 function sqimap_mailbox_list_all($imap_stream) {
744 global $show_only_subscribed_folders;
745 // fourth argument prevents registration of retrieved list of mailboxes in session
746 $boxes=sqimap_get_mailboxes($imap_stream,true,false,false);
752 * Gets the list of mailboxes for sqimap_maolbox_tree and sqimap_mailbox_list
754 * This is because both of those functions had duplicated logic, but with slightly different
755 * implementations. This will make both use the same implementation, which should make it
756 * easier to maintain and easier to modify in the future
757 * @param stream $imap_stream imap connection resource
758 * @param bool $force force a reload and ignore cache
759 * @param bool $show_only_subscribed controls listing of visible or all folders
760 * @param bool $session_register controls registration of retrieved data in session.
761 * @return object boxesnew - array of mailboxes and their attributes
764 function sqimap_get_mailboxes($imap_stream,$force=false,$show_only_subscribed=true,$session_register=true) {
765 global $show_only_subscribed_folders,$noselect_fix_enable,$folder_prefix,
766 $list_special_folders_first,$imap_server_type;
767 $inbox_subscribed = false;
768 $listsubscribed = sqimap_capability($imap_stream,'LIST-SUBSCRIBED');
770 if ($show_only_subscribed) { $show_only_subscribed=$show_only_subscribed_folders; }
772 require_once(SM_PATH
. 'include/load_prefs.php');
775 * There are three main listing commands we can use in IMAP:
776 * LSUB shows just the list of subscribed folders
777 * may include flags, but these are not necessarily accurate or authoratative
778 * \NoSelect has special meaning: the folder does not exist -OR- it means this
779 * folder is not subscribed but children may be
781 * LIST this shows every mailbox on the system
782 * flags are always included and are accurate and authoratative
783 * \NoSelect means folder should not be selected
785 * LIST (SUBSCRIBED) implemented with LIST-SUBSCRIBED extension
786 * this is like list but returns only subscribed folders
787 * flag meanings are like LIST, not LSUB
788 * \NonExistent means mailbox doesn't exist
789 * \PlaceHolder means parent is not valid (selectable), but one or more children are
790 * \NoSelect indeed means that the folder should not be selected
791 * IMAPEXT-LIST-EXTENSIONS-04 August 2003 B. Leiba
793 if (!$show_only_subscribed) {
795 $sub_cache_name='list_cache';
796 } elseif ($listsubscribed) {
797 $lsub = 'LIST (SUBSCRIBED)';
798 $sub_cache_name='listsub_cache';
801 $sub_cache_name='lsub_cache';
804 // Some IMAP servers allow subfolders to exist even if the parent folders do not
805 // This fixes some problems with the folder list when this is the case, causing the
806 // NoSelect folders to be displayed
807 if ($noselect_fix_enable) {
808 $lsub_args = "$lsub \"$folder_prefix\" \"*%\"";
809 $list_args = "LIST \"$folder_prefix\" \"*%\"";
811 $lsub_args = "$lsub \"$folder_prefix\" \"*\"";
812 $list_args = "LIST \"$folder_prefix\" \"*\"";
815 // get subscribed mailbox list from cache (session)
816 // if not there, then get it from the imap server and store in cache
817 sqsession_is_active();
820 sqgetGlobalVar($sub_cache_name,$lsub_cache,SQ_SESSION
);
823 $lsub_assoc_ary=array();
824 if (!empty($lsub_cache)) {
825 $lsub_assoc_ary=$lsub_cache;
827 $lsub_ary = sqimap_run_command ($imap_stream, $lsub_args, true, $response, $message);
828 $lsub_ary = compact_mailboxes_response($lsub_ary);
829 if (!empty($lsub_ary)) {
830 foreach ($lsub_ary as $rawline) {
831 $temp_mailbox_name=find_mailbox_name($rawline);
832 $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
835 sqsession_register($lsub_assoc_ary,$sub_cache_name);
839 // Now to get the mailbox flags
840 // The LSUB response may return \NoSelect flags, etc. but it is optional
841 // according to RFC3501, and even when returned it may not be accurate
842 // or authoratative. LIST will always return accurate results.
843 if (($lsub == 'LIST') ||
($lsub == 'LIST (SUBSCRIBED)')) {
844 // we've already done a LIST or LIST (SUBSCRIBED)
845 // and NOT a LSUB, so no need to do it again
846 $list_assoc_ary = $lsub_assoc_ary;
848 // we did a LSUB so now we need to do a LIST
849 // first see if it is in cache
850 $list_cache_name='list_cache';
852 sqgetGlobalVar($list_cache_name,$list_cache,SQ_SESSION
);
855 if (!empty($list_cache)) {
856 $list_assoc_ary=$list_cache;
857 // we could store this in list_cache_name but not necessary
859 // not in cache so we need to go get it from the imap server
860 $list_assoc_ary = array();
861 $list_ary = sqimap_run_command($imap_stream, $list_args,
862 true, $response, $message);
863 $list_ary = compact_mailboxes_response($list_ary);
864 if (!empty($list_ary)) {
865 foreach ($list_ary as $rawline) {
866 $temp_mailbox_name=find_mailbox_name($rawline);
867 $list_assoc_ary[$temp_mailbox_name]=$rawline;
870 sqsession_register($list_assoc_ary,$list_cache_name);
875 // If they aren't subscribed to the inbox, then add it anyway (if its in LIST)
876 $inbox_subscribed=false;
877 if (!empty($lsub_assoc_ary)) {
878 foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
879 if (strtoupper($temp_mailbox_name) == 'INBOX') {
880 $inbox_subscribed=true;
884 if (!$inbox_subscribed) {
885 if (!empty($list_assoc_ary)) {
886 foreach ($list_assoc_ary as $temp_mailbox_name=>$rawline) {
887 if (strtoupper($temp_mailbox_name) == 'INBOX') {
888 $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
894 // Now we have the raw output, we need to create an array of mailbox names we will return
895 if (!$show_only_subscribed) {
896 $final_folders_assoc_ary=$list_assoc_ary;
899 * only show subscribed folders
900 * we need to merge the folders here... we can't trust the flags, etc. from the lsub_assoc_array
901 * so we use the lsub_assoc_array as the list of folders and the values come from list_assoc_array
903 if (!empty($lsub_assoc_ary)) {
904 foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
905 if (!empty($list_assoc_ary[$temp_mailbox_name])) {
906 $final_folders_assoc_ary[$temp_mailbox_name]=$list_assoc_ary[$temp_mailbox_name];
913 // Now produce a flat, sorted list
914 if (!empty($final_folders_assoc_ary)) {
915 uksort($final_folders_assoc_ary,'strnatcasecmp');
916 foreach ($final_folders_assoc_ary as $temp_mailbox_name=>$rawline) {
917 $final_folders_ary[]=$rawline;
921 // this will put it into an array we can use later
923 // raw - Raw LIST/LSUB response from the IMAP server
924 // formatted - formatted folder name
925 // unformatted - unformatted, but with the delimiter at the end removed
926 // unformated-dm - folder name as it appears in raw response
927 // unformatted-disp - unformatted without $folder_prefix
928 // id - the array element number (0, 1, 2, etc.)
929 // flags - mailbox flags
930 if (!empty($final_folders_ary)) {
931 $boxesall = sqimap_mailbox_parse($final_folders_ary);
933 // they have no mailboxes
937 /* Now, lets sort for special folders */
938 $boxesnew = $used = array();
941 $cnt = count($boxesall);
942 $used = array_pad($used,$cnt,false);
944 for($k = 0; $k < $cnt; ++
$k) {
945 if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
946 $boxesnew[] = $boxesall[$k];
953 if ($has_inbox == false) {
954 // do a list request for inbox because we should always show
955 // inbox even if the user isn't subscribed to it.
956 $inbox_ary = sqimap_run_command($imap_stream, 'LIST "" "INBOX"',
957 true, $response, $message);
958 $inbox_ary = compact_mailboxes_response($inbox_ary);
959 if (count($inbox_ary)) {
960 $inbox_entry = sqimap_mailbox_parse($inbox_ary);
961 // add it on top of the list
962 if (!empty($boxesnew)) {
963 array_unshift($boxesnew,$inbox_entry[0]);
965 $boxesnew[]=$inbox_entry[0];
967 /* array_unshift($used,true); */
971 /* List special folders and their subfolders, if requested. */
972 if ($list_special_folders_first) {
973 for($k = 0; $k < $cnt; ++
$k) {
974 if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
975 $boxesnew[] = $boxesall[$k];
981 /* Find INBOX's children */
982 for($k = 0; $k < $cnt; ++
$k) {
983 $isboxbelow=isBoxBelow(strtoupper($boxesall[$k]['unformatted']),'INBOX');
984 if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
990 if (!$used[$k] && $isboxbelow && $is_inbox) {
991 $boxesnew[] = $boxesall[$k];
996 /* Rest of the folders */
997 for($k = 0; $k < $cnt; $k++
) {
999 $boxesnew[] = $boxesall[$k];
1003 * Don't register boxes in session, if $session_register is set to false
1004 * Prevents registration of sqimap_mailbox_list_all() results.
1006 if ($session_register) sqsession_register($boxesnew,'boxesnew');
1011 * Fills mailbox object
1013 * this is passed the mailbox array by left_main.php
1014 * who has previously obtained it from sqimap_get_mailboxes
1015 * that way, the raw mailbox list is available in left_main to other
1016 * things besides just sqimap_mailbox_tree
1017 * imap_stream is just used now to get status info
1019 * most of the functionality is moved to sqimap_get_mailboxes
1020 * also takes care of TODO items:
1021 * caching mailbox tree
1022 * config setting for UW imap section (not needed now)
1024 * Some code fragments are present in 1.3.0 - 1.4.4.
1025 * @param stream $imap_stream imap connection resource
1026 * @param array $lsub_ary output array from sqimap_get_mailboxes (contains mailboxes and flags)
1027 * @return object see mailboxes class.
1030 function sqimap_mailbox_tree($imap_stream,$lsub_ary) {
1032 $sorted_lsub_ary = array();
1033 $cnt = count($lsub_ary);
1034 for ($i = 0; $i < $cnt; $i++
) {
1035 $mbx=$lsub_ary[$i]['unformatted'];
1036 $flags=$lsub_ary[$i]['flags'];
1039 if (in_array('\Noinferiors',$flags)) { $noinferiors=1; }
1040 if (in_array('\NoInferiors',$flags)) { $noinferiors=1; }
1041 if (in_array('\HasNoChildren',$flags)) { $noinferiors=1; }
1044 if (in_array('\NoSelect',$flags)) { $noselect=1; }
1046 * LIST (SUBSCRIBED) has two new flags, \NonExistent which means the mailbox is subscribed to
1047 * but doesn't exist, and \PlaceHolder which is similar (but not the same) as \NoSelect
1048 * For right now, we'll treat these the same as \NoSelect and this behavior can be changed
1051 if (in_array('\NonExistent',$flags)) { $noselect=1; }
1052 if (in_array('\PlaceHolder',$flags)) { $noselect=1; }
1053 $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
1056 $sorted_lsub_ary = array_values($sorted_lsub_ary);
1057 usort($sorted_lsub_ary, 'mbxSort');
1058 $boxestree = sqimap_fill_mailbox_tree($sorted_lsub_ary,false,$imap_stream);
1063 * Callback function used for sorting mailboxes in sqimap_mailbox_tree
1066 * @return integer see php strnatcasecmp()
1069 function mbxSort($a, $b) {
1070 return strnatcasecmp($a['mbx'], $b['mbx']);
1074 * Fills mailbox object
1076 * Some code fragments are present in 1.3.0 - 1.4.4.
1077 * @param array $mbx_ary
1079 * @param stream $imap_stream imap connection resource
1080 * @return object see mailboxes class
1083 function sqimap_fill_mailbox_tree($mbx_ary, $mbxs=false,$imap_stream) {
1084 global $data_dir, $username, $list_special_folders_first,
1085 $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
1086 $move_to_trash, $move_to_sent, $save_as_draft,
1087 $delimiter, $imap_server_type;
1089 // $special_folders = array ('INBOX', $sent_folder, $draft_folder, $trash_folder);
1091 /* create virtual root node */
1092 $mailboxes= new mailboxes();
1093 $mailboxes->is_root
= true;
1097 if (isset($folder_prefix) && ($folder_prefix != '')) {
1098 $start = substr_count($folder_prefix,$delimiter);
1099 if (strrpos($folder_prefix, $delimiter) == (strlen($folder_prefix)-1)) {
1100 $mailboxes->mailboxname_full
= substr($folder_prefix,0, (strlen($folder_prefix)-1));
1102 $mailboxes->mailboxname_full
= $folder_prefix;
1105 $mailboxes->mailboxname_sub
= $mailboxes->mailboxname_full
;
1110 $cnt = count($mbx_ary);
1111 for ($i=0; $i < $cnt; $i++
) {
1112 if ($mbx_ary[$i]['mbx'] !='' ) {
1113 $mbx = new mailboxes();
1114 $mailbox = $mbx_ary[$i]['mbx'];
1117 * Set the is_special flag if it concerned a special mailbox.
1118 * Used for displaying the special folders on top in the mailbox
1119 * tree displaying code.
1121 $mbx->is_special |
= ($mbx->is_inbox
= (strtoupper($mailbox) == 'INBOX'));
1122 $mbx->is_special |
= ($mbx->is_trash
= isTrashMailbox($mailbox));
1123 $mbx->is_special |
= ($mbx->is_sent
= isSentMailbox($mailbox));
1124 $mbx->is_special |
= ($mbx->is_draft
= isDraftMailbox($mailbox));
1126 if (!$mbx->is_special
)
1127 $mbx->is_special
= boolean_hook_function('special_mailbox', $mailbox, 1);
1129 if (isset($mbx_ary[$i]['unseen'])) {
1130 $mbx->unseen
= $mbx_ary[$i]['unseen'];
1132 if (isset($mbx_ary[$i]['nummessages'])) {
1133 $mbx->total
= $mbx_ary[$i]['nummessages'];
1136 $mbx->is_noselect
= $mbx_ary[$i]['noselect'];
1137 $mbx->is_noinferiors
= $mbx_ary[$i]['noinferiors'];
1139 $r_del_pos = strrpos($mbx_ary[$i]['mbx'], $delimiter);
1141 $mbx->mailboxname_sub
= substr($mbx_ary[$i]['mbx'],$r_del_pos+
1);
1142 } else { /* mailbox is root folder */
1143 $mbx->mailboxname_sub
= $mbx_ary[$i]['mbx'];
1145 $mbx->mailboxname_full
= $mbx_ary[$i]['mbx'];
1147 $mailboxes->addMbx($mbx, $delimiter, $start, $list_special_folders_first);
1150 sqimap_utf7_decode_mbx_tree($mailboxes);
1151 sqimap_get_status_mbx_tree($imap_stream,$mailboxes);
1156 * @param object $mbx_tree
1159 function sqimap_utf7_decode_mbx_tree(&$mbx_tree) {
1161 if (strtoupper($mbx_tree->mailboxname_full
) == 'INBOX')
1162 $mbx_tree->mailboxname_sub
= _("INBOX");
1164 $mbx_tree->mailboxname_sub
= imap_utf7_decode_local($mbx_tree->mailboxname_sub
);
1165 if ($mbx_tree->mbxs
) {
1166 $iCnt = count($mbx_tree->mbxs
);
1167 for ($i=0;$i<$iCnt;++
$i) {
1168 sqimap_utf7_decode_mbx_tree($mbx_tree->mbxs
[$i]);
1174 * @param object $mbx_tree
1175 * @param array $aMbxs
1178 function sqimap_tree_to_ref_array(&$mbx_tree,&$aMbxs) {
1180 $aMbxs[] =& $mbx_tree;
1181 if ($mbx_tree->mbxs
) {
1182 $iCnt = count($mbx_tree->mbxs
);
1183 for ($i=0;$i<$iCnt;++
$i) {
1184 sqimap_tree_to_ref_array($mbx_tree->mbxs
[$i],$aMbxs);
1190 * @param stream $imap_stream imap connection resource
1191 * @param object $mbx_tree
1192 * @since since 1.5.0
1194 function sqimap_get_status_mbx_tree($imap_stream,&$mbx_tree) {
1195 global $unseen_notify, $unseen_type, $trash_folder,$move_to_trash;
1196 $aMbxs = $aQuery = array();
1197 sqimap_tree_to_ref_array($mbx_tree,$aMbxs);
1198 // remove the root node
1199 array_shift($aMbxs);
1201 if($unseen_notify == 3) {
1202 $cnt = count($aMbxs);
1203 for($i=0;$i<$cnt;++
$i) {
1204 $oMbx =& $aMbxs[$i];
1205 if (!$oMbx->is_noselect
) {
1206 $mbx = $oMbx->mailboxname_full
;
1207 if ($unseen_type == 2 ||
1208 ($move_to_trash && $oMbx->mailboxname_full
== $trash_folder)) {
1209 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (MESSAGES UNSEEN RECENT)';
1211 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (UNSEEN RECENT)';
1213 sqimap_prepare_pipelined_query($query,$tag,$aQuery,false);
1215 $oMbx->unseen
= $oMbx->total
= $oMbx->recent
= false;
1219 $aMbxs[$i] =& $oMbx;
1221 // execute all the queries at once
1222 $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
1223 $cnt = count($aMbxs);
1224 for($i=0;$i<$cnt;++
$i) {
1225 $oMbx =& $aMbxs[$i];
1227 if ($tag && $aServerResponse[$tag] == 'OK') {
1228 $sResponse = implode('', $aResponse[$tag]);
1229 if (preg_match('/UNSEEN\s+([0-9]+)/i', $sResponse, $regs)) {
1230 $oMbx->unseen
= $regs[1];
1232 if (preg_match('/MESSAGES\s+([0-9]+)/i', $sResponse, $regs)) {
1233 $oMbx->total
= $regs[1];
1235 if (preg_match('/RECENT\s+([0-9]+)/i', $sResponse, $regs)) {
1236 $oMbx->recent
= $regs[1];
1242 } else if ($unseen_notify == 2) { // INBOX only
1243 $cnt = count($aMbxs);
1244 for($i=0;$i<$cnt;++
$i) {
1245 $oMbx =& $aMbxs[$i];
1246 if (strtoupper($oMbx->mailboxname_full
) == 'INBOX' ||
1247 ($move_to_trash && $oMbx->mailboxname_full
== $trash_folder)) {
1248 if ($unseen_type == 2 ||
1249 ($oMbx->mailboxname_full
== $trash_folder && $move_to_trash)) {
1250 $aStatus = sqimap_status_messages($imap_stream,$oMbx->mailboxname_full
);
1251 $oMbx->unseen
= $aStatus['UNSEEN'];
1252 $oMbx->total
= $aStatus['MESSAGES'];
1253 $oMbx->recent
= $aStatus['RECENT'];
1255 $oMbx->unseen
= sqimap_unseen_messages($imap_stream,$oMbx->mailboxname_full
);
1257 $aMbxs[$i] =& $oMbx;
1258 if (!$move_to_trash && $trash_folder) {
1261 // trash comes after INBOX
1262 if ($oMbx->mailboxname_full
== $trash_folder) {
1270 $cnt = count($aMbxs);
1271 for($i=0;$i<$cnt;++
$i) {
1272 $oMbx =& $aMbxs[$i];
1273 unset($hook_status);
1274 if (!empty($oMbx->unseen
)) { $hook_status['UNSEEN']=$oMbx->unseen
; }
1275 if (!empty($oMbx->total
)) { $hook_status['MESSAGES']=$oMbx->total
; }
1276 if (!empty($oMbx->recent
)) { $hook_status['RECENT']=$oMbx->recent
; }
1277 if (!empty($hook_status))
1279 $hook_status['MAILBOX']=$oMbx->mailboxname_full
;
1280 $hook_status['CALLER']='sqimap_get_status_mbx_tree'; // helps w/ debugging
1281 do_hook_function('folder_status',$hook_status);
1287 * Checks if folder is noselect (can't store messages)
1289 * Function does not check if folder subscribed.
1290 * @param stream $oImapStream imap connection resource
1291 * @param string $sImapFolder imap folder name
1292 * @param object $oBoxes mailboxes class object.
1293 * @return boolean true, when folder has noselect flag. false in any other case.
1296 function sqimap_mailbox_is_noselect($oImapStream,$sImapFolder,&$oBoxes) {
1297 // build mailbox object if it is not available
1298 if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
1299 foreach($oBoxes as $box) {
1300 if ($box['unformatted']==$sImapFolder) {
1301 return (bool) check_is_noselect($box['raw']);
1308 * Checks if folder is noinferiors (can't store other folders)
1310 * Function does not check if folder subscribed.
1311 * @param stream $oImapStream imap connection resource
1312 * @param string $sImapFolder imap folder name
1313 * @param object $oBoxes mailboxes class object.
1314 * @return boolean true, when folder has noinferiors flag. false in any other case.
1317 function sqimap_mailbox_is_noinferiors($oImapStream,$sImapFolder,&$oBoxes) {
1318 // build mailbox object if it is not available
1319 if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
1320 foreach($oBoxes as $box) {
1321 if ($box['unformatted']==$sImapFolder) {
1322 return (bool) check_is_noinferiors($box['raw']);