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