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