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