+/**
+ * Retrieves the namespaces from the IMAP server.
+ * NAMESPACE is an IMAP extension defined in RFC 2342.
+ *
+ * @param stream $imap_stream
+ * @return array
+ */
+function sqimap_get_namespace($imap_stream) {
+ $read = sqimap_run_command($imap_stream, 'NAMESPACE', true, $a, $b);
+ return sqimap_parse_namespace($read[0]);
+}
+
+/**
+ * Parses a NAMESPACE response and returns an array with the available
+ * personal, users and shared namespaces.
+ *
+ * @param string $input
+ * @return array The returned array has the following format:
+ * <pre>
+ * array(
+ * 'personal' => array(
+ * 0 => array('prefix'=>'INBOX.','delimiter' =>'.'),
+ * 1 => ...
+ * ),
+ * 'users' => array(..
+ * ),
+ * 'shared' => array( ..
+ * )
+ * )
+ * </pre>
+ * Note that if a namespace is not defined in the server, then the corresponding
+ * array will be empty.
+ */
+function sqimap_parse_namespace(&$input) {
+ $ns_strings = array(1=>'personal', 2=>'users', 3=>'shared');
+ $namespace = array();
+
+ if(ereg('NAMESPACE (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL) (\(\(.*\)\)|NIL)', $input, $regs) !== false) {
+ for($i=1; $i<=3; $i++) {
+ if($regs[$i] == 'NIL') {
+ $namespace[$ns_strings[$i]] = array();
+ } else {
+ // Pop-out the first ( and last ) for easier parsing
+ $ns = substr($regs[$i], 1, sizeof($regs[$i])-2);
+ if($c = preg_match_all('/\((?:(.*?)\s*?)\)/', $ns, $regs2)) {
+ $namespace[$ns_strings[$i]] = array();
+ for($j=0; $j<sizeof($regs2[1]); $j++) {
+ preg_match('/"(.*)"\s+("(.*)"|NIL)/', $regs2[1][$j], $regs3);
+ $namespace[$ns_strings[$i]][$j]['prefix'] = $regs3[1];
+ if($regs3[2] == 'NIL') {
+ $namespace[$ns_strings[$i]][$j]['delimiter'] = null;
+ } else {
+ // $regs[3] is $regs[2] without the quotes
+ $namespace[$ns_strings[$i]][$j]['delimiter'] = $regs3[3];
+ }
+ unset($regs3);
+ }
+ }
+ unset($ns);
+ }
+ }
+ }
+ return($namespace);
+}
+