+
+/**
+* Retrieves an array with a sorted uid list. Sorting is done by SquirrelMail
+*
+* @param resource $imap_stream IMAP socket connection
+* @param string $sSortField Field to sort on
+* @param bool $reverse Reverse order search
+* @return array $aUid sorted uid list
+*/
+function get_squirrel_sort ($imap_stream, $sSortField, $reverse = false) {
+
+ if ($sSortField == 'UID') {
+ // FIX ME: this is not needed. Try to find another way to solve this
+ $query = "SEARCH UID 1:*";
+ $uids = sqimap_run_command ($imap_stream, $query, true, $response, $message, true);
+ if (isset($uids[0])) {
+ if (preg_match("/^\* SEARCH (.+)$/", $uids[0], $regs)) {
+ $msgs = preg_split("/ /", trim($regs[1]));
+ }
+ }
+ if (!preg_match("/OK/", $response)) {
+ $msgs = false;
+ }
+ } else if ($sSortField != 'RFC822.SIZE' && $sSortField != 'INTERNALDATE') {
+ $msgs = sqimap_get_small_header_list($imap_stream, false, '*',
+ array($sSortField), array('UID'));
+ } else {
+ $msgs = sqimap_get_small_header_list($imap_stream, false, '*',
+ array(), array('UID', $sSortField));
+ }
+ $aUid = array();
+ $walk = false;
+ switch ($sSortField) {
+ // natcasesort section
+ case 'FROM':
+ case 'TO':
+ case 'CC':
+ if(!$walk) {
+ array_walk($msgs, create_function('&$v,&$k,$f',
+ '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
+ $addr = parseAddress($v[$f]);
+ $v[$f] = ($addr[0][1]) ? decodeHeader($addr[0][1]):$addr[0][0];'),$sSortField);
+ $walk = true;
+ }
+ // nobreak
+ case 'SUBJECT':
+ if(!$walk) {
+ array_walk($msgs, create_function('&$v,&$k,$f',
+ '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
+ $v[$f] = strtolower(decodeHeader(trim($v[$f])));
+ $v[$f] = (preg_match("/^(vedr|sv|re|aw|\[\w\]):\s*(.*)$/si", $v[$f], $matches)) ?
+ $matches[2] : $v[$f];'),$sSortField);
+ $walk = true;
+ }
+ foreach ($msgs as $item) {
+ $aUid[$item['ID']] = $item[$sSortField];
+ }
+ natcasesort($aUid);
+ $aUid = array_keys($aUid);
+ if ($reverse) {
+ array_reverse($aUid);
+ }
+ break;
+ // \natcasesort section
+ // sort_numeric section
+ case 'DATE':
+ case 'INTERNALDATE':
+ if(!$walk) {
+ array_walk($msgs, create_function('&$v,$k,$f',
+ '$v[$f] = (isset($v[$f])) ? $v[$f] : "";
+ $v[$f] = getTimeStamp(explode(" ",$v[$f]));'),$sSortField);
+ $walk = true;
+ }
+ // nobreak;
+ case 'RFC822.SIZE':
+ if(!$walk) {
+ // redefine $sSortField to maintain the same namespace between
+ // server-side sorting and squirrelmail sorting
+ $sSortField = 'SIZE';
+ }
+ foreach ($msgs as $item) {
+ $aUid[$item['ID']] = (isset($item[$sSortField])) ? $item[$sSortField] : 0;
+ }
+ if ($reverse) {
+ arsort($aUid,SORT_NUMERIC);
+ } else {
+ asort($aUid, SORT_NUMERIC);
+ }
+ $aUid = array_keys($aUid);
+ break;
+ // \sort_numeric section
+ case 'UID':
+ $aUid = array_reverse($msgs);
+ break;
+ }
+ return $aUid;
+}
+
+/**
+* Returns an indent array for printMessageinfo()
+* This represents the amount of indent needed (value),
+* for this message number (key)