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