Cleanup and abstraction of how default template set is retrieved
[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 }
3824e89a 367
92ffe525 368 // cleanup $mailbox in order to prevent IMAP injection attacks
369 $mailbox = str_replace(array("\r","\n"), array("",""),$mailbox);
3824e89a 370
371 /**
372 * Default UW IMAP server configuration allows to access other files
373 * on server. $imap_server_type is not checked because interface can
374 * be used with 'other' or any other server type setting. $mailbox
375 * variable can be modified in any script that uses variable from GET
376 * or POST. This code blocks all standard SquirrelMail IMAP API requests
377 * that use mailbox with full path (/etc/passwd) or with ../ characters
378 * in path (../../etc/passwd)
379 */
380 if (strstr($mailbox, '../') || substr($mailbox, 0, 1) == '/') {
381 global $oTemplate;
382 error_box(sprintf(_("Invalid mailbox name: %s"),htmlspecialchars($mailbox)));
383 sqimap_logout($imap_stream);
384 $oTemplate->display('footer.tpl');
385 die();
386 }
387
568cb884 388 $read = sqimap_run_command($imap_stream, 'SELECT ' . sqimap_encode_mailbox_name($mailbox),
3411d4ec 389 true, $response, $message);
e4c6fe41 390 $result = array();
ff245fbd 391 for ($i = 0, $cnt = count($read); $i < $cnt; $i++) {
e4c6fe41 392 if (preg_match('/^\*\s+OK\s\[(\w+)\s(\w+)\]/',$read[$i], $regs)) {
ff245fbd 393 $result[strtoupper($regs[1])] = $regs[2];
394 } else if (preg_match('/^\*\s([0-9]+)\s(\w+)/',$read[$i], $regs)) {
395 $result[strtoupper($regs[2])] = $regs[1];
396 } else {
397 if (preg_match("/PERMANENTFLAGS(.*)/i",$read[$i], $regs)) {
398 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/","/\]/") ,'', $regs[1])) ;
4669e892 399 $result['PERMANENTFLAGS'] = explode(' ',strtolower($regs[1]));
ff245fbd 400 } else if (preg_match("/FLAGS(.*)/i",$read[$i], $regs)) {
401 $regs[1]=trim(preg_replace ( array ("/\(/","/\)/") ,'', $regs[1])) ;
4669e892 402 $result['FLAGS'] = explode(' ',strtolower($regs[1]));
ff245fbd 403 }
404 }
e4c6fe41 405 }
4669e892 406 if (!isset($result['PERMANENTFLAGS'])) {
407 $result['PERMANENTFLAGS'] = $result['FLAGS'];
408 }
e4c6fe41 409 if (preg_match('/^\[(.+)\]/',$message, $regs)) {
4669e892 410 $result['RIGHTS']=strtoupper($regs[1]);
e4c6fe41 411 }
f69feefe 412
e4c6fe41 413 return $result;
43b698c7 414}
415
48af4b64 416/**
417 * Creates a folder.
d43853c7 418 *
419 * Mailbox is automatically subscribed.
f8a1ed5a 420 *
421 * Set $type to string that does not match 'noselect' (case insensitive),
422 * if you don't want to prepend delimiter to mailbox name. Please note
423 * that 'noinferiors' might be used someday as keyword for folders
d43853c7 424 * that store only messages.
425 * @param stream $imap_steam imap connection resource
426 * @param string $mailbox mailbox name
427 * @param string $type folder type.
428 * @since 1.0 or older
48af4b64 429 */
3411d4ec 430function sqimap_mailbox_create ($imap_stream, $mailbox, $type) {
43b698c7 431 global $delimiter;
432 if (strtolower($type) == 'noselect') {
5221db27 433 $create_mailbox = $mailbox . $delimiter;
434 } else {
435 $create_mailbox = $mailbox;
43b698c7 436 }
e429f014 437
48af4b64 438 $read_ary = sqimap_run_command($imap_stream, 'CREATE ' .
5221db27 439 sqimap_encode_mailbox_name($create_mailbox),
3411d4ec 440 true, $response, $message);
43b698c7 441 sqimap_subscribe ($imap_stream, $mailbox);
442}
443
48af4b64 444/**
445 * Subscribes to an existing folder.
d43853c7 446 * @param stream $imap_stream imap connection resource
447 * @param string $mailbox mailbox name
448 * @param boolean $debug (since 1.5.1)
449 * @since 1.0 or older
48af4b64 450 */
852abae7 451function sqimap_subscribe ($imap_stream, $mailbox,$debug=true) {
48af4b64 452 $read_ary = sqimap_run_command($imap_stream, 'SUBSCRIBE ' .
453 sqimap_encode_mailbox_name($mailbox),
852abae7 454 $debug, $response, $message);
43b698c7 455}
456
48af4b64 457/**
458 * Unsubscribes from an existing folder
d43853c7 459 * @param stream $imap_stream imap connection resource
460 * @param string $mailbox mailbox name
461 * @since 1.0 or older
48af4b64 462 */
3411d4ec 463function sqimap_unsubscribe ($imap_stream, $mailbox) {
48af4b64 464 $read_ary = sqimap_run_command($imap_stream, 'UNSUBSCRIBE ' .
465 sqimap_encode_mailbox_name($mailbox),
e2e8b92b 466 false, $response, $message);
43b698c7 467}
468
48af4b64 469/**
470 * Deletes the given folder
3131bc8d 471 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
472 * @param stream $imap_stream imap connection resource
473 * @param string $mailbox mailbox name
474 * @since 1.0 or older
48af4b64 475 */
3411d4ec 476function sqimap_mailbox_delete ($imap_stream, $mailbox) {
78cc4b12 477 global $data_dir, $username;
e2e8b92b 478 sqimap_unsubscribe ($imap_stream, $mailbox);
c957afd1 479
480 if (sqimap_mailbox_exists($imap_stream, $mailbox)) {
481
482 $read_ary = sqimap_run_command($imap_stream, 'DELETE ' .
483 sqimap_encode_mailbox_name($mailbox),
484 true, $response, $message);
485 if ($response !== 'OK') {
486 // subscribe again
487 sqimap_subscribe ($imap_stream, $mailbox);
488 } else {
489 do_hook_function('rename_or_delete_folder', $args = array($mailbox, 'delete', ''));
490 removePref($data_dir, $username, "thread_$mailbox");
491 removePref($data_dir, $username, "collapse_folder_$mailbox");
492 }
e2e8b92b 493 }
43b698c7 494}
495
48af4b64 496/**
497 * Determines if the user is subscribed to the folder or not
3131bc8d 498 * @param stream $imap_stream imap connection resource
499 * @param string $mailbox mailbox name
500 * @return boolean
501 * @since 1.2.0
48af4b64 502 */
1da22cda 503function sqimap_mailbox_is_subscribed($imap_stream, $folder) {
1da22cda 504 $boxesall = sqimap_mailbox_list ($imap_stream);
505 foreach ($boxesall as $ref) {
43b698c7 506 if ($ref['unformatted'] == $folder) {
3411d4ec 507 return true;
43b698c7 508 }
509 }
510 return false;
511}
512
48af4b64 513/**
514 * Renames a mailbox.
3131bc8d 515 * Since 1.2.6 and 1.3.0 contains rename_or_delete_folder hook
516 * @param stream $imap_stream imap connection resource
517 * @param string $old_name mailbox name
518 * @param string $new_name new mailbox name
519 * @since 1.2.3
48af4b64 520 */
1c52ba77 521function sqimap_mailbox_rename( $imap_stream, $old_name, $new_name ) {
3411d4ec 522 if ( $old_name != $new_name ) {
78cc4b12 523 global $delimiter, $imap_server_type, $data_dir, $username;
1c52ba77 524 if ( substr( $old_name, -1 ) == $delimiter ) {
525 $old_name = substr( $old_name, 0, strlen( $old_name ) - 1 );
526 $new_name = substr( $new_name, 0, strlen( $new_name ) - 1 );
527 $postfix = $delimiter;
1c52ba77 528 } else {
529 $postfix = '';
1c52ba77 530 }
68f2ce7a 531
5659ad2e 532 $boxesall = sqimap_mailbox_list_all($imap_stream);
48af4b64 533 $cmd = 'RENAME ' . sqimap_encode_mailbox_name($old_name) .
91e0dccc 534 ' ' . sqimap_encode_mailbox_name($new_name);
3411d4ec 535 $data = sqimap_run_command($imap_stream, $cmd, true, $response, $message);
1c52ba77 536 sqimap_unsubscribe($imap_stream, $old_name.$postfix);
5659ad2e 537 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$old_name.$postfix);
538 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
68f2ce7a 539 removePref($data_dir, $username, 'thread_'.$old_name.$postfix);
5659ad2e 540 removePref($data_dir, $username, 'collapse_folder_'.$old_name.$postfix);
1c52ba77 541 sqimap_subscribe($imap_stream, $new_name.$postfix);
5659ad2e 542 setPref($data_dir, $username, 'thread_'.$new_name.$postfix, $oldpref_thread);
543 setPref($data_dir, $username, 'collapse_folder_'.$new_name.$postfix, $oldpref_collapse);
e429f014 544 do_hook_function('rename_or_delete_folder',$args = array($old_name, 'rename', $new_name));
648713af 545 $l = strlen( $old_name ) + 1;
546 $p = 'unformatted';
68f2ce7a 547
ff245fbd 548 foreach ($boxesall as $box) {
549 if (substr($box[$p], 0, $l) == $old_name . $delimiter) {
648713af 550 $new_sub = $new_name . $delimiter . substr($box[$p], $l);
5659ad2e 551 /* With Cyrus IMAPd >= 2.0 rename is recursive, so don't check for errors here */
648713af 552 if ($imap_server_type == 'cyrus') {
68f2ce7a 553 $cmd = 'RENAME "' . $box[$p] . '" "' . $new_sub . '"';
5659ad2e 554 $data = sqimap_run_command($imap_stream, $cmd, false,
648713af 555 $response, $message);
1c52ba77 556 }
5659ad2e 557 $was_subscribed = sqimap_mailbox_is_subscribed($imap_stream, $box[$p]);
558 if ( $was_subscribed ) {
559 sqimap_unsubscribe($imap_stream, $box[$p]);
560 }
561 $oldpref_thread = getPref($data_dir, $username, 'thread_'.$box[$p]);
562 $oldpref_collapse = getPref($data_dir, $username, 'collapse_folder_'.$box[$p]);
68f2ce7a 563 removePref($data_dir, $username, 'thread_'.$box[$p]);
5659ad2e 564 removePref($data_dir, $username, 'collapse_folder_'.$box[$p]);
565 if ( $was_subscribed ) {
566 sqimap_subscribe($imap_stream, $new_sub);
567 }
568 setPref($data_dir, $username, 'thread_'.$new_sub, $oldpref_thread);
569 setPref($data_dir, $username, 'collapse_folder_'.$new_sub, $oldpref_collapse);
68f2ce7a 570 do_hook_function('rename_or_delete_folder',
3411d4ec 571 $args = array($box[$p], 'rename', $new_sub));
1c52ba77 572 }
573 }
1c52ba77 574 }
1c52ba77 575}
43b698c7 576
48af4b64 577/**
86c2763d 578 * Formats a mailbox into parts for the $boxesall array
3411d4ec 579 *
86c2763d 580 * The parts are:
3131bc8d 581 * <ul>
582 * <li>raw - Raw LIST/LSUB response from the IMAP server
583 * <li>formatted - nicely formatted folder name
584 * <li>unformatted - unformatted, but with delimiter at end removed
585 * <li>unformatted-dm - folder name as it appears in raw response
586 * <li>unformatted-disp - unformatted without $folder_prefix
587 * <li>id - TODO: document me
588 * <li>flags - TODO: document me
589 * </ul>
590 * Before 1.2.0 used third argument for delimiter.
a462b928 591 *
592 * Before 1.5.1 used second argument for lsub line. Argument was removed in order to use
92ffe525 593 * find_mailbox_name() on the raw input. Since 1.5.1 includes RFC3501 names in flags
a462b928 594 * array (for example, "\NoSelect" in addition to "noselect")
595 * @param array $line
3131bc8d 596 * @return array
597 * @since 1.0 or older
598 * @todo document id and flags keys in boxes array and function arguments.
3411d4ec 599 */
a462b928 600function sqimap_mailbox_parse ($line) {
43b698c7 601 global $folder_prefix, $delimiter;
3411d4ec 602
43b698c7 603 /* Process each folder line */
cef054e4 604 for ($g = 0, $cnt = count($line); $g < $cnt; ++$g) {
43b698c7 605 /* Store the raw IMAP reply */
606 if (isset($line[$g])) {
e429f014 607 $boxesall[$g]['raw'] = $line[$g];
ff245fbd 608 } else {
e429f014 609 $boxesall[$g]['raw'] = '';
43b698c7 610 }
3411d4ec 611
43b698c7 612 /* Count number of delimiters ($delimiter) in folder name */
a462b928 613 $mailbox = find_mailbox_name($line[$g]);
ff245fbd 614 $dm_count = substr_count($mailbox, $delimiter);
43b698c7 615 if (substr($mailbox, -1) == $delimiter) {
3411d4ec 616 /* If name ends in delimiter, decrement count by one */
617 $dm_count--;
43b698c7 618 }
3411d4ec 619
620 /* Format folder name, but only if it's a INBOX.* or has a parent. */
1da22cda 621 $boxesallbyname[$mailbox] = $g;
43b698c7 622 $parentfolder = readMailboxParent($mailbox, $delimiter);
623 if ( (strtolower(substr($mailbox, 0, 5)) == "inbox") ||
624 (substr($mailbox, 0, strlen($folder_prefix)) == $folder_prefix) ||
ff245fbd 625 (isset($boxesallbyname[$parentfolder]) &&
626 (strlen($parentfolder) > 0) ) ) {
627 $indent = $dm_count - (substr_count($folder_prefix, $delimiter));
43b698c7 628 if ($indent > 0) {
ff245fbd 629 $boxesall[$g]['formatted'] = str_repeat('&nbsp;&nbsp;', $indent);
630 } else {
1da22cda 631 $boxesall[$g]['formatted'] = '';
43b698c7 632 }
447b2166 633 $boxesall[$g]['formatted'] .= imap_utf7_decode_local(readShortMailboxName($mailbox, $delimiter));
ff245fbd 634 } else {
447b2166 635 $boxesall[$g]['formatted'] = imap_utf7_decode_local($mailbox);
43b698c7 636 }
90de1755 637
1da22cda 638 $boxesall[$g]['unformatted-dm'] = $mailbox;
43b698c7 639 if (substr($mailbox, -1) == $delimiter) {
8e9e8afa 640 $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
43b698c7 641 }
1da22cda 642 $boxesall[$g]['unformatted'] = $mailbox;
43b698c7 643 if (substr($mailbox,0,strlen($folder_prefix))==$folder_prefix) {
631b9da3 644 $mailbox = substr($mailbox, strlen($folder_prefix));
43b698c7 645 }
1da22cda 646 $boxesall[$g]['unformatted-disp'] = $mailbox;
647 $boxesall[$g]['id'] = $g;
90de1755 648
1da22cda 649 $boxesall[$g]['flags'] = array();
43b698c7 650 if (isset($line[$g])) {
36dfb0c9 651 ereg("\(([^)]*)\)",$line[$g],$regs);
a462b928 652 /**
653 * Since 1.5.1 flags are stored with RFC3501 naming
654 * and also the old way for backwards compatibility
655 * so for example "\NoSelect" and "noselect"
656 */
657 $flags = trim($regs[1]);
43b698c7 658 if ($flags) {
a462b928 659 $flagsarr = explode(' ',$flags);
660 $flagsarrnew=$flagsarr;
661 // add old type
662 foreach ($flagsarr as $flag) {
663 $flagsarrnew[]=strtolower(str_replace('\\', '',$flag));
664 }
665 $boxesall[$g]['flags']=$flagsarrnew;
43b698c7 666 }
667 }
668 }
1da22cda 669 return $boxesall;
43b698c7 670}
671
48af4b64 672/**
f5b3b0fc 673 * Returns an array of mailboxes available. Separated from sqimap_mailbox_option_list()
674 * below for template development.
675 *
676 * @author Steve Brown
677 * @since 1.5.2
be2d5495 678 */
f5b3b0fc 679function sqimap_mailbox_option_array($imap_stream, $folder_skip = 0, $boxes = 0,
59a8e3e8 680 $flag = 'noselect', $use_long_format = false ) {
dbd9ce25 681 global $username, $data_dir, $translate_special_folders, $sent_folder,
682 $trash_folder, $draft_folder;
683
684 $delimiter = sqimap_get_delimiter($imap_stream);
685
be2d5495 686 $mbox_options = '';
45f836eb 687 if ( $use_long_format ) {
688 $shorten_box_names = 0;
689 } else {
690 $shorten_box_names = getPref($data_dir, $username, 'mailbox_select_style', SMPREF_OFF);
691 }
ff245fbd 692
693 if ($boxes == 0) {
be2d5495 694 $boxes = sqimap_mailbox_list($imap_stream);
ff245fbd 695 }
59a8e3e8 696
f5b3b0fc 697 $a = array();
be2d5495 698 foreach ($boxes as $boxes_part) {
4df5d823 699 if ($flag == NULL || (is_array($boxes_part['flags'])
700 && !in_array($flag, $boxes_part['flags']))) {
be2d5495 701 $box = $boxes_part['unformatted'];
be2d5495 702
d0928dd5 703 if ($folder_skip != 0 && in_array($box, $folder_skip) ) {
be2d5495 704 continue;
705 }
4669e892 706 $lowerbox = strtolower($box);
5c300c60 707 // mailboxes are casesensitive => inbox.sent != inbox.Sent
708 // nevermind, to many dependencies this should be fixed!
4669e892 709
d0928dd5 710 if (strtolower($box) == 'inbox') { // inbox is special and not casesensitive
be2d5495 711 $box2 = _("INBOX");
4669e892 712 } else {
5c300c60 713 switch ($shorten_box_names)
714 {
715 case 2: /* delimited, style = 2 */
dbd9ce25 716 if ($translate_special_folders && $boxes_part['unformatted-dm']==$sent_folder) {
717 /*
718 * calculate pad level from number of delimiters. do it inside if control in order
719 * to reduce number of calculations. Other folders don't need it.
720 */
721 $pad = str_pad('',7 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'.&nbsp;');
722 // i18n: Name of Sent folder
723 $box2 = $pad . _("Sent");
724 } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$trash_folder) {
725 $pad = str_pad('',7 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'.&nbsp;');
726 // i18n: Name of Trash folder
727 $box2 = $pad . _("Trash");
728 } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$draft_folder) {
729 $pad = str_pad('',7 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'.&nbsp;');
730 // i18n: Name of Drafts folder
731 $box2 = $pad . _("Drafts");
732 } else {
733 $box2 = str_replace('&amp;nbsp;&amp;nbsp;', '.&nbsp;', htmlspecialchars($boxes_part['formatted']));
734 }
5c300c60 735 break;
d0928dd5 736 case 1: /* indent, style = 1 */
dbd9ce25 737 if ($translate_special_folders && $boxes_part['unformatted-dm']==$sent_folder) {
738 $pad = str_pad('',12 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'&nbsp;&nbsp;');
739 $box2 = $pad . _("Sent");
740 } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$trash_folder) {
741 $pad = str_pad('',12 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'&nbsp;&nbsp;');
742 $box2 = $pad . _("Trash");
743 } elseif ($translate_special_folders && $boxes_part['unformatted-dm']==$draft_folder) {
744 $pad = str_pad('',12 * (count(explode($delimiter,$boxes_part['unformatted-dm']))-1),'&nbsp;&nbsp;');
745 $box2 = $pad . _("Drafts");
746 } else {
747 $box2 = str_replace('&amp;nbsp;&amp;nbsp;', '&nbsp;&nbsp;', htmlspecialchars($boxes_part['formatted']));
748 }
5c300c60 749 break;
d0928dd5 750 default: /* default, long names, style = 0 */
6c4f0fa1 751 $box2 = str_replace(' ', '&nbsp;', htmlspecialchars(imap_utf7_decode_local($boxes_part['unformatted-disp'])));
5c300c60 752 break;
753 }
be2d5495 754 }
f5b3b0fc 755
756 $a[htmlspecialchars($box)] = $box2;
757 }
758 }
759
760 return $a;
761}
762
763/**
764 * Returns list of options (to be echoed into select statement
765 * based on available mailboxes and separators
766 * Caller should surround options with <select ...> </select> and
767 * any formatting.
768 * @param stream $imap_stream imap connection resource to query for mailboxes
769 * @param array $show_selected array containing list of mailboxes to pre-select (0 if none)
770 * @param array $folder_skip array of folders to keep out of option list (compared in lower)
771 * @param $boxes list of already fetched boxes (for places like folder panel, where
772 * you know these options will be shown 3 times in a row.. (most often unset).
773 * @param string $flag (since 1.4.1) flag to check for in mailbox flags, used to filter out mailboxes.
774 * 'noselect' by default to remove unselectable mailboxes.
775 * 'noinferiors' used to filter out folders that can not contain subfolders.
776 * NULL to avoid flag check entirely.
777 * NOTE: noselect and noiferiors are used internally. The IMAP representation is
778 * \NoSelect and \NoInferiors
779 * @param boolean $use_long_format (since 1.4.1) override folder display preference and always show full folder name.
780 * @return string html formated mailbox selection options
781 * @since 1.3.2
782 */
783function sqimap_mailbox_option_list($imap_stream, $show_selected = 0, $folder_skip = 0, $boxes = 0,
784 $flag = 'noselect', $use_long_format = false ) {
785 global $username, $data_dir, $translate_special_folders, $sent_folder,
786 $trash_folder, $draft_folder;
787
788 $boxes = sqimap_mailbox_option_array($imap_stream, $folder_skip, $boxes, $flag, $use_long_format);
789
790 $str = '';
791 foreach ($boxes as $value=>$option) {
792 $lowerbox = strtolower(htmlspecialchars($value));
793 $sel = false;
794 if ($show_selected != 0) {
795 reset($show_selected);
796 while (!$sel && (list($x, $val) = each($show_selected))) {
797 if (strtolower($value) == strtolower(htmlspecialchars($val))) {
798 $sel = true;
799 }
be2d5495 800 }
801 }
f5b3b0fc 802
803 $str .= '<option value="'. $value .'"'. ($sel ? ' selected="selected"' : '').'>'. $option ."</option>\n";
be2d5495 804 }
f5b3b0fc 805
806 return $str;
be2d5495 807}
43b698c7 808
48af4b64 809/**
4669e892 810 * Returns sorted mailbox lists in several different ways.
a462b928 811 *
812 * Since 1.5.1 most of the functionality has been moved to new function sqimap_get_mailboxes
813 *
3411d4ec 814 * See comment on sqimap_mailbox_parse() for info about the returned array.
3e9441a2 815 * @param resource $imap_stream imap connection resource
816 * @param boolean $force force update of mailbox listing. available since 1.4.2 and 1.5.0
817 * @return array list of mailboxes
3131bc8d 818 * @since 1.0 or older
3411d4ec 819 */
fe6efa94 820function sqimap_mailbox_list($imap_stream, $force=false) {
a462b928 821 global $boxesnew,$show_only_subscribed_folders;
fe6efa94 822 if (!sqgetGlobalVar('boxesnew',$boxesnew,SQ_SESSION) || $force) {
a462b928 823 $boxesnew=sqimap_get_mailboxes($imap_stream,$force,$show_only_subscribed_folders);
824 }
825 return $boxesnew;
826}
4669e892 827
a462b928 828/**
829 * Returns a list of all folders, subscribed or not
830 *
831 * Since 1.5.1 code moved to sqimap_get_mailboxes()
832 *
833 * @param stream $imap_stream imap connection resource
834 * @return array see sqimap_mailbox_parse()
835 * @since 1.0 or older
836 */
837function sqimap_mailbox_list_all($imap_stream) {
838 global $show_only_subscribed_folders;
839 // fourth argument prevents registration of retrieved list of mailboxes in session
840 $boxes=sqimap_get_mailboxes($imap_stream,true,false,false);
841 return $boxes;
842}
7e235a1a 843
159d2af7 844
a462b928 845/**
846 * Gets the list of mailboxes for sqimap_maolbox_tree and sqimap_mailbox_list
847 *
848 * This is because both of those functions had duplicated logic, but with slightly different
849 * implementations. This will make both use the same implementation, which should make it
850 * easier to maintain and easier to modify in the future
851 * @param stream $imap_stream imap connection resource
852 * @param bool $force force a reload and ignore cache
853 * @param bool $show_only_subscribed controls listing of visible or all folders
854 * @param bool $session_register controls registration of retrieved data in session.
855 * @return object boxesnew - array of mailboxes and their attributes
856 * @since 1.5.1
857 */
858function sqimap_get_mailboxes($imap_stream,$force=false,$show_only_subscribed=true,$session_register=true) {
859 global $show_only_subscribed_folders,$noselect_fix_enable,$folder_prefix,
860 $list_special_folders_first,$imap_server_type;
861 $inbox_subscribed = false;
862 $listsubscribed = sqimap_capability($imap_stream,'LIST-SUBSCRIBED');
cef054e4 863
a462b928 864 if ($show_only_subscribed) { $show_only_subscribed=$show_only_subscribed_folders; }
fe6efa94 865
202bcbcc 866 //require_once(SM_PATH . 'include/load_prefs.php');
4669e892 867
a462b928 868 /**
869 * There are three main listing commands we can use in IMAP:
870 * LSUB shows just the list of subscribed folders
871 * may include flags, but these are not necessarily accurate or authoratative
92ffe525 872 * \NoSelect has special meaning: the folder does not exist -OR- it means this
a462b928 873 * folder is not subscribed but children may be
874 * [RFC-2060]
875 * LIST this shows every mailbox on the system
876 * flags are always included and are accurate and authoratative
877 * \NoSelect means folder should not be selected
878 * [RFC-2060]
879 * LIST (SUBSCRIBED) implemented with LIST-SUBSCRIBED extension
880 * this is like list but returns only subscribed folders
881 * flag meanings are like LIST, not LSUB
882 * \NonExistent means mailbox doesn't exist
883 * \PlaceHolder means parent is not valid (selectable), but one or more children are
884 * \NoSelect indeed means that the folder should not be selected
885 * IMAPEXT-LIST-EXTENSIONS-04 August 2003 B. Leiba
886 */
887 if (!$show_only_subscribed) {
888 $lsub = 'LIST';
889 $sub_cache_name='list_cache';
890 } elseif ($listsubscribed) {
891 $lsub = 'LIST (SUBSCRIBED)';
892 $sub_cache_name='listsub_cache';
893 } else {
894 $lsub = 'LSUB';
895 $sub_cache_name='lsub_cache';
896 }
4669e892 897
a462b928 898 // Some IMAP servers allow subfolders to exist even if the parent folders do not
899 // This fixes some problems with the folder list when this is the case, causing the
900 // NoSelect folders to be displayed
901 if ($noselect_fix_enable) {
902 $lsub_args = "$lsub \"$folder_prefix\" \"*%\"";
903 $list_args = "LIST \"$folder_prefix\" \"*%\"";
904 } else {
905 $lsub_args = "$lsub \"$folder_prefix\" \"*\"";
906 $list_args = "LIST \"$folder_prefix\" \"*\"";
907 }
7e235a1a 908
a462b928 909 // get subscribed mailbox list from cache (session)
910 // if not there, then get it from the imap server and store in cache
7e235a1a 911
a462b928 912 if (!$force) {
913 sqgetGlobalVar($sub_cache_name,$lsub_cache,SQ_SESSION);
914 }
7e235a1a 915
76682066 916 $lsub_assoc_ary=array();
a462b928 917 if (!empty($lsub_cache)) {
918 $lsub_assoc_ary=$lsub_cache;
919 } else {
920 $lsub_ary = sqimap_run_command ($imap_stream, $lsub_args, true, $response, $message);
921 $lsub_ary = compact_mailboxes_response($lsub_ary);
922 if (!empty($lsub_ary)) {
923 foreach ($lsub_ary as $rawline) {
924 $temp_mailbox_name=find_mailbox_name($rawline);
925 $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
7e235a1a 926 }
a462b928 927 unset($lsub_ary);
928 sqsession_register($lsub_assoc_ary,$sub_cache_name);
929 }
930 }
931
932 // Now to get the mailbox flags
933 // The LSUB response may return \NoSelect flags, etc. but it is optional
934 // according to RFC3501, and even when returned it may not be accurate
935 // or authoratative. LIST will always return accurate results.
936 if (($lsub == 'LIST') || ($lsub == 'LIST (SUBSCRIBED)')) {
937 // we've already done a LIST or LIST (SUBSCRIBED)
938 // and NOT a LSUB, so no need to do it again
939 $list_assoc_ary = $lsub_assoc_ary;
940 } else {
92ffe525 941 // we did a LSUB so now we need to do a LIST
a462b928 942 // first see if it is in cache
943 $list_cache_name='list_cache';
944 if (!$force) {
945 sqgetGlobalVar($list_cache_name,$list_cache,SQ_SESSION);
7e235a1a 946 }
a462b928 947
948 if (!empty($list_cache)) {
949 $list_assoc_ary=$list_cache;
950 // we could store this in list_cache_name but not necessary
951 } else {
952 // not in cache so we need to go get it from the imap server
953 $list_assoc_ary = array();
954 $list_ary = sqimap_run_command($imap_stream, $list_args,
955 true, $response, $message);
956 $list_ary = compact_mailboxes_response($list_ary);
957 if (!empty($list_ary)) {
958 foreach ($list_ary as $rawline) {
959 $temp_mailbox_name=find_mailbox_name($rawline);
960 $list_assoc_ary[$temp_mailbox_name]=$rawline;
7e235a1a 961 }
a462b928 962 unset($list_ary);
963 sqsession_register($list_assoc_ary,$list_cache_name);
5c300c60 964 }
965 }
a462b928 966 }
c3ce607e 967
a462b928 968 // If they aren't subscribed to the inbox, then add it anyway (if its in LIST)
969 $inbox_subscribed=false;
970 if (!empty($lsub_assoc_ary)) {
971 foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
972 if (strtoupper($temp_mailbox_name) == 'INBOX') {
973 $inbox_subscribed=true;
f8a1ed5a 974 }
c3ce607e 975 }
a462b928 976 }
977 if (!$inbox_subscribed) {
978 if (!empty($list_assoc_ary)) {
979 foreach ($list_assoc_ary as $temp_mailbox_name=>$rawline) {
980 if (strtoupper($temp_mailbox_name) == 'INBOX') {
981 $lsub_assoc_ary[$temp_mailbox_name]=$rawline;
982 }
983 }
984 }
985 }
f8a1ed5a 986
a462b928 987 // Now we have the raw output, we need to create an array of mailbox names we will return
988 if (!$show_only_subscribed) {
989 $final_folders_assoc_ary=$list_assoc_ary;
990 } else {
991 /**
992 * only show subscribed folders
993 * we need to merge the folders here... we can't trust the flags, etc. from the lsub_assoc_array
994 * so we use the lsub_assoc_array as the list of folders and the values come from list_assoc_array
995 */
996 if (!empty($lsub_assoc_ary)) {
997 foreach ($lsub_assoc_ary as $temp_mailbox_name=>$rawline) {
998 if (!empty($list_assoc_ary[$temp_mailbox_name])) {
999 $final_folders_assoc_ary[$temp_mailbox_name]=$list_assoc_ary[$temp_mailbox_name];
1000 }
7e235a1a 1001 }
1002 }
43b698c7 1003 }
43b698c7 1004
bac13dd7 1005
a462b928 1006 // Now produce a flat, sorted list
1007 if (!empty($final_folders_assoc_ary)) {
1008 uksort($final_folders_assoc_ary,'strnatcasecmp');
1009 foreach ($final_folders_assoc_ary as $temp_mailbox_name=>$rawline) {
1010 $final_folders_ary[]=$rawline;
1011 }
1012 }
bac13dd7 1013
a462b928 1014 // this will put it into an array we can use later
1015 // containing:
1016 // raw - Raw LIST/LSUB response from the IMAP server
1017 // formatted - formatted folder name
1018 // unformatted - unformatted, but with the delimiter at the end removed
1019 // unformated-dm - folder name as it appears in raw response
1020 // unformatted-disp - unformatted without $folder_prefix
1021 // id - the array element number (0, 1, 2, etc.)
1022 // flags - mailbox flags
1023 if (!empty($final_folders_ary)) {
1024 $boxesall = sqimap_mailbox_parse($final_folders_ary);
1025 } else {
1026 // they have no mailboxes
1027 $boxesall=array();
1028 }
90de1755 1029
a462b928 1030 /* Now, lets sort for special folders */
1031 $boxesnew = $used = array();
90de1755 1032
a462b928 1033 /* Find INBOX */
1034 $cnt = count($boxesall);
1035 $used = array_pad($used,$cnt,false);
1036 $has_inbox = false;
1037 for($k = 0; $k < $cnt; ++$k) {
1038 if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
1039 $boxesnew[] = $boxesall[$k];
1040 $used[$k] = true;
1041 $has_inbox = true;
1042 break;
1043 }
1044 }
92ffe525 1045
a462b928 1046 if ($has_inbox == false) {
1047 // do a list request for inbox because we should always show
1048 // inbox even if the user isn't subscribed to it.
1049 $inbox_ary = sqimap_run_command($imap_stream, 'LIST "" "INBOX"',
1050 true, $response, $message);
1051 $inbox_ary = compact_mailboxes_response($inbox_ary);
1052 if (count($inbox_ary)) {
1053 $inbox_entry = sqimap_mailbox_parse($inbox_ary);
1054 // add it on top of the list
1055 if (!empty($boxesnew)) {
1056 array_unshift($boxesnew,$inbox_entry[0]);
90de1755 1057 } else {
a462b928 1058 $boxesnew[]=$inbox_entry[0];
12d61439 1059 }
a462b928 1060 /* array_unshift($used,true); */
780dd344 1061 }
a462b928 1062 }
780dd344 1063
a462b928 1064 /* List special folders and their subfolders, if requested. */
1065 if ($list_special_folders_first) {
1066 for($k = 0; $k < $cnt; ++$k) {
1067 if (!$used[$k] && isSpecialMailbox($boxesall[$k]['unformatted'])) {
1068 $boxesnew[] = $boxesall[$k];
1069 $used[$k] = true;
1070 }
780dd344 1071 }
a462b928 1072 }
1073
1074 /* Find INBOX's children */
1075 for($k = 0; $k < $cnt; ++$k) {
1076 $isboxbelow=isBoxBelow(strtoupper($boxesall[$k]['unformatted']),'INBOX');
1077 if (strtoupper($boxesall[$k]['unformatted']) == 'INBOX') {
1078 $is_inbox=1;
780dd344 1079 } else {
a462b928 1080 $is_inbox=0;
1081 }
1082
1083 if (!$used[$k] && $isboxbelow && $is_inbox) {
1084 $boxesnew[] = $boxesall[$k];
1085 $used[$k] = true;
43b698c7 1086 }
43b698c7 1087 }
90de1755 1088
a462b928 1089 /* Rest of the folders */
1090 for($k = 0; $k < $cnt; $k++) {
1091 if (!$used[$k]) {
1092 $boxesnew[] = $boxesall[$k];
1093 }
1094 }
1095 /**
1096 * Don't register boxes in session, if $session_register is set to false
1097 * Prevents registration of sqimap_mailbox_list_all() results.
1098 */
1099 if ($session_register) sqsession_register($boxesnew,'boxesnew');
1100 return $boxesnew;
43b698c7 1101}
5bdd7223 1102
3131bc8d 1103/**
4b2720f5 1104 * Fills mailbox object
1105 *
a462b928 1106 * this is passed the mailbox array by left_main.php
1107 * who has previously obtained it from sqimap_get_mailboxes
1108 * that way, the raw mailbox list is available in left_main to other
1109 * things besides just sqimap_mailbox_tree
1110 * imap_stream is just used now to get status info
1111 *
1112 * most of the functionality is moved to sqimap_get_mailboxes
1113 * also takes care of TODO items:
1114 * caching mailbox tree
1115 * config setting for UW imap section (not needed now)
1116 *
4b2720f5 1117 * Some code fragments are present in 1.3.0 - 1.4.4.
3131bc8d 1118 * @param stream $imap_stream imap connection resource
a462b928 1119 * @param array $lsub_ary output array from sqimap_get_mailboxes (contains mailboxes and flags)
3131bc8d 1120 * @return object see mailboxes class.
4b2720f5 1121 * @since 1.5.0
3131bc8d 1122 */
a462b928 1123function sqimap_mailbox_tree($imap_stream,$lsub_ary) {
bac13dd7 1124
4b2720f5 1125 $sorted_lsub_ary = array();
1126 $cnt = count($lsub_ary);
1127 for ($i = 0; $i < $cnt; $i++) {
a462b928 1128 $mbx=$lsub_ary[$i]['unformatted'];
1129 $flags=$lsub_ary[$i]['flags'];
1130
1131 $noinferiors=0;
1132 if (in_array('\Noinferiors',$flags)) { $noinferiors=1; }
1133 if (in_array('\NoInferiors',$flags)) { $noinferiors=1; }
1134 if (in_array('\HasNoChildren',$flags)) { $noinferiors=1; }
1135
1136 $noselect=0;
92ffe525 1137 if (in_array('\NoSelect',$flags)) { $noselect=1; }
a462b928 1138 /**
1139 * LIST (SUBSCRIBED) has two new flags, \NonExistent which means the mailbox is subscribed to
1140 * but doesn't exist, and \PlaceHolder which is similar (but not the same) as \NoSelect
1141 * For right now, we'll treat these the same as \NoSelect and this behavior can be changed
1142 * later if needed
1143 */
92ffe525 1144 if (in_array('\NonExistent',$flags)) { $noselect=1; }
a462b928 1145 if (in_array('\PlaceHolder',$flags)) { $noselect=1; }
4b2720f5 1146 $sorted_lsub_ary[] = array ('mbx' => $mbx, 'noselect' => $noselect, 'noinferiors' => $noinferiors);
1147 }
a462b928 1148
4b2720f5 1149 $sorted_lsub_ary = array_values($sorted_lsub_ary);
1150 usort($sorted_lsub_ary, 'mbxSort');
1151 $boxestree = sqimap_fill_mailbox_tree($sorted_lsub_ary,false,$imap_stream);
1152 return $boxestree;
60b5724d 1153}
1154
3131bc8d 1155/**
1156 * Callback function used for sorting mailboxes in sqimap_mailbox_tree
1157 * @param string $a
1158 * @param string $b
1159 * @return integer see php strnatcasecmp()
1160 * @since 1.5.1
1161 */
9d8d1ebd 1162function mbxSort($a, $b) {
1163 return strnatcasecmp($a['mbx'], $b['mbx']);
1164}
1165
3131bc8d 1166/**
4b2720f5 1167 * Fills mailbox object
1168 *
1169 * Some code fragments are present in 1.3.0 - 1.4.4.
3131bc8d 1170 * @param array $mbx_ary
1171 * @param $mbxs
4b2720f5 1172 * @param stream $imap_stream imap connection resource
3131bc8d 1173 * @return object see mailboxes class
4b2720f5 1174 * @since 1.5.0
3131bc8d 1175 */
483f9ef9 1176function sqimap_fill_mailbox_tree($mbx_ary, $mbxs=false,$imap_stream) {
60b5724d 1177 global $data_dir, $username, $list_special_folders_first,
1178 $folder_prefix, $trash_folder, $sent_folder, $draft_folder,
1179 $move_to_trash, $move_to_sent, $save_as_draft,
43a31298 1180 $delimiter, $imap_server_type;
60b5724d 1181
8d8da447 1182 // $special_folders = array ('INBOX', $sent_folder, $draft_folder, $trash_folder);
ff245fbd 1183
60b5724d 1184 /* create virtual root node */
1185 $mailboxes= new mailboxes();
1186 $mailboxes->is_root = true;
ff245fbd 1187 $trail_del = false;
78bc908d 1188 $start = 0;
1189
43a31298 1190 if (isset($folder_prefix) && ($folder_prefix != '')) {
ff245fbd 1191 $start = substr_count($folder_prefix,$delimiter);
1192 if (strrpos($folder_prefix, $delimiter) == (strlen($folder_prefix)-1)) {
ff245fbd 1193 $mailboxes->mailboxname_full = substr($folder_prefix,0, (strlen($folder_prefix)-1));
1194 } else {
1195 $mailboxes->mailboxname_full = $folder_prefix;
1196 $start++;
1197 }
1198 $mailboxes->mailboxname_sub = $mailboxes->mailboxname_full;
1199 } else {
1200 $start = 0;
1201 }
78bc908d 1202
9d8d1ebd 1203 $cnt = count($mbx_ary);
e4c6fe41 1204 for ($i=0; $i < $cnt; $i++) {
ff245fbd 1205 if ($mbx_ary[$i]['mbx'] !='' ) {
1206 $mbx = new mailboxes();
1207 $mailbox = $mbx_ary[$i]['mbx'];
cc82c2b7 1208
4669e892 1209 /*
ae9e2adc 1210 * Set the is_special flag if it concerned a special mailbox.
1211 * Used for displaying the special folders on top in the mailbox
1212 * tree displaying code.
1213 */
8edc9f31 1214 $mbx->is_special |= ($mbx->is_inbox = (strtoupper($mailbox) == 'INBOX'));
1215 $mbx->is_special |= ($mbx->is_trash = isTrashMailbox($mailbox));
1216 $mbx->is_special |= ($mbx->is_sent = isSentMailbox($mailbox));
1217 $mbx->is_special |= ($mbx->is_draft = isDraftMailbox($mailbox));
ae9e2adc 1218
8edc9f31 1219 if (!$mbx->is_special)
fda01075 1220 $mbx->is_special = boolean_hook_function('special_mailbox', $mailbox, 1);
4669e892 1221
ff245fbd 1222 if (isset($mbx_ary[$i]['unseen'])) {
1223 $mbx->unseen = $mbx_ary[$i]['unseen'];
1224 }
1225 if (isset($mbx_ary[$i]['nummessages'])) {
1226 $mbx->total = $mbx_ary[$i]['nummessages'];
1227 }
1228
1229 $mbx->is_noselect = $mbx_ary[$i]['noselect'];
86c2763d 1230 $mbx->is_noinferiors = $mbx_ary[$i]['noinferiors'];
ff245fbd 1231
60b5724d 1232 $r_del_pos = strrpos($mbx_ary[$i]['mbx'], $delimiter);
ff245fbd 1233 if ($r_del_pos) {
587ec647 1234 $mbx->mailboxname_sub = substr($mbx_ary[$i]['mbx'],$r_del_pos+1);
ff245fbd 1235 } else { /* mailbox is root folder */
587ec647 1236 $mbx->mailboxname_sub = $mbx_ary[$i]['mbx'];
ff245fbd 1237 }
1238 $mbx->mailboxname_full = $mbx_ary[$i]['mbx'];
38068e69 1239
9871bdaa 1240 $mailboxes->addMbx($mbx, $delimiter, $start, $list_special_folders_first);
ff245fbd 1241 }
60b5724d 1242 }
587ec647 1243 sqimap_utf7_decode_mbx_tree($mailboxes);
483f9ef9 1244 sqimap_get_status_mbx_tree($imap_stream,$mailboxes);
60b5724d 1245 return $mailboxes;
1246}
259faa39 1247
3131bc8d 1248/**
1249 * @param object $mbx_tree
1250 * @since 1.5.0
1251 */
587ec647 1252function sqimap_utf7_decode_mbx_tree(&$mbx_tree) {
3d548be7 1253 global $draft_folder, $sent_folder, $trash_folder, $translate_special_folders;
1254
1255 /* decode folder name and set mailboxname_sub */
1256 if ($translate_special_folders && strtoupper($mbx_tree->mailboxname_full) == 'INBOX') {
1257 $mbx_tree->mailboxname_sub = _("INBOX");
1258 } elseif ($translate_special_folders && $mbx_tree->mailboxname_full == $draft_folder) {
1259 $mbx_tree->mailboxname_sub = _("Drafts");
1260 } elseif ($translate_special_folders && $mbx_tree->mailboxname_full == $sent_folder) {
1261 $mbx_tree->mailboxname_sub = _("Sent");
1262 } elseif ($translate_special_folders && $mbx_tree->mailboxname_full == $trash_folder) {
1263 $mbx_tree->mailboxname_sub = _("Trash");
1264 } else {
1265 $mbx_tree->mailboxname_sub = imap_utf7_decode_local($mbx_tree->mailboxname_sub);
1266 }
9e0f10a8 1267
3d548be7 1268 if ($mbx_tree->mbxs) {
1269 $iCnt = count($mbx_tree->mbxs);
1270 for ($i=0;$i<$iCnt;++$i) {
9e0f10a8 1271 sqimap_utf7_decode_mbx_tree($mbx_tree->mbxs[$i]);
3d548be7 1272 }
1273 }
483f9ef9 1274}
1275
3131bc8d 1276/**
1277 * @param object $mbx_tree
1278 * @param array $aMbxs
1279 * @since 1.5.0
1280 */
483f9ef9 1281function sqimap_tree_to_ref_array(&$mbx_tree,&$aMbxs) {
5c300c60 1282 if ($mbx_tree)
483f9ef9 1283 $aMbxs[] =& $mbx_tree;
1284 if ($mbx_tree->mbxs) {
1285 $iCnt = count($mbx_tree->mbxs);
1286 for ($i=0;$i<$iCnt;++$i) {
5c300c60 1287 sqimap_tree_to_ref_array($mbx_tree->mbxs[$i],$aMbxs);
483f9ef9 1288 }
1289 }
4669e892 1290}
483f9ef9 1291
3131bc8d 1292/**
1293 * @param stream $imap_stream imap connection resource
1294 * @param object $mbx_tree
1295 * @since since 1.5.0
1296 */
483f9ef9 1297function sqimap_get_status_mbx_tree($imap_stream,&$mbx_tree) {
1298 global $unseen_notify, $unseen_type, $trash_folder,$move_to_trash;
8d8da447 1299 $aMbxs = $aQuery = array();
483f9ef9 1300 sqimap_tree_to_ref_array($mbx_tree,$aMbxs);
1301 // remove the root node
1302 array_shift($aMbxs);
1303
1304 if($unseen_notify == 3) {
1305 $cnt = count($aMbxs);
1306 for($i=0;$i<$cnt;++$i) {
5c300c60 1307 $oMbx =& $aMbxs[$i];
1308 if (!$oMbx->is_noselect) {
483f9ef9 1309 $mbx = $oMbx->mailboxname_full;
5c300c60 1310 if ($unseen_type == 2 ||
1311 ($move_to_trash && $oMbx->mailboxname_full == $trash_folder)) {
48879ef0 1312 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (MESSAGES UNSEEN RECENT)';
5c300c60 1313 } else {
48879ef0 1314 $query = 'STATUS ' . sqimap_encode_mailbox_name($mbx) . ' (UNSEEN RECENT)';
5c300c60 1315 }
483f9ef9 1316 sqimap_prepare_pipelined_query($query,$tag,$aQuery,false);
5c300c60 1317 } else {
48879ef0 1318 $oMbx->unseen = $oMbx->total = $oMbx->recent = false;
5c300c60 1319 $tag = false;
1320 }
1321 $oMbx->tag = $tag;
1322 $aMbxs[$i] =& $oMbx;
483f9ef9 1323 }
1324 // execute all the queries at once
1325 $aResponse = sqimap_run_pipelined_command ($imap_stream, $aQuery, false, $aServerResponse, $aServerMessage);
1326 $cnt = count($aMbxs);
1327 for($i=0;$i<$cnt;++$i) {
5c300c60 1328 $oMbx =& $aMbxs[$i];
1329 $tag = $oMbx->tag;
1330 if ($tag && $aServerResponse[$tag] == 'OK') {
1331 $sResponse = implode('', $aResponse[$tag]);
483f9ef9 1332 if (preg_match('/UNSEEN\s+([0-9]+)/i', $sResponse, $regs)) {
1333 $oMbx->unseen = $regs[1];
1334 }
1335 if (preg_match('/MESSAGES\s+([0-9]+)/i', $sResponse, $regs)) {
1336 $oMbx->total = $regs[1];
5c300c60 1337 }
48879ef0 1338 if (preg_match('/RECENT\s+([0-9]+)/i', $sResponse, $regs)) {
1339 $oMbx->recent = $regs[1];
1340 }
1341
5c300c60 1342 }
1343 unset($oMbx->tag);
1344 }
483f9ef9 1345 } else if ($unseen_notify == 2) { // INBOX only
1346 $cnt = count($aMbxs);
1347 for($i=0;$i<$cnt;++$i) {
5c300c60 1348 $oMbx =& $aMbxs[$i];
1349 if (strtoupper($oMbx->mailboxname_full) == 'INBOX' ||
1350 ($move_to_trash && $oMbx->mailboxname_full == $trash_folder)) {
4669e892 1351 if ($unseen_type == 2 ||
5c300c60 1352 ($oMbx->mailboxname_full == $trash_folder && $move_to_trash)) {
1353 $aStatus = sqimap_status_messages($imap_stream,$oMbx->mailboxname_full);
1354 $oMbx->unseen = $aStatus['UNSEEN'];
1355 $oMbx->total = $aStatus['MESSAGES'];
48879ef0 1356 $oMbx->recent = $aStatus['RECENT'];
5c300c60 1357 } else {
1358 $oMbx->unseen = sqimap_unseen_messages($imap_stream,$oMbx->mailboxname_full);
1359 }
1360 $aMbxs[$i] =& $oMbx;
1361 if (!$move_to_trash && $trash_folder) {
1362 break;
1363 } else {
1364 // trash comes after INBOX
1365 if ($oMbx->mailboxname_full == $trash_folder) {
1366 break;
1367 }
1368 }
1369 }
1370 }
4669e892 1371 }
48879ef0 1372
1373 $cnt = count($aMbxs);
1374 for($i=0;$i<$cnt;++$i) {
1375 $oMbx =& $aMbxs[$i];
1376 unset($hook_status);
1377 if (!empty($oMbx->unseen)) { $hook_status['UNSEEN']=$oMbx->unseen; }
1378 if (!empty($oMbx->total)) { $hook_status['MESSAGES']=$oMbx->total; }
1379 if (!empty($oMbx->recent)) { $hook_status['RECENT']=$oMbx->recent; }
1380 if (!empty($hook_status))
1381 {
1382 $hook_status['MAILBOX']=$oMbx->mailboxname_full;
1383 $hook_status['CALLER']='sqimap_get_status_mbx_tree'; // helps w/ debugging
1384 do_hook_function('folder_status',$hook_status);
1385 }
1386 }
4669e892 1387}
587ec647 1388
367fb0ca 1389/**
1390 * Checks if folder is noselect (can't store messages)
1391 *
1392 * Function does not check if folder subscribed.
1393 * @param stream $oImapStream imap connection resource
1394 * @param string $sImapFolder imap folder name
1395 * @param object $oBoxes mailboxes class object.
1396 * @return boolean true, when folder has noselect flag. false in any other case.
1397 * @since 1.5.1
1398 */
1399function sqimap_mailbox_is_noselect($oImapStream,$sImapFolder,&$oBoxes) {
1400 // build mailbox object if it is not available
1401 if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
1402 foreach($oBoxes as $box) {
1403 if ($box['unformatted']==$sImapFolder) {
1404 return (bool) check_is_noselect($box['raw']);
1405 }
1406 }
1407 return false;
1408}
1409
1410/**
1411 * Checks if folder is noinferiors (can't store other folders)
1412 *
1413 * Function does not check if folder subscribed.
1414 * @param stream $oImapStream imap connection resource
1415 * @param string $sImapFolder imap folder name
1416 * @param object $oBoxes mailboxes class object.
1417 * @return boolean true, when folder has noinferiors flag. false in any other case.
1418 * @since 1.5.1
1419 */
1420function sqimap_mailbox_is_noinferiors($oImapStream,$sImapFolder,&$oBoxes) {
1421 // build mailbox object if it is not available
1422 if (! is_object($oBoxes)) $oBoxes=sqimap_mailbox_list($oImapStream);
1423 foreach($oBoxes as $box) {
1424 if ($box['unformatted']==$sImapFolder) {
1425 return (bool) check_is_noinferiors($box['raw']);
1426 }
1427 }
1428 return false;
1429}