XCOURIEROUTBOX indicates option that can create duplicate messages.
[squirrelmail.git] / functions / imap_mailbox.php
CommitLineData
59177427 1<?php
62f7daa5 2
35586184 3/**
4 * imap_mailbox.php
5 *
4b2720f5 6 * This implements all functions that manipulate mailboxes
35586184 7 *
47ccfad4 8 * @copyright &copy; 1999-2006 The SquirrelMail Project Team
4b4abf93 9 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
eb19bc67 10 * @version $Id$
d6c32258 11 * @package squirrelmail
eb19bc67 12 * @subpackage imap
35586184 13 */
d6c32258 14
15/** UTF7 support */
334a77f8 16require_once(SM_PATH . 'functions/imap_utf7_local.php');
17
1da22cda 18
d6c32258 19/**
20 * Mailboxes class
4669e892 21 *
22 * FIXME. This class should be extracted and placed in a separate file that
d6c32258 23 * can be included before we start the session. That makes caching of the tree
4669e892 24 * possible. On a refresh mailboxes from left_main.php the only function that
25 * should be called is the sqimap_get_status_mbx_tree. In case of subscribe
26 * / rename / delete / new we have to create methods for adding/changing the
d6c32258 27 * mailbox in the mbx_tree without the need for a refresh.
4b2720f5 28 *
29 * Some code fragments are present in 1.3.0 - 1.4.4.
d6c32258 30 * @package squirrelmail
dc027257 31 * @subpackage imap
4b2720f5 32 * @since 1.5.0
dc027257 33 */
60b5724d 34class mailboxes {
86c2763d 35 var $mailboxname_full = '', $mailboxname_sub= '', $is_noselect = false, $is_noinferiors = false,
ff245fbd 36 $is_special = false, $is_root = false, $is_inbox = false, $is_sent = false,
4669e892 37 $is_trash = false, $is_draft = false, $mbxs = array(),
48879ef0 38 $unseen = false, $total = false, $recent = false;
ff245fbd 39
40 function addMbx($mbx, $delimiter, $start, $specialfirst) {
41 $ary = explode($delimiter, $mbx->mailboxname_full);
ae7df16e 42 $mbx_parent =& $this;
ff245fbd 43 for ($i = $start, $c = count($ary)-1; $i < $c; $i++) {
ae7df16e 44 $mbx_childs =& $mbx_parent->mbxs;
ff245fbd 45 $found = false;
46 if ($mbx_childs) {
47 foreach ($mbx_childs as $key => $parent) {
48 if ($parent->mailboxname_sub == $ary[$i]) {
ae7df16e 49 $mbx_parent =& $mbx_parent->mbxs[$key];
ff245fbd 50 $found = true;
ae7df16e 51 break;
ff245fbd 52 }
53 }
54 }
55 if (!$found) {
56 $no_select_mbx = new mailboxes();
57 if (isset($mbx_parent->mailboxname_full) && $mbx_parent->mailboxname_full != '') {
58 $no_select_mbx->mailboxname_full = $mbx_parent->mailboxname_full.$delimiter.$ary[$i];
59 } else {
60 $no_select_mbx->mailboxname_full = $ary[$i];
61 }
587ec647 62 $no_select_mbx->mailboxname_sub = $ary[$i];
ff245fbd 63 $no_select_mbx->is_noselect = true;
64 $mbx_parent->mbxs[] = $no_select_mbx;
65 $i--;
66 }
67 }
68 $mbx_parent->mbxs[] = $mbx;
69 if ($mbx->is_special && $specialfirst) {
70 usort($mbx_parent->mbxs, 'sortSpecialMbx');
71 }
72 }
60b5724d 73}
74
dc027257 75/**
76 * array callback used for sorting in mailboxes class
77 * @param object $a
78 * @param object $b
3131bc8d 79 * @return integer see php strnatcasecmp()
dc027257 80 * @since 1.3.0
81 */
60b5724d 82function sortSpecialMbx($a, $b) {
83 if ($a->is_inbox) {
ff245fbd 84 $acmp = '0'. $a->mailboxname_full;
60b5724d 85 } else if ($a->is_special) {
ff245fbd 86 $acmp = '1'. $a->mailboxname_full;
60b5724d 87 } else {
ff245fbd 88 $acmp = '2' . $a->mailboxname_full;
89 }
60b5724d 90 if ($b->is_inbox) {
ff245fbd 91 $bcmp = '0'. $b->mailboxname_full;
60b5724d 92 }else if ($b->is_special) {
ff245fbd 93 $bcmp = '1' . $b->mailboxname_full;
60b5724d 94 } else {
ff245fbd 95 $bcmp = '2' . $b->mailboxname_full;
60b5724d 96 }
4669e892 97 return strnatcasecmp($acmp, $bcmp);
ff245fbd 98}
60b5724d 99
dc027257 100/**
101 * @param array $ary
102 * @return array
103 * @since 1.5.0
104 */
105function compact_mailboxes_response($ary) {
86c2763d 106 /*
107 * Workaround for mailboxes returned as literal
4669e892 108 * FIXME : Doesn't work if the mailbox name is multiple lines
86c2763d 109 * (larger then fgets buffer)
110 */
111 for ($i = 0, $iCnt=count($ary); $i < $iCnt; $i++) {
112 if (isset($ary[$i + 1]) && substr($ary[$i], -3) == "}\r\n") {
113 if (ereg("^(\\* [A-Z]+.*)\\{[0-9]+\\}([ \n\r\t]*)$",
114 $ary[$i], $regs)) {
115 $ary[$i] = $regs[1] . '"' . addslashes(trim($ary[$i+1])) . '"' . $regs[2];
116 array_splice($ary, $i+1, 2);
117 }
118 }
119 }
120 /* remove duplicates and ensure array is contiguous */
121 return array_values(array_unique($ary));
122}
123
48af4b64 124/**
125 * Extract the mailbox name from an untagged LIST (7.2.2) or LSUB (7.2.3) answer
126 * (LIST|LSUB) (<Flags list>) (NIL|"<separator atom>") <mailbox name string>\r\n
127 * mailbox name in quoted string MUST be unquoted and stripslashed (sm API)
dc027257 128 *
f8a1ed5a 129 * Originally stored in functions/strings.php. Since 1.2.6 stored in
dc027257 130 * functions/imap_mailbox.php
131 * @param string $line imap LIST/LSUB response line
132 * @return string mailbox name
48af4b64 133 */
dc027257 134function find_mailbox_name($line) {
bac13dd7 135 if (preg_match('/^\* (?:LIST|LSUB) \([^\)]*\) (?:NIL|\"[^\"]*\") ([^\r\n]*)[\r\n]*$/i', $line, $regs)) {
136 if (substr($regs[1], 0, 1) == '"')
137 return stripslashes(substr($regs[1], 1, -1));
138 return $regs[1];
139 }
140 return '';
141}
142
48af4b64 143/**
dc027257 144 * Detects if mailbox has noselect flag (can't store messages)
ae9e2adc 145 * In versions older than 1.4.5 function checks only LSUB responses
146 * and can produce pcre warnings.
dc027257 147 * @param string $lsub_line mailbox line from untagged LIST or LSUB response
48af4b64 148 * @return bool whether this is a Noselect mailbox.
dc027257 149 * @since 1.3.2
48af4b64 150 */
f73348a3 151function check_is_noselect ($lsub_line) {
3698bd49 152 return preg_match("/^\* (LSUB|LIST) \([^\)]*\\\\Noselect[^\)]*\)/i", $lsub_line);
79e07c7e 153}
154
48af4b64 155/**
dc027257 156 * Detects if mailbox has noinferiors flag (can't store subfolders)
157 * @param string $lsub_line mailbox line from untagged LIST or LSUB response
48af4b64 158 * @return bool whether this is a Noinferiors mailbox.
dc027257 159 * @since 1.5.0
48af4b64 160 */
86c2763d 161function check_is_noinferiors ($lsub_line) {
162 return preg_match("/^\* (LSUB|LIST) \([^\)]*\\\\Noinferiors[^\)]*\)/i", $lsub_line);
163}
164
97b1248c 165/**
d43853c7 166 * Detects mailbox's parent folder
167 *
97b1248c 168 * If $haystack is a full mailbox name, and $needle is the mailbox
169 * separator character, returns the second last part of the full
170 * mailbox name (i.e. the mailbox's parent mailbox)
d43853c7 171 *
f8a1ed5a 172 * Originally stored in functions/strings.php. Since 1.2.6 stored in
d43853c7 173 * functions/imap_mailbox.php
174 * @param string $haystack full mailbox name
175 * @param string $needle delimiter
f8a1ed5a 176 * @return string parent mailbox
97b1248c 177 */
178function readMailboxParent($haystack, $needle) {
97b1248c 179 if ($needle == '') {
180 $ret = '';
181 } else {
182 $parts = explode($needle, $haystack);
183 $elem = array_pop($parts);
184 while ($elem == '' && count($parts)) {
185 $elem = array_pop($parts);
186 }
187 $ret = join($needle, $parts);
188 }
189 return( $ret );
190}
191
4669e892 192/**
6a8e7cae 193 * Check if $subbox is below the specified $parentbox
d43853c7 194 * @param string $subbox potential sub folder
195 * @param string $parentbox potential parent
196 * @return boolean
197 * @since 1.2.3
6a8e7cae 198 */
199function isBoxBelow( $subbox, $parentbox ) {
cef054e4 200 global $delimiter;
4669e892 201 /*
202 * Eliminate the obvious mismatch, where the
6a8e7cae 203 * subfolder path is shorter than that of the potential parent
204 */
205 if ( strlen($subbox) < strlen($parentbox) ) {
206 return false;
207 }
cef054e4 208 /* check for delimiter */
c3ce607e 209 if (substr($parentbox,-1) != $delimiter) {
210 $parentbox .= $delimiter;
211 }
212
213 return (substr($subbox,0,strlen($parentbox)) == $parentbox);
1e18bf95 214}
215
48af4b64 216/**
217 * Defines special mailboxes: given a mailbox name, it checks if this is a
218 * "special" one: INBOX, Trash, Sent or Draft.
f8a1ed5a 219 *
d43853c7 220 * Since 1.2.5 function includes special_mailbox hook.<br>
221 * Since 1.4.3 hook supports more than one plugin.
222 * @param string $box mailbox name
ceb7ad3c 223 * @param boolean $include_subs (since 1.5.2) if true, subfolders of system
224 * folders are special. if false, subfolders are not special mailboxes
225 * unless they are tagged as special in 'special_mailbox' hook.
d43853c7 226 * @return boolean
227 * @since 1.2.3
48af4b64 228 */
ceb7ad3c 229function isSpecialMailbox($box,$include_subs=true) {
90de1755 230 $ret = ( (strtolower($box) == 'inbox') ||
ceb7ad3c 231 isTrashMailbox($box,$include_subs) ||
232 isSentMailbox($box,$include_subs) ||
233 isDraftMailbox($box,$include_subs) );
90de1755 234
2586d588 235 if ( !$ret ) {
5576644b 236 $ret = boolean_hook_function('special_mailbox',$box,1);
2586d588 237 }
3411d4ec 238 return $ret;
90de1755 239}
240
48af4b64 241/**
d43853c7 242 * Detects if mailbox is a Trash folder or subfolder of Trash
243 * @param string $box mailbox name
ceb7ad3c 244 * @param boolean $include_subs (since 1.5.2) if true, subfolders of system
245 * folders are special. if false, subfolders are not special mailboxes.
48af4b64 246 * @return bool whether this is a Trash folder
d43853c7 247 * @since 1.4.0
48af4b64 248 */
ceb7ad3c 249function isTrashMailbox ($box,$include_subs=true) {
6a8e7cae 250 global $trash_folder, $move_to_trash;
251 return $move_to_trash && $trash_folder &&
ceb7ad3c 252 ( $box == $trash_folder ||
253 ($include_subs && isBoxBelow($box, $trash_folder)) );
6a8e7cae 254}
255
48af4b64 256/**
d43853c7 257 * Detects if mailbox is a Sent folder or subfolder of Sent
258 * @param string $box mailbox name
ceb7ad3c 259 * @param boolean $include_subs (since 1.5.2) if true, subfolders of system
260 * folders are special. if false, subfolders are not special mailboxes.
48af4b64 261 * @return bool whether this is a Sent folder
d43853c7 262 * @since 1.4.0
48af4b64 263 */
ceb7ad3c 264function isSentMailbox($box,$include_subs=true) {
6a8e7cae 265 global $sent_folder, $move_to_sent;
266 return $move_to_sent && $sent_folder &&
ceb7ad3c 267 ( $box == $sent_folder ||
268 ($include_subs && isBoxBelow($box, $sent_folder)) );
6a8e7cae 269}
270
48af4b64 271/**
d43853c7 272 * Detects if mailbox is a Drafts folder or subfolder of Drafts
273 * @param string $box mailbox name
ceb7ad3c 274 * @param boolean $include_subs (since 1.5.2) if true, subfolders of system
275 * folders are special. if false, subfolders are not special mailboxes.
48af4b64 276 * @return bool whether this is a Draft folder
d43853c7 277 * @since 1.4.0
48af4b64 278 */
ceb7ad3c 279function isDraftMailbox($box,$include_subs=true) {
6a8e7cae 280 global $draft_folder, $save_as_draft;
281 return $save_as_draft &&
ceb7ad3c 282 ( $box == $draft_folder ||
283 ($include_subs && isBoxBelow($box, $draft_folder)) );
6a8e7cae 284}
285
48af4b64 286/**
d43853c7 287 * Expunges a mailbox
f8a1ed5a 288 *
d43853c7 289 * WARNING: Select mailbox before calling this function.
f8a1ed5a 290 *
291 * permanently removes all messages that have the \Deleted flag
292 * set from the selected mailbox. See EXPUNGE command chapter in
d43853c7 293 * IMAP RFC.
294 * @param stream $imap_stream imap connection resource
295 * @param string $mailbox mailbox name (unused since 1.1.3).
296 * @param boolean $handle_errors error handling control (displays error_box on error).
297 * @param mixed $id (since 1.3.0) integer message id or array with integer ids
298 * @return integer number of expunged messages
3131bc8d 299 * @since 1.0 or older
48af4b64 300 */
8f6505f6 301function sqimap_mailbox_expunge ($imap_stream, $mailbox, $handle_errors = true, $id='') {
06b5c3ff 302 if ($id) {
ff245fbd 303 if (is_array($id)) {
304 $id = sqimap_message_list_squisher($id);
305 }
306 $id = ' '.$id;
9d8d1ebd 307 $uid = TRUE;
06b5c3ff 308 } else {
ff245fbd 309 $uid = false;
8f6505f6 310 }
06b5c3ff 311 $read = sqimap_run_command($imap_stream, 'EXPUNGE'.$id, $handle_errors,
312 $response, $message, $uid);
63240b90 313 $cnt = 0;
ff245fbd 314
315 if (is_array($read)) {
63240b90 316 foreach ($read as $r) {
ff245fbd 317 if (preg_match('/^\*\s[0-9]+\sEXPUNGE/AUi',$r,$regs)) {
318 $cnt++;
319 }
63240b90 320 }
8f6505f6 321 }
ff245fbd 322 return $cnt;
43b698c7 323}
324
48af4b64 325/**
326 * Checks whether or not the specified mailbox exists
a462b928 327 *
d43853c7 328 * @param stream $imap_stream imap connection resource
329 * @param string $mailbox mailbox name
92ffe525 330 * @param array $mailboxlist (since 1.5.1) optional array of mailboxes from
a462b928 331 * sqimap_get_mailboxes() (to avoid having to talk to imap server)
d43853c7 332 * @return boolean
333 * @since 1.0 or older
48af4b64 334 */
a462b928 335function sqimap_mailbox_exists ($imap_stream, $mailbox, $mailboxlist=null) {
247f700e 336 if (!isset($mailbox) || empty($mailbox)) {
43b698c7 337 return false;
338 }
a462b928 339
340 if (is_array($mailboxlist)) {
341 // use previously retrieved mailbox list
342 foreach ($mailboxlist as $mbox) {
343 if ($mbox['unformatted-dm'] == $mailbox) { return true; }
344 }
345 return false;
346 } else {
347 // go to imap server
348 $mbx = sqimap_run_command($imap_stream, 'LIST "" ' . sqimap_encode_mailbox_name($mailbox),
349 true, $response, $message);
350 return isset($mbx[0]);
351 }
43b698c7 352}
353
48af4b64 354/**
355 * Selects a mailbox
3d548be7 356 * Before 1.3.0 used more arguments and returned data depended on those arguments.
d43853c7 357 * @param stream $imap_stream imap connection resource
358 * @param string $mailbox mailbox name
f8a1ed5a 359 * @return array results of select command (on success - permanentflags, flags and rights)
d43853c7 360 * @since 1.0 or older
48af4b64 361 */
e4c6fe41 362function sqimap_mailbox_select ($imap_stream, $mailbox) {
92ffe525 363 // FIX ME: WHAAAA DO NOT USE "None" for something that does not exist. Use false or NULL instead
ff245fbd 364 if ($mailbox == 'None') {
43b698c7 365 return;
366 }
92ffe525 367 // cleanup $mailbox in order to prevent IMAP injection attacks
368 $mailbox = str_replace(array("\r","\n"), array("",""),$mailbox);
568cb884 369 $read = sqimap_run_command($imap_stream, 'SELECT ' . sqimap_encode_mailbox_name($mailbox),
3411d4ec 370 true, $response, $message);
e4c6fe41 371 $result = array();
ff245fbd 372 for ($i = 0, $cnt = count($read); $i < $cnt; $i++) {
e4c6fe41 373 if (preg_match('/^\*\s+OK\s\[(\w+)\s(\w+)\]/',$read[$i], $regs)) {
ff245fbd 374 $result[strtoupper($regs[1])] = $regs[2];
375 } else if (preg_match('/^\*\s([0-9]+)\s(\w+)/',$read[$i], $regs)) {
376 $result[strtoupper($regs[2])] = $regs[1];
377 } else {
378 if (preg_match("/PERMANENTFLAGS(.*)/i",$read[$i], $regs)) {
379 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/","/\]/") ,'', $regs[1])) ;
4669e892 380 $result['PERMANENTFLAGS'] = explode(' ',strtolower($regs[1]));
ff245fbd 381 } else if (preg_match("/FLAGS(.*)/i",$read[$i], $regs)) {
382 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/") ,'', $regs[1])) ;
4669e892 383 $result['FLAGS'] = explode(' ',strtolower($regs[1]));
ff245fbd 384 }
385 }
e4c6fe41 386 }
4669e892 387 if (!isset($result['PERMANENTFLAGS'])) {
388 $result['PERMANENTFLAGS'] = $result['FLAGS'];
389 }
e4c6fe41 390 if (preg_match('/^\[(.+)\]/',$message, $regs)) {
4669e892 391 $result['RIGHTS']=strtoupper($regs[1]);
e4c6fe41 392 }
f69feefe 393
e4c6fe41 394 return $result;
43b698c7 395}
396
48af4b64 397/**
398 * Creates a folder.
d43853c7 399 *
400 * Mailbox is automatically subscribed.
f8a1ed5a 401 *
402 * Set $type to string that does not match 'noselect' (case insensitive),
403 * if you don't want to prepend delimiter to mailbox name. Please note
404 * that 'noinferiors' might be used someday as keyword for folders
d43853c7 405 * that store only messages.
406 * @param stream $imap_steam imap connection resource
407 * @param string $mailbox mailbox name
408 * @param string $type folder type.
409 * @since 1.0 or older
48af4b64 410 */
3411d4ec 411function sqimap_mailbox_create ($imap_stream, $mailbox, $type) {
43b698c7 412 global $delimiter;
413 if (strtolower($type) == 'noselect') {
5221db27 414 $create_mailbox = $mailbox . $delimiter;
415 } else {
416 $create_mailbox = $mailbox;
43b698c7 417 }
e429f014 418
48af4b64 419 $read_ary = sqimap_run_command($imap_stream, 'CREATE ' .
5221db27 420 sqimap_encode_mailbox_name($create_mailbox),
3411d4ec 421 true, $response, $message);
43b698c7 422 sqimap_subscribe ($imap_stream, $mailbox);
423}
424
48af4b64 425/**
426 * Subscribes to an existing folder.
d43853c7 427 * @param stream $imap_stream imap connection resource
428 * @param string $mailbox mailbox name
429 * @param boolean $debug (since 1.5.1)
430 * @since 1.0 or older
48af4b64 431 */
852abae7 432function sqimap_subscribe ($imap_stream, $mailbox,$debug=true) {
48af4b64 433 $read_ary = sqimap_run_command($imap_stream, 'SUBSCRIBE ' .
434 sqimap_encode_mailbox_name($mailbox),
852abae7 435 $debug, $response, $message);
43b698c7 436}
437
48af4b64 438/**
439 * Unsubscribes from an existing folder
d43853c7 440 * @param stream $imap_stream imap connection resource
441 * @param string $mailbox mailbox name
442 * @since 1.0 or older
48af4b64 443 */
3411d4ec 444function sqimap_unsubscribe ($imap_stream, $mailbox) {
48af4b64 445 $read_ary = sqimap_run_command($imap_stream, 'UNSUBSCRIBE ' .
446 sqimap_encode_mailbox_name($mailbox),
e2e8b92b 447 false, $response, $message);
43b698c7 448}
449
48af4b64 450/**
451 * Deletes the given folder
3131bc8d 452 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
453 * @param stream $imap_stream imap connection resource
454 * @param string $mailbox mailbox name
455 * @since 1.0 or older
48af4b64 456 */
3411d4ec 457function sqimap_mailbox_delete ($imap_stream, $mailbox) {
78cc4b12 458 global $data_dir, $username;
e2e8b92b 459 sqimap_unsubscribe ($imap_stream, $mailbox);
c957afd1 460
461 if (sqimap_mailbox_exists($imap_stream, $mailbox)) {
462
463 $read_ary = sqimap_run_command($imap_stream, 'DELETE ' .
464 sqimap_encode_mailbox_name($mailbox),
465 true, $response, $message);
466 if ($response !== 'OK') {
467 // subscribe again
468 sqimap_subscribe ($imap_stream, $mailbox);
469 } else {
470 do_hook_function('rename_or_delete_folder', $args = array($mailbox, 'delete', ''));
471 removePref($data_dir, $username, "thread_$mailbox");
472 removePref($data_dir, $username, "collapse_folder_$mailbox");
473 }
e2e8b92b 474 }
43b698c7 475}
476
48af4b64 477/**
478 * Determines if the user is subscribed to the folder or not
3131bc8d 479 * @param stream $imap_stream imap connection resource
480 * @param string $mailbox mailbox name
481 * @return boolean
482 * @since 1.2.0
48af4b64 483 */
1da22cda 484function sqimap_mailbox_is_subscribed($imap_stream, $folder) {
1da22cda 485 $boxesall = sqimap_mailbox_list ($imap_stream);
486 foreach ($boxesall as $ref) {
43b698c7 487 if ($ref['unformatted'] == $folder) {
3411d4ec 488 return true;
43b698c7 489 }
490 }
491 return false;
492}
493
48af4b64 494/**
495 * Renames a mailbox.
3131bc8d 496 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
497 * @param stream $imap_stream imap connection resource
498 * @param string $old_name mailbox name
499 * @param string $new_name new mailbox name
500 * @since 1.2.3
48af4b64 501 */
1c52ba77 502function sqimap_mailbox_rename( $imap_stream, $old_name, $new_name ) {
3411d4ec 503 if ( $old_name != $new_name ) {
78cc4b12 504 global $delimiter, $imap_server_type, $data_dir, $username;
1c52ba77 505 if ( substr( $old_name, -1 ) == $delimiter ) {
506 $old_name = substr( $old_name, 0, strlen( $old_name ) - 1 );
507 $new_name = substr( $new_name, 0, strlen( $new_name ) - 1 );
508 $postfix = $delimiter;
1c52ba77 509 } else {
510 $postfix = '';
1c52ba77 511 }
68f2ce7a 512
5659ad2e 513 $boxesall = sqimap_mailbox_list_all($imap_stream);
48af4b64 514 $cmd = 'RENAME ' . sqimap_encode_mailbox_name($old_name) .
91e0dccc 515 ' ' . sqimap_encode_mailbox_name($new_name);
3411d4ec 516 $data = sqimap_run_command($imap_stream, $cmd, true, $response, $message);
1c52ba77 517 sqimap_unsubscribe($imap_stream, $old_name.$postfix);
5659ad2e 518 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$old_name.$postfix);
519 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
68f2ce7a 520 removePref($data_dir, $username, 'thread_'.$old_name.$postfix);
5659ad2e 521 removePref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
1c52ba77 522 sqimap_subscribe($imap_stream, $new_name.$postfix);
5659ad2e 523 setPref($data_dir, $username, 'thread_'.$new_name.$postfix, $oldpref_thread);
524 setPref($data_dir, $username, 'collapse_folder_'.$new_name.$postfix, $oldpref_collapse);
e429f014 525 do_hook_function('rename_or_delete_folder',$args = array($old_name, 'rename', $new_name));
648713af 526 $l = strlen( $old_name ) + 1;
527 $p = 'unformatted';
68f2ce7a 528
ff245fbd 529 foreach ($boxesall as $box) {
530 if (substr($box[$p], 0, $l) == $old_name . $delimiter) {
648713af 531 $new_sub = $new_name . $delimiter . substr($box[$p], $l);
5659ad2e 532 /* With Cyrus IMAPd >= 2.0 rename is recursive, so don't check for errors here */
648713af 533 if ($imap_server_type == 'cyrus') {
68f2ce7a 534 $cmd = 'RENAME "' . $box[$p] . '" "' . $new_sub . '"';
5659ad2e 535 $data = sqimap_run_command($imap_stream, $cmd, false,
648713af 536 $response, $message);
1c52ba77 537 }
5659ad2e 538 $was_subscribed = sqimap_mailbox_is_subscribed($imap_stream, $box[$p]);
539 if ( $was_subscribed ) {
540 sqimap_unsubscribe($imap_stream, $box[$p]);
541 }
542 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$box[$p]);
543 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$box[$p]);
68f2ce7a 544 removePref($data_dir, $username, 'thread_'.$box[$p]);
5659ad2e 545 removePref($data_dir, $username, 'collapse_folder_'.$box[$p]);
546 if ( $was_subscribed ) {
547 sqimap_subscribe($imap_stream, $new_sub);
548 }
549 setPref($data_dir, $username, 'thread_'.$new_sub, $oldpref_thread);
550 setPref($data_dir, $username, 'collapse_folder_'.$new_sub, $oldpref_collapse);
68f2ce7a 551 do_hook_function('rename_or_delete_folder',
3411d4ec 552 $args = array($box[$p], 'rename', $new_sub));
1c52ba77 553 }
554 }
1c52ba77 555 }
1c52ba77 556}
43b698c7 557
48af4b64 558/**
86c2763d 559 * Formats a mailbox into parts for the $boxesall array
3411d4ec 560 *
86c2763d 561 * The parts are:
3131bc8d 562 * <ul>
563 * <li>raw - Raw LIST/LSUB response from the IMAP server
564 * <li>formatted - nicely formatted folder name
565 * <li>unformatted - unformatted, but with delimiter at end removed
566 * <li>unformatted-dm - folder name as it appears in raw response
567 * <li>unformatted-disp - unformatted without $folder_prefix
568 * <li>id - TODO: document me
569 * <li>flags - TODO: document me
570 * </ul>
571 * Before 1.2.0 used third argument for delimiter.
a462b928 572 *
573 * Before 1.5.1 used second argument for lsub line. Argument was removed in order to use
92ffe525 574 * find_mailbox_name() on the raw input. Since 1.5.1 includes RFC3501 names in flags
a462b928 575 * array (for example, "\NoSelect" in addition to "noselect")
576 * @param array $line
3131bc8d 577 * @return array
578 * @since 1.0 or older
579 * @todo document id and flags keys in boxes array and function arguments.
3411d4ec 580 */
a462b928 581function sqimap_mailbox_parse ($line) {
43b698c7 582 global $folder_prefix, $delimiter;
3411d4ec 583
43b698c7 584 /* Process each folder line */
cef054e4 585 for ($g = 0, $cnt = count($line); $g < $cnt; ++$g) {
43b698c7 586 /* Store the raw IMAP reply */
587 if (isset($line[$g])) {
e429f014 588 $boxesall[$g]['raw'] = $line[$g];
ff245fbd 589 } else {
e429f014 590 $boxesall[$g]['raw'] = '';
43b698c7 591 }
3411d4ec 592
43b698c7 593 /* Count number of delimiters ($delimiter) in folder name */
a462b928 594 $mailbox = find_mailbox_name($line[$g]);
ff245fbd 595 $dm_count = substr_count($mailbox, $delimiter);
43b698c7 596 if (substr($mailbox, -1) == $delimiter) {
3411d4ec 597 /* If name ends in delimiter, decrement count by one */
598 $dm_count--;
43b698c7 599 }
3411d4ec 600
601 /* Format folder name, but only if it's a INBOX.* or has a parent. */
1da22cda 602 $boxesallbyname[$mailbox] = $g;
43b698c7 603 $parentfolder = readMailboxParent($mailbox, $delimiter);
604 if ( (strtolower(substr($mailbox, 0, 5)) == "inbox") ||
605 (substr($mailbox, 0, strlen($folder_prefix)) == $folder_prefix) ||
ff245fbd 606 (isset($boxesallbyname[$parentfolder]) &&
607 (strlen($parentfolder) > 0) ) ) {
608 $indent = $dm_count - (substr_count($folder_prefix, $delimiter));
43b698c7 609 if ($indent > 0) {
ff245fbd 610 $boxesall[$g]['formatted'] = str_repeat('&nbsp;&nbsp;', $indent);
611 } else {
1da22cda 612 $boxesall[$g]['formatted'] = '';
43b698c7 613 }
447b2166 614 $boxesall[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
ff245fbd 615 } else {
447b2166 616 $boxesall[$g]['formatted'] = imap_utf7_decode_local($mailbox);
43b698c7 617 }
90de1755 618
1da22cda 619 $boxesall[$g]['unformatted-dm'] = $mailbox;
43b698c7 620 if (substr($mailbox, -1) == $delimiter) {
8e9e8afa 621 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
43b698c7 622 }
1da22cda 623 $boxesall[$g]['unformatted'] = $mailbox;
43b698c7 624 if (substr($mailbox,0,strlen($folder_prefix))==$folder_prefix) {
631b9da3 625 $mailbox = substr($mailbox, strlen($folder_prefix));
43b698c7 626 }
1da22cda 627 $boxesall[$g]['unformatted-disp'] = $mailbox;
628 $boxesall[$g]['id'] = $g;
90de1755 629
1da22cda 630 $boxesall[$g]['flags'] = array();
43b698c7 631 if (isset($line[$g])) {
36dfb0c9 632 ereg("\(([^)]*)\)",$line[$g],$regs);
a462b928 633 /**
634 * Since 1.5.1 flags are stored with RFC3501 naming
635 * and also the old way for backwards compatibility
636 * so for example "\NoSelect" and "noselect"
637 */
638 $flags = trim($regs[1]);
43b698c7 639 if ($flags) {
a462b928 640 $flagsarr = explode(' ',$flags);
641 $flagsarrnew=$flagsarr;
642 // add old type
643 foreach ($flagsarr as $flag) {
644 $flagsarrnew[]=strtolower(str_replace('\\', '',$flag));
645 }
646 $boxesall[$g]['flags']=$flagsarrnew;
43b698c7 647 }
648 }
649 }
1da22cda 650 return $boxesall;
43b698c7 651}
652
48af4b64 653/**
be2d5495 654 * Returns list of options (to be echoed into select statement
655 * based on available mailboxes and separators
6fd95361 656 * Caller should surround options with <select ...> </select> and
be2d5495 657 * any formatting.
3131bc8d 658 * @param stream $imap_stream imap connection resource to query for mailboxes
659 * @param array $show_selected array containing list of mailboxes to pre-select (0 if none)
660 * @param array $folder_skip array of folders to keep out of option list (compared in lower)
661 * @param $boxes list of already fetched boxes (for places like folder panel, where
be2d5495 662 * you know these options will be shown 3 times in a row.. (most often unset).
3131bc8d 663 * @param string $flag (since 1.4.1) flag to check for in mailbox flags, used to filter out mailboxes.
59a8e3e8 664 * 'noselect' by default to remove unselectable mailboxes.
665 * 'noinferiors' used to filter out folders that can not contain subfolders.
666 * NULL to avoid flag check entirely.
d0928dd5 667 * NOTE: noselect and noiferiors are used internally. The IMAP representation is
668 * \NoSelect and \NoInferiors
3131bc8d 669 * @param boolean $use_long_format (since 1.4.1) override folder display preference and always show full folder name.
670 * @return string html formated mailbox selection options
671 * @since 1.3.2
be2d5495 672 */
4669e892 673function sqimap_mailbox_option_list($imap_stream, $show_selected = 0, $folder_skip = 0, $boxes = 0,
59a8e3e8 674 $flag = 'noselect', $use_long_format = false ) {
dbd9ce25 675 global $username, $data_dir, $translate_special_folders, $sent_folder,
676 $trash_folder, $draft_folder;
677
678 $delimiter = sqimap_get_delimiter($imap_stream);
679
be2d5495 680 $mbox_options = '';
45f836eb 681 if ( $use_long_format ) {
682 $shorten_box_names = 0;
683 } else {
684 $shorten_box_names = getPref($data_dir, $username, 'mailbox_select_style', SMPREF_OFF);
685 }
ff245fbd 686
687 if ($boxes == 0) {
be2d5495 688 $boxes = sqimap_mailbox_list($imap_stream);
ff245fbd 689 }
59a8e3e8 690
be2d5495 691 foreach ($boxes as $boxes_part) {
4df5d823 692 if ($flag == NULL || (is_array($boxes_part['flags'])
693 && !in_array($flag, $boxes_part['flags']))) {
be2d5495 694 $box = $boxes_part['unformatted'];
be2d5495 695
d0928dd5 696 if ($folder_skip != 0 && in_array($box, $folder_skip) ) {
be2d5495 697 continue;
698 }
4669e892 699 $lowerbox = strtolower($box);
5c300c60 700 // mailboxes are casesensitive => inbox.sent != inbox.Sent
701 // nevermind, to many dependencies this should be fixed!
4669e892 702
d0928dd5 703 if (strtolower($box) == 'inbox') { // inbox is special and not casesensitive
be2d5495 704 $box2 = _("INBOX");
4669e892 705 } else {
5c300c60 706 switch ($shorten_box_names)
707 {
708 case 2: /* delimited, style = 2 */
dbd9ce25 709 if ($translate_special_folders && $boxes_part['unformatted-dm']==$sent_folder) {
710 /*
711 * calculate pad level from number of delimiters. do it inside if control in order
712 * to reduce number of calculations. Other folders don't need it.
713 */
714 $pad = str_pad('',7 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'.&nbsp;');
715 // i18n: Name of Sent folder
716 $box2 = $pad . _("Sent");
717 } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$trash_folder) {
718 $pad = str_pad('',7 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'.&nbsp;');
719 // i18n: Name of Trash folder
720 $box2 = $pad . _("Trash");
721 } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$draft_folder) {
722 $pad = str_pad('',7 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'.&nbsp;');
723 // i18n: Name of Drafts folder
724 $box2 = $pad . _("Drafts");
725 } else {
726 $box2 = str_replace('&amp;nbsp;&amp;nbsp;', '.&nbsp;', htmlspecialchars($boxes_part['formatted']));
727 }
5c300c60 728 break;
d0928dd5 729 case 1: /* indent, style = 1 */
dbd9ce25 730 if ($translate_special_folders && $boxes_part['unformatted-dm']==$sent_folder) {
731 $pad = str_pad('',12 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'&nbsp;&nbsp;');
732 $box2 = $pad . _("Sent");
733 } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$trash_folder) {
734 $pad = str_pad('',12 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'&nbsp;&nbsp;');
735 $box2 = $pad . _("Trash");
736 } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$draft_folder) {
737 $pad = str_pad('',12 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'&nbsp;&nbsp;');
738 $box2 = $pad . _("Drafts");
739 } else {
740 $box2 = str_replace('&amp;nbsp;&amp;nbsp;', '&nbsp;&nbsp;', htmlspecialchars($boxes_part['formatted']));
741 }
5c300c60 742 break;
d0928dd5 743 default: /* default, long names, style = 0 */
6c4f0fa1 744 $box2 = str_replace(' ', '&nbsp;', htmlspecialchars(imap_utf7_decode_local($boxes_part['unformatted-disp'])));
5c300c60 745 break;
746 }
be2d5495 747 }
748 if ($show_selected != 0 && in_array($lowerbox, $show_selected) ) {
ff0969a0 749 $mbox_options .= '<option value="' . htmlspecialchars($box) .'" selected="selected">'.$box2.'</option>' . "\n";
be2d5495 750 } else {
ff0969a0 751 $mbox_options .= '<option value="' . htmlspecialchars($box) .'">'.$box2.'</option>' . "\n";
be2d5495 752 }
753 }
754 }
755 return $mbox_options;
756}
43b698c7 757
48af4b64 758/**
4669e892 759 * Returns sorted mailbox lists in several different ways.
a462b928 760 *
761 * Since 1.5.1 most of the functionality has been moved to new function sqimap_get_mailboxes
762 *
3411d4ec 763 * See comment on sqimap_mailbox_parse() for info about the returned array.
3e9441a2 764 * @param resource $imap_stream imap connection resource
765 * @param boolean $force force update of mailbox listing. available since 1.4.2 and 1.5.0
766 * @return array list of mailboxes
3131bc8d 767 * @since 1.0 or older
3411d4ec 768 */
fe6efa94 769function sqimap_mailbox_list($imap_stream, $force=false) {
a462b928 770 global $boxesnew,$show_only_subscribed_folders;
fe6efa94 771 if (!sqgetGlobalVar('boxesnew',$boxesnew,SQ_SESSION) || $force) {
a462b928 772 $boxesnew=sqimap_get_mailboxes($imap_stream,$force,$show_only_subscribed_folders);
773 }
774 return $boxesnew;
775}
4669e892 776
a462b928 777/**
778 * Returns a list of all folders, subscribed or not
779 *
780 * Since 1.5.1 code moved to sqimap_get_mailboxes()
781 *
782 * @param stream $imap_stream imap connection resource
783 * @return array see sqimap_mailbox_parse()
784 * @since 1.0 or older
785 */
786function sqimap_mailbox_list_all($imap_stream) {
787 global $show_only_subscribed_folders;
788 // fourth argument prevents registration of retrieved list of mailboxes in session
789 $boxes=sqimap_get_mailboxes($imap_stream,true,false,false);
790 return $boxes;
791}
7e235a1a 792
159d2af7 793
a462b928 794/**
795 * Gets the list of mailboxes for sqimap_maolbox_tree and sqimap_mailbox_list
796 *
797 * This is because both of those functions had duplicated logic, but with slightly different
798 * implementations. This will make both use the same implementation, which should make it
799 * easier to maintain and easier to modify in the future
800 * @param stream $imap_stream imap connection resource
801 * @param bool $force force a reload and ignore cache
802 * @param bool $show_only_subscribed controls listing of visible or all folders
803 * @param bool $session_register controls registration of retrieved data in session.
804 * @return object boxesnew - array of mailboxes and their attributes
805 * @since 1.5.1
806 */
807function sqimap_get_mailboxes($imap_stream,$force=false,$show_only_subscribed=true,$session_register=true) {
808 global $show_only_subscribed_folders,$noselect_fix_enable,$folder_prefix,
809 $list_special_folders_first,$imap_server_type;
810 $inbox_subscribed = false;
811 $listsubscribed = sqimap_capability($imap_stream,'LIST-SUBSCRIBED');
cef054e4 812
a462b928 813 if ($show_only_subscribed) { $show_only_subscribed=$show_only_subscribed_folders; }
fe6efa94 814
202bcbcc 815 //require_once(SM_PATH . 'include/load_prefs.php');
4669e892 816
a462b928 817 /**
818 * There are three main listing commands we can use in IMAP:
819 * LSUB shows just the list of subscribed folders
820 * may include flags, but these are not necessarily accurate or authoratative
92ffe525 821 * \NoSelect has special meaning: the folder does not exist -OR- it means this
a462b928 822 * folder is not subscribed but children may be
823 * [RFC-2060]
824 * LIST this shows every mailbox on the system
825 * flags are always included and are accurate and authoratative
826 * \NoSelect means folder should not be selected
827 * [RFC-2060]
828 * LIST (SUBSCRIBED) implemented with LIST-SUBSCRIBED extension
829 * this is like list but returns only subscribed folders
830 * flag meanings are like LIST, not LSUB
831 * \NonExistent means mailbox doesn't exist
832 * \PlaceHolder means parent is not valid (selectable), but one or more children are
833 * \NoSelect indeed means that the folder should not be selected
834 * IMAPEXT-LIST-EXTENSIONS-04 August 2003 B. Leiba
835 */
836 if (!$show_only_subscribed) {
837 $lsub = 'LIST';
838 $sub_cache_name='list_cache';
839 } elseif ($listsubscribed) {
840 $lsub = 'LIST (SUBSCRIBED)';
841 $sub_cache_name='listsub_cache';
842 } else {
843 $lsub = 'LSUB';
844 $sub_cache_name='lsub_cache';
845 }
4669e892 846
a462b928 847 // Some IMAP servers allow subfolders to exist even if the parent folders do not
848 // This fixes some problems with the folder list when this is the case, causing the
849 // NoSelect folders to be displayed
850 if ($noselect_fix_enable) {
851 $lsub_args = "$lsub \"$folder_prefix\" \"*%\"";
852 $list_args = "LIST \"$folder_prefix\" \"*%\"";
853 } else {
854 $lsub_args = "$lsub \"$folder_prefix\" \"*\"";
855 $list_args = "LIST \"$folder_prefix\" \"*\"";
856 }
7e235a1a 857
a462b928 858 // get subscribed mailbox list from cache (session)
859 // if not there, then get it from the imap server and store in cache
7e235a1a 860
a462b928 861 if (!$force) {
862 sqgetGlobalVar($sub_cache_name,$lsub_cache,SQ_SESSION);
863 }
7e235a1a 864
76682066 865 $lsub_assoc_ary=array();
a462b928 866 if (!empty($lsub_cache)) {
867 $lsub_assoc_ary=$lsub_cache;
868 } else {
869 $lsub_ary = sqimap_run_command ($imap_stream, $lsub_args, true, $response, $message);
870 $lsub_ary = compact_mailboxes_response($lsub_ary);
871 if (!empty($lsub_ary)) {
872 foreach ($lsub_ary as $rawline) {
873 $temp_mailbox_name=find_mailbox_name($rawline);
874 $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
7e235a1a 875 }
a462b928 876 unset($lsub_ary);
877 sqsession_register($lsub_assoc_ary,$sub_cache_name);
878 }
879 }
880
881 // Now to get the mailbox flags
882 // The LSUB response may return \NoSelect flags, etc. but it is optional
883 // according to RFC3501, and even when returned it may not be accurate
884 // or authoratative. LIST will always return accurate results.
885 if (($lsub == 'LIST') || ($lsub == 'LIST (SUBSCRIBED)')) {
886 // we've already done a LIST or LIST (SUBSCRIBED)
887 // and NOT a LSUB, so no need to do it again
888 $list_assoc_ary = $lsub_assoc_ary;
889 } else {
92ffe525 890 // we did a LSUB so now we need to do a LIST
a462b928 891 // first see if it is in cache
892 $list_cache_name='list_cache';
893 if (!$force) {
894 sqgetGlobalVar($list_cache_name,$list_cache,SQ_SESSION);
7e235a1a 895 }
a462b928 896
897 if (!empty($list_cache)) {
898 $list_assoc_ary=$list_cache;
899 // we could store this in list_cache_name but not necessary
900 } else {
901 // not in cache so we need to go get it from the imap server
902 $list_assoc_ary = array();
903 $list_ary = sqimap_run_command($imap_stream, $list_args,
904 true, $response, $message);
905 $list_ary = compact_mailboxes_response($list_ary);
906 if (!empty($list_ary)) {
907 foreach ($list_ary as $rawline) {
908 $temp_mailbox_name=find_mailbox_name($rawline);
909 $list_assoc_ary[$temp_mailbox_name]=$rawline;
7e235a1a 910 }
a462b928 911 unset($list_ary);
912 sqsession_register($list_assoc_ary,$list_cache_name);
5c300c60 913 }
914 }
a462b928 915 }
c3ce607e 916
a462b928 917 // If they aren't subscribed to the inbox, then add it anyway (if its in LIST)
918 $inbox_subscribed=false;
919 if (!empty($lsub_assoc_ary)) {
920 foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
921 if (strtoupper($temp_mailbox_name) == 'INBOX') {
922 $inbox_subscribed=true;
f8a1ed5a 923 }
c3ce607e 924 }
a462b928 925 }
926 if (!$inbox_subscribed) {
927 if (!empty($list_assoc_ary)) {
928 foreach ($list_assoc_ary as $temp_mailbox_name=>$rawline) {
929 if (strtoupper($temp_mailbox_name) == 'INBOX') {
930 $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
931 }
932 }
933 }
934 }
f8a1ed5a 935
a462b928 936 // Now we have the raw output, we need to create an array of mailbox names we will return
937 if (!$show_only_subscribed) {
938 $final_folders_assoc_ary=$list_assoc_ary;
939 } else {
940 /**
941 * only show subscribed folders
942 * we need to merge the folders here... we can't trust the flags, etc. from the lsub_assoc_array
943 * so we use the lsub_assoc_array as the list of folders and the values come from list_assoc_array
944 */
945 if (!empty($lsub_assoc_ary)) {
946 foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
947 if (!empty($list_assoc_ary[$temp_mailbox_name])) {
948 $final_folders_assoc_ary[$temp_mailbox_name]=$list_assoc_ary[$temp_mailbox_name];
949 }
7e235a1a 950 }
951 }
43b698c7 952 }
43b698c7 953
bac13dd7 954
a462b928 955 // Now produce a flat, sorted list
956 if (!empty($final_folders_assoc_ary)) {
957 uksort($final_folders_assoc_ary,'strnatcasecmp');
958 foreach ($final_folders_assoc_ary as $temp_mailbox_name=>$rawline) {
959 $final_folders_ary[]=$rawline;
960 }
961 }
bac13dd7 962
a462b928 963 // this will put it into an array we can use later
964 // containing:
965 // raw - Raw LIST/LSUB response from the IMAP server
966 // formatted - formatted folder name
967 // unformatted - unformatted, but with the delimiter at the end removed
968 // unformated-dm - folder name as it appears in raw response
969 // unformatted-disp - unformatted without $folder_prefix
970 // id - the array element number (0, 1, 2, etc.)
971 // flags - mailbox flags
972 if (!empty($final_folders_ary)) {
973 $boxesall = sqimap_mailbox_parse($final_folders_ary);
974 } else {
975 // they have no mailboxes
976 $boxesall=array();
977 }
90de1755 978
a462b928 979 /* Now, lets sort for special folders */
980 $boxesnew = $used = array();
90de1755 981
a462b928 982 /* Find INBOX */
983 $cnt = count($boxesall);
984 $used = array_pad($used,$cnt,false);
985 $has_inbox = false;
986 for($k = 0; $k < $cnt; ++$k) {
987 if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
988 $boxesnew[] = $boxesall[$k];
989 $used[$k] = true;
990 $has_inbox = true;
991 break;
992 }
993 }
92ffe525 994
a462b928 995 if ($has_inbox == false) {
996 // do a list request for inbox because we should always show
997 // inbox even if the user isn't subscribed to it.
998 $inbox_ary = sqimap_run_command($imap_stream, 'LIST "" "INBOX"',
999 true, $response, $message);
1000 $inbox_ary = compact_mailboxes_response($inbox_ary);
1001 if (count($inbox_ary)) {
1002 $inbox_entry = sqimap_mailbox_parse($inbox_ary);
1003 // add it on top of the list
1004 if (!empty($boxesnew)) {
1005 array_unshift($boxesnew,$inbox_entry[0]);
90de1755 1006 } else {
a462b928 1007 $boxesnew[]=$inbox_entry[0];
12d61439 1008 }
a462b928 1009 /* array_unshift($used,true); */
780dd344 1010 }
a462b928 1011 }
780dd344 1012
a462b928 1013 /* List special folders and their subfolders, if requested. */
1014 if ($list_special_folders_first) {
1015 for($k = 0; $k < $cnt; ++$k) {
1016 if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
1017 $boxesnew[] = $boxesall[$k];
1018 $used[$k] = true;
1019 }
780dd344 1020 }
a462b928 1021 }
1022
1023 /* Find INBOX's children */
1024 for($k = 0; $k < $cnt; ++$k) {
1025 $isboxbelow=isBoxBelow(strtoupper($boxesall[$k]['unformatted']),'INBOX');
1026 if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
1027 $is_inbox=1;
780dd344 1028 } else {
a462b928 1029 $is_inbox=0;
1030 }
1031
1032 if (!$used[$k] && $isboxbelow && $is_inbox) {
1033 $boxesnew[] = $boxesall[$k];
1034 $used[$k] = true;
43b698c7 1035 }
43b698c7 1036 }
90de1755 1037
a462b928 1038 /* Rest of the folders */
1039 for($k = 0; $k < $cnt; $k++) {
1040 if (!$used[$k]) {
1041 $boxesnew[] = $boxesall[$k];
1042 }
1043 }
1044 /**
1045 * Don't register boxes in session, if $session_register is set to false
1046 * Prevents registration of sqimap_mailbox_list_all() results.
1047 */
1048 if ($session_register) sqsession_register($boxesnew,'boxesnew');
1049 return $boxesnew;
43b698c7 1050}
5bdd7223 1051
3131bc8d 1052/**
4b2720f5 1053 * Fills mailbox object
1054 *
a462b928 1055 * this is passed the mailbox array by left_main.php
1056 * who has previously obtained it from sqimap_get_mailboxes
1057 * that way, the raw mailbox list is available in left_main to other
1058 * things besides just sqimap_mailbox_tree
1059 * imap_stream is just used now to get status info
1060 *
1061 * most of the functionality is moved to sqimap_get_mailboxes
1062 * also takes care of TODO items:
1063 * caching mailbox tree
1064 * config setting for UW imap section (not needed now)
1065 *
4b2720f5 1066 * Some code fragments are present in 1.3.0 - 1.4.4.
3131bc8d 1067 * @param stream $imap_stream imap connection resource
a462b928 1068 * @param array $lsub_ary output array from sqimap_get_mailboxes (contains mailboxes and flags)
3131bc8d 1069 * @return object see mailboxes class.
4b2720f5 1070 * @since 1.5.0
3131bc8d 1071 */
a462b928 1072function sqimap_mailbox_tree($imap_stream,$lsub_ary) {
bac13dd7 1073
4b2720f5 1074 $sorted_lsub_ary = array();
1075 $cnt = count($lsub_ary);
1076 for ($i = 0; $i < $cnt; $i++) {
a462b928 1077 $mbx=$lsub_ary[$i]['unformatted'];
1078 $flags=$lsub_ary[$i]['flags'];
1079
1080 $noinferiors=0;
1081 if (in_array('\Noinferiors',$flags)) { $noinferiors=1; }
1082 if (in_array('\NoInferiors',$flags)) { $noinferiors=1; }
1083 if (in_array('\HasNoChildren',$flags)) { $noinferiors=1; }
1084
1085 $noselect=0;
92ffe525 1086 if (in_array('\NoSelect',$flags)) { $noselect=1; }
a462b928 1087 /**
1088 * LIST (SUBSCRIBED) has two new flags, \NonExistent which means the mailbox is subscribed to
1089 * but doesn't exist, and \PlaceHolder which is similar (but not the same) as \NoSelect
1090 * For right now, we'll treat these the same as \NoSelect and this behavior can be changed
1091 * later if needed
1092 */
92ffe525 1093 if (in_array('\NonExistent',$flags)) { $noselect=1; }
a462b928 1094 if (in_array('\PlaceHolder',$flags)) { $noselect=1; }
4b2720f5 1095 $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
1096 }
a462b928 1097
4b2720f5 1098 $sorted_lsub_ary = array_values($sorted_lsub_ary);
1099 usort($sorted_lsub_ary, 'mbxSort');
1100 $boxestree = sqimap_fill_mailbox_tree($sorted_lsub_ary,false,$imap_stream);
1101 return $boxestree;
60b5724d 1102}
1103
3131bc8d 1104/**
1105 * Callback function used for sorting mailboxes in sqimap_mailbox_tree
1106 * @param string $a
1107 * @param string $b
1108 * @return integer see php strnatcasecmp()
1109 * @since 1.5.1
1110 */
9d8d1ebd 1111function mbxSort($a, $b) {
1112 return strnatcasecmp($a['mbx'], $b['mbx']);
1113}
1114
3131bc8d 1115/**
4b2720f5 1116 * Fills mailbox object
1117 *
1118 * Some code fragments are present in 1.3.0 - 1.4.4.
3131bc8d 1119 * @param array $mbx_ary
1120 * @param $mbxs
4b2720f5 1121 * @param stream $imap_stream imap connection resource
3131bc8d 1122 * @return object see mailboxes class
4b2720f5 1123 * @since 1.5.0
3131bc8d 1124 */
483f9ef9 1125function sqimap_fill_mailbox_tree($mbx_ary, $mbxs=false,$imap_stream) {
60b5724d 1126 global $data_dir, $username, $list_special_folders_first,
1127 $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
1128 $move_to_trash, $move_to_sent, $save_as_draft,
43a31298 1129 $delimiter, $imap_server_type;
60b5724d 1130
8d8da447 1131 // $special_folders = array ('INBOX', $sent_folder, $draft_folder, $trash_folder);
ff245fbd 1132
60b5724d 1133 /* create virtual root node */
1134 $mailboxes= new mailboxes();
1135 $mailboxes->is_root = true;
ff245fbd 1136 $trail_del = false;
78bc908d 1137 $start = 0;
1138
43a31298 1139 if (isset($folder_prefix) && ($folder_prefix != '')) {
ff245fbd 1140 $start = substr_count($folder_prefix,$delimiter);
1141 if (strrpos($folder_prefix, $delimiter) == (strlen($folder_prefix)-1)) {
ff245fbd 1142 $mailboxes->mailboxname_full = substr($folder_prefix,0, (strlen($folder_prefix)-1));
1143 } else {
1144 $mailboxes->mailboxname_full = $folder_prefix;
1145 $start++;
1146 }
1147 $mailboxes->mailboxname_sub = $mailboxes->mailboxname_full;
1148 } else {
1149 $start = 0;
1150 }
78bc908d 1151
9d8d1ebd 1152 $cnt = count($mbx_ary);
e4c6fe41 1153 for ($i=0; $i < $cnt; $i++) {
ff245fbd 1154 if ($mbx_ary[$i]['mbx'] !='' ) {
1155 $mbx = new mailboxes();
1156 $mailbox = $mbx_ary[$i]['mbx'];
cc82c2b7 1157
4669e892 1158 /*
ae9e2adc 1159 * Set the is_special flag if it concerned a special mailbox.
1160 * Used for displaying the special folders on top in the mailbox
1161 * tree displaying code.
1162 */
8edc9f31 1163 $mbx->is_special |= ($mbx->is_inbox = (strtoupper($mailbox) == 'INBOX'));
1164 $mbx->is_special |= ($mbx->is_trash = isTrashMailbox($mailbox));
1165 $mbx->is_special |= ($mbx->is_sent = isSentMailbox($mailbox));
1166 $mbx->is_special |= ($mbx->is_draft = isDraftMailbox($mailbox));
ae9e2adc 1167
8edc9f31 1168 if (!$mbx->is_special)
fda01075 1169 $mbx->is_special = boolean_hook_function('special_mailbox', $mailbox, 1);
4669e892 1170
ff245fbd 1171 if (isset($mbx_ary[$i]['unseen'])) {
1172 $mbx->unseen = $mbx_ary[$i]['unseen'];
1173 }
1174 if (isset($mbx_ary[$i]['nummessages'])) {
1175 $mbx->total = $mbx_ary[$i]['nummessages'];
1176 }
1177
1178 $mbx->is_noselect = $mbx_ary[$i]['noselect'];
86c2763d 1179 $mbx->is_noinferiors = $mbx_ary[$i]['noinferiors'];
ff245fbd 1180
60b5724d 1181 $r_del_pos = strrpos($mbx_ary[$i]['mbx'], $delimiter);
ff245fbd 1182 if ($r_del_pos) {
587ec647 1183 $mbx->mailboxname_sub = substr($mbx_ary[$i]['mbx'],$r_del_pos+1);
ff245fbd 1184 } else { /* mailbox is root folder */
587ec647 1185 $mbx->mailboxname_sub = $mbx_ary[$i]['mbx'];
ff245fbd 1186 }
1187 $mbx->mailboxname_full = $mbx_ary[$i]['mbx'];
38068e69 1188
9871bdaa 1189 $mailboxes->addMbx($mbx, $delimiter, $start, $list_special_folders_first);
ff245fbd 1190 }
60b5724d 1191 }
587ec647 1192 sqimap_utf7_decode_mbx_tree($mailboxes);
483f9ef9 1193 sqimap_get_status_mbx_tree($imap_stream,$mailboxes);
60b5724d 1194 return $mailboxes;
1195}
259faa39 1196
3131bc8d 1197/**
1198 * @param object $mbx_tree
1199 * @since 1.5.0
1200 */
587ec647 1201function sqimap_utf7_decode_mbx_tree(&$mbx_tree) {
3d548be7 1202 global $draft_folder, $sent_folder, $trash_folder, $translate_special_folders;
1203
1204 /* decode folder name and set mailboxname_sub */
1205 if ($translate_special_folders && strtoupper($mbx_tree->mailboxname_full) == 'INBOX') {
1206 $mbx_tree->mailboxname_sub = _("INBOX");
1207 } elseif ($translate_special_folders && $mbx_tree->mailboxname_full == $draft_folder) {
1208 $mbx_tree->mailboxname_sub = _("Drafts");
1209 } elseif ($translate_special_folders && $mbx_tree->mailboxname_full == $sent_folder) {
1210 $mbx_tree->mailboxname_sub = _("Sent");
1211 } elseif ($translate_special_folders && $mbx_tree->mailboxname_full == $trash_folder) {
1212 $mbx_tree->mailboxname_sub = _("Trash");
1213 } else {
1214 $mbx_tree->mailboxname_sub = imap_utf7_decode_local($mbx_tree->mailboxname_sub);
1215 }
9e0f10a8 1216
3d548be7 1217 if ($mbx_tree->mbxs) {
1218 $iCnt = count($mbx_tree->mbxs);
1219 for ($i=0;$i<$iCnt;++$i) {
9e0f10a8 1220 sqimap_utf7_decode_mbx_tree($mbx_tree->mbxs[$i]);
3d548be7 1221 }
1222 }
483f9ef9 1223}
1224
3131bc8d 1225/**
1226 * @param object $mbx_tree
1227 * @param array $aMbxs
1228 * @since 1.5.0
1229 */
483f9ef9 1230function sqimap_tree_to_ref_array(&$mbx_tree,&$aMbxs) {
5c300c60 1231 if ($mbx_tree)
483f9ef9 1232 $aMbxs[] =& $mbx_tree;
1233 if ($mbx_tree->mbxs) {
1234 $iCnt = count($mbx_tree->mbxs);
1235 for ($i=0;$i<$iCnt;++$i) {
5c300c60 1236 sqimap_tree_to_ref_array($mbx_tree->mbxs[$i],$aMbxs);
483f9ef9 1237 }
1238 }
4669e892 1239}
483f9ef9 1240
3131bc8d 1241/**
1242 * @param stream $imap_stream imap connection resource
1243 * @param object $mbx_tree
1244 * @since since 1.5.0
1245 */
483f9ef9 1246function sqimap_get_status_mbx_tree($imap_stream,&$mbx_tree) {
1247 global $unseen_notify, $unseen_type, $trash_folder,$move_to_trash;
8d8da447 1248 $aMbxs = $aQuery = array();
483f9ef9 1249 sqimap_tree_to_ref_array($mbx_tree,$aMbxs);
1250 // remove the root node
1251 array_shift($aMbxs);
1252
1253 if($unseen_notify == 3) {
1254 $cnt = count($aMbxs);
1255 for($i=0;$i<$cnt;++$i) {
5c300c60 1256 $oMbx =& $aMbxs[$i];
1257 if (!$oMbx->is_noselect) {
483f9ef9 1258 $mbx = $oMbx->mailboxname_full;
5c300c60 1259 if ($unseen_type == 2 ||
1260 ($move_to_trash && $oMbx->mailboxname_full == $trash_folder)) {
48879ef0 1261 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (MESSAGES UNSEEN RECENT)';
5c300c60 1262 } else {
48879ef0 1263 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (UNSEEN RECENT)';
5c300c60 1264 }
483f9ef9 1265 sqimap_prepare_pipelined_query($query,$tag,$aQuery,false);
5c300c60 1266 } else {
48879ef0 1267 $oMbx->unseen = $oMbx->total = $oMbx->recent = false;
5c300c60 1268 $tag = false;
1269 }
1270 $oMbx->tag = $tag;
1271 $aMbxs[$i] =& $oMbx;
483f9ef9 1272 }
1273 // execute all the queries at once
1274 $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
1275 $cnt = count($aMbxs);
1276 for($i=0;$i<$cnt;++$i) {
5c300c60 1277 $oMbx =& $aMbxs[$i];
1278 $tag = $oMbx->tag;
1279 if ($tag && $aServerResponse[$tag] == 'OK') {
1280 $sResponse = implode('', $aResponse[$tag]);
483f9ef9 1281 if (preg_match('/UNSEEN\s+([0-9]+)/i', $sResponse, $regs)) {
1282 $oMbx->unseen = $regs[1];
1283 }
1284 if (preg_match('/MESSAGES\s+([0-9]+)/i', $sResponse, $regs)) {
1285 $oMbx->total = $regs[1];
5c300c60 1286 }
48879ef0 1287 if (preg_match('/RECENT\s+([0-9]+)/i', $sResponse, $regs)) {
1288 $oMbx->recent = $regs[1];
1289 }
1290
5c300c60 1291 }
1292 unset($oMbx->tag);
1293 }
483f9ef9 1294 } else if ($unseen_notify == 2) { // INBOX only
1295 $cnt = count($aMbxs);
1296 for($i=0;$i<$cnt;++$i) {
5c300c60 1297 $oMbx =& $aMbxs[$i];
1298 if (strtoupper($oMbx->mailboxname_full) == 'INBOX' ||
1299 ($move_to_trash && $oMbx->mailboxname_full == $trash_folder)) {
4669e892 1300 if ($unseen_type == 2 ||
5c300c60 1301 ($oMbx->mailboxname_full == $trash_folder && $move_to_trash)) {
1302 $aStatus = sqimap_status_messages($imap_stream,$oMbx->mailboxname_full);
1303 $oMbx->unseen = $aStatus['UNSEEN'];
1304 $oMbx->total = $aStatus['MESSAGES'];
48879ef0 1305 $oMbx->recent = $aStatus['RECENT'];
5c300c60 1306 } else {
1307 $oMbx->unseen = sqimap_unseen_messages($imap_stream,$oMbx->mailboxname_full);
1308 }
1309 $aMbxs[$i] =& $oMbx;
1310 if (!$move_to_trash && $trash_folder) {
1311 break;
1312 } else {
1313 // trash comes after INBOX
1314 if ($oMbx->mailboxname_full == $trash_folder) {
1315 break;
1316 }
1317 }
1318 }
1319 }
4669e892 1320 }
48879ef0 1321
1322 $cnt = count($aMbxs);
1323 for($i=0;$i<$cnt;++$i) {
1324 $oMbx =& $aMbxs[$i];
1325 unset($hook_status);
1326 if (!empty($oMbx->unseen)) { $hook_status['UNSEEN']=$oMbx->unseen; }
1327 if (!empty($oMbx->total)) { $hook_status['MESSAGES']=$oMbx->total; }
1328 if (!empty($oMbx->recent)) { $hook_status['RECENT']=$oMbx->recent; }
1329 if (!empty($hook_status))
1330 {
1331 $hook_status['MAILBOX']=$oMbx->mailboxname_full;
1332 $hook_status['CALLER']='sqimap_get_status_mbx_tree'; // helps w/ debugging
1333 do_hook_function('folder_status',$hook_status);
1334 }
1335 }
4669e892 1336}
587ec647 1337
367fb0ca 1338/**
1339 * Checks if folder is noselect (can't store messages)
1340 *
1341 * Function does not check if folder subscribed.
1342 * @param stream $oImapStream imap connection resource
1343 * @param string $sImapFolder imap folder name
1344 * @param object $oBoxes mailboxes class object.
1345 * @return boolean true, when folder has noselect flag. false in any other case.
1346 * @since 1.5.1
1347 */
1348function sqimap_mailbox_is_noselect($oImapStream,$sImapFolder,&$oBoxes) {
1349 // build mailbox object if it is not available
1350 if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
1351 foreach($oBoxes as $box) {
1352 if ($box['unformatted']==$sImapFolder) {
1353 return (bool) check_is_noselect($box['raw']);
1354 }
1355 }
1356 return false;
1357}
1358
1359/**
1360 * Checks if folder is noinferiors (can't store other folders)
1361 *
1362 * Function does not check if folder subscribed.
1363 * @param stream $oImapStream imap connection resource
1364 * @param string $sImapFolder imap folder name
1365 * @param object $oBoxes mailboxes class object.
1366 * @return boolean true, when folder has noinferiors flag. false in any other case.
1367 * @since 1.5.1
1368 */
1369function sqimap_mailbox_is_noinferiors($oImapStream,$sImapFolder,&$oBoxes) {
1370 // build mailbox object if it is not available
1371 if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
1372 foreach($oBoxes as $box) {
1373 if ($box['unformatted']==$sImapFolder) {
1374 return (bool) check_is_noinferiors($box['raw']);
1375 }
1376 }
1377 return false;
1378}