Index: branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 3798)
+++ branches/2.2/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 3803)
@@ -3383,165 +3383,148 @@
 
 	function search_msg($params = ''){
-		$retorno = "";
-		$mbox_stream = "";
-		if(strpos($params['condition'],"#")===false) { //local messages
-			$search=false;
-		}
-		else {
-			$search = explode(",",$params['condition']);
-		}
-
-                $offsetToGMT = $this->functions->CalculateDateOffset();
-
-		if($search){
-			$search_criteria = '';
-                        $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
-                        foreach($search as $tmp)
-			{
-				$tmp1 = explode("##",$tmp);
-                                $sum = 0;
-				$name_box = $tmp1[0];
-				unset($filter);
-				foreach($tmp1 as $index => $criteria)
-				{
-                                    if ($index != 0 && strlen($criteria) != 0)
+            $mbox_stream = "";
+            if(strpos($params['condition'],"#")===false) { //local messages? It shouldn't be necessary, should it? FIXME
+                    $search=false;
+            }
+            else {
+                    $search = explode(",",$params['condition']);
+	    }
+	    $params['page'] = $params['page']*1;
+
+	    if(is_array($search)){
+		$search = array_unique($search); // Remove duplicated folders
+                $search_criteria = '';
+                $search_result_number = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'];
+                foreach($search as $tmp)
+                {
+                    $tmp1 = explode("##",$tmp);
+                    $sum = 0;
+                    $name_box = $tmp1[0];
+                    unset($filter);
+                    foreach($tmp1 as $index => $criteria)
+                    {
+                        if ($index != 0 && strlen($criteria) != 0)
+                        {
+                            $filter_array = explode("<=>",rawurldecode($criteria));
+                            $filter .= " ".$filter_array[0];
+                            if (strlen($filter_array[1]) != 0){
+                                if (trim($filter_array[0]) != 'BEFORE' &&
+                                    trim($filter_array[0]) != 'SINCE' &&
+                                    trim($filter_array[0]) != 'ON')
+                                {
+                                    $filter .= '"'.$filter_array[1].'"';
+                                }
+                                else
                                     {
-                                        $filter_array = explode("<=>",html_entity_decode(rawurldecode($criteria)));
-                                        $filter .= " ".$filter_array[0];
-                                        if (strlen($filter_array[1]) != 0){
-                                            if (trim($filter_array[0]) != 'BEFORE' &&
-                                                trim($filter_array[0]) != 'SINCE' &&
-                                                trim($filter_array[0]) != 'ON')
-                                            {
-                                                // Remove accents from criteria, because method remove accents is broken.
-                                                $a = 'áàâãäéèêëíìîïóòôõöúùûüçÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇ';
-                                                $b = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
-                                                $filter .= '"'.strtr($filter_array[1], $a, $b).'"';
-                                            }
-                                            else {
-                                                $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
-                                            }
-                                        }
+                                        $filter .= '"'.$this->make_search_date($filter_array[1]).'"';
                                     }
-				}
-				$name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
-
-                                //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
-				if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
-				{
-					$folder_name = explode($this->imap_delimiter,$name_box);
-					$this->ldap = new ldap_functions();
-					if ($cn = $this->ldap->uid2cn($folder_name[1]))
-					{
-						$folder_name[1] = $cn;
-					}
-					$folder_name = implode($this->imap_delimiter,$folder_name);
-				}
-				else
-					$folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
-
-				if(!is_resource($mbox_stream))
-					$mbox_stream = $this->open_mbox($name_box);
-				else
-					imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
-
-                if (preg_match("/^.?\bALL\b/", $filter)){ // Quick Search, note: this ALL isn't the same ALL from imap_search
-
-					$all_criterias = array ("TO","SUBJECT","FROM","CC");
-
-					foreach($all_criterias as $criteria_fixed)
-					{
-						$_filter = $criteria_fixed . substr($filter,4);
-
-						$search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
-						// Testa aqui
-						if($search_criteria) // && count($search_criteria) < $search_result_number)
-						{
-							foreach($search_criteria as $new_search){
-                                if ($search_result_number != '65536' && $sum == $search_result_number)
+                            }
+                        }
+                    }
+                    $name_box = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
+                    $filter = $this->remove_accents($filter);
+                    //Este bloco tem a finalidade de transformar o login (quando numerico) das pastas compartilhadas em common name
+                    if ($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] && substr($name_box,0,4) == 'user')
+                    {
+                        $folder_name = explode($this->imap_delimiter,$name_box);
+                        $this->ldap = new ldap_functions();
+                        if ($cn = $this->ldap->uid2cn($folder_name[1]))
+                        {
+                            $folder_name[1] = $cn;
+                        }
+                        $folder_name = implode($this->imap_delimiter,$folder_name);
+                    }
+                    else
+                    {
+                        $folder_name = mb_convert_encoding(utf8_decode($name_box), "UTF7-IMAP", "ISO_8859-1" );
+                    }
+
+                    if(!is_resource($mbox_stream))
+                    {
+                        $mbox_stream = $this->open_mbox($name_box);
+                    }
+                    else
+                        {
+                            imap_reopen($mbox_stream, "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}".$name_box);
+                        }
+
+                    if (preg_match("/^.?\bALL\b/", $filter))
+                    { // Quick Search, note: this ALL isn't the same ALL from imap_search
+
+                        $all_criterias = array ("TO","SUBJECT","FROM","CC");
+                        foreach($all_criterias as $criteria_fixed)
+                        {
+                            $_filter = $criteria_fixed . substr($filter,4);
+
+                            $search_criteria = imap_search($mbox_stream, $_filter, SE_UID);
+
+                            if(is_array($search_criteria))
+                            {
+                                foreach($search_criteria as $new_search)
                                 {
-                                  return $retorno ? $sum . "=sumResults=" . $retorno : "none";
-                                }
-
-								$m_token = trim("##". mb_convert_encoding( $folder_name, "ISO_8859-1", "UTF7-IMAP" ) . "--" . mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--".$new_search."##"."\n");
-								if(!@strstr($retorno,$m_token))
-                                {
-                                    $retorno .= $m_token;
-                                    $sum++;
-                                }
-							}
-						}
-					}
-				}
-				else {
-					$search_criteria = imap_search($mbox_stream, $filter, SE_UID);
-					if($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag'])
-					{
-	                	if((!strpos($filter,"FLAGGED") === false) || (!strpos($filter,"UNFLAGGED") === false))
-						{
-	                		$num_msgs = imap_num_msg($mbox_stream);
-							$flagged_msgs = array();
-							for ($i=$num_msgs; $i>0; $i--)
-							{								
-								$iuid = @imap_uid($this->mbox,$i);
-								$header = $this->get_header($iuid);								
-								if(trim($header->Flagged))
-								{
-									$flagged_msgs[$i] = $iuid;
-								}
-							}
-							if((count($flagged_msgs) >0) && (strpos($filter,"UNFLAGGED") === false))
-							{
-								$arry_diff = array_diff($flagged_msgs,$search_criteria);
-								foreach($arry_diff as $msg)
-								{
-									$search_criteria[] = $msg;
-								}
-							}
-							else if((count($flagged_msgs) >0) && (is_array($search_criteria)) && (!strpos($filter,"UNFLAGGED") === false))
-							{
-								$search_criteria = array_diff($search_criteria,$flagged_msgs);
-							}
-						}
-					}	
-					if( is_array( $search_criteria) )
-					{
-						foreach($search_criteria as $new_search)
-                                                {
-                                                    if ($search_result_number != '65536' && $sum == $search_result_number)
-                                                    {
-                                                        return $retorno ? $sum . "=sumResults=" . $retorno : "none";
-                                                    }
-                                                    $retorno .= trim("##". mb_convert_encoding( $folder_name, "ISO_8859-1", "UTF7-IMAP" ) . "--" . mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ) . "--" . $this->get_msg($new_search,$name_box,$mbox_stream) . "--" . $new_search."##"."\n");
-                                                    $sum++;
-                                                }
-					}
-				}
-
-//                                $acumulated_results += $sum;
-//
-//                                if ($search_result_number != '65536' && $acumulated_results >= $search_result_number)
-//                                {
-//                                    return "many results";
-//                                }
-			}
-		}
-		if($mbox_stream)
-			imap_close($mbox_stream);
-
-                if ($retorno){
-                    return $retorno;
+				    $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream); 
+				    $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ); 
+				    $elem['uid'] = $new_search; 
+				    $retorno[] = $elem; 
+				}
+			    }
+                        }
+                    }
+                    else {
+                        $search_criteria = imap_search($mbox_stream, $filter, SE_UID);
+                        if( is_array( $search_criteria) )
+                        {
+                            foreach($search_criteria as $new_search)
+			    {
+				    $elem = $this->get_msg_detail($new_search,$name_box,$mbox_stream); 
+				    $elem['boxname'] = mb_convert_encoding( $name_box, "ISO_8859-1", "UTF7-IMAP" ); 
+				    $elem['uid'] = $new_search; 
+				    $retorno[] = $elem;
+                            }
+                        }
+		    }
                 }
-                else
-                {
-                    return 'none';
-                }
-		//return $retorno ? $retorno : "none";
-	}
-
-	function get_msg($uid_msg,$name_box, $mbox_stream )
+            }
+            if($mbox_stream)
+            {
+                imap_close($mbox_stream);
+	    }
+	    $num_msgs = count($retorno);
+
+	    /* Comparison functions, descendent is ascendent with parms inverted */
+	    function SORTDATE($a, $b) { return ($a['udate'] < $b['udate']); }
+	    function SORTDATE_REVERSE($b, $a) { return SORTDATE($a,$b); }
+
+	    function SORTWHO($a, $b) { return (strtoupper($a['from']) > strtoupper($b['from'])); }
+	    function SORTWHO_REVERSE($b, $a) { return SORTWHO($a,$b); }
+
+	    function SORTSUBJECT($a, $b) { return (strtoupper($a['subject']) > strtoupper($b['subject'])); }
+	    function SORTSUBJECT_REVERSE($b, $a) { return SORTSUBJECT($a,$b); }
+
+	    function SORTBOX($a, $b) { return ($a['boxname'] > $b['boxname']); }
+	    function SORTBOX_REVERSE($b, $a) { return SORTBOX($a,$b); }
+
+	    function SORTSIZE($a, $b) { return ($a['size'] > $b['size']); }
+	    function SORTSIZE_REVERSE($b, $a) { return SORTSIZE($a,$b); }
+
+	    usort($retorno, $params['sort_type']);
+	    $pageret = array_slice($retorno, $params['page'] * $this->prefs['max_email_per_page'], $this->prefs['max_email_per_page']);
+	    $arrayRetorno['num_msgs'] =  $num_msgs;
+	    $arrayRetorno['data'] =  $pageret;
+
+            if ($pageret)
+            {
+                return $arrayRetorno;
+            }
+            else
+            {
+                return 'none';
+            }
+	}
+
+	function get_msg_detail($uid_msg,$name_box, $mbox_stream )
 	{
 		$header = $this->get_header($uid_msg);
-		include_once("class.imap_attachment.inc.php");
+		require_once("class.imap_attachment.inc.php");
 		$imap_attachment = new imap_attachment();
 		$attachments =  $imap_attachment->get_attachment_headerinfo($mbox_stream, $uid_msg);
@@ -3560,5 +3543,9 @@
 		if($header->from[0]->personal != "")
 			$from = $header->from[0]->personal;
-		$ret_msg = $this->decode_string($from) . "--" . htmlentities(rawurlencode($subject)) . "--". gmdate("d/m/Y",$header ->udate + $this->functions->CalculateDateOffset())."--". $this->size_msg($header->Size) ."--". $flag;
+		$ret_msg['from'] = $this->decode_string($from); 
+		$ret_msg['subject'] = $subject; 
+		$ret_msg['udate'] = gmdate("d/m/Y",$header->udate + $this->functions->CalculateDateOffset()); 
+		$ret_msg['size'] = $header->Size; 
+		$ret_msg['flag'] = $flag; 
 		return $ret_msg;
 	}
@@ -3810,4 +3797,7 @@
 		if (!is_object($header))
 			return false;
+		// Prepare udate from mailDate (DateTime arrived with TZ) for fixing summertime problem.
+		$pdate = date_parse($header->MailDate);
+ 		$header->udate +=  $pdate['zone']*(-60);
 
 		if($header->Flagged != "F" && $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_important_flag']) {
@@ -3855,22 +3845,19 @@
     }
 
-    function show_decript($params,$dec=0){
-        
+    function show_decript($params){
         $source = $params['source'];
         //error_log("source: $source\nversao: " . PHP_VERSION, 3, '/tmp/teste.log');
-
-        if ($dec == 0)
-        {
-            $source = str_replace(" ", "+", $source,$i);
-            if (version_compare(PHP_VERSION, '5.2.0', '>=')){
-                if(!$source = base64_decode($source,true))
-                    return "error ".$source."Espaços ".$i;
-
-            }
-            else {
-                if(!$source = base64_decode($source))
-                    return "error ".$source."Espaços ".$i;
-            }
+        $source = str_replace(" ", "+", $source,$i);
+
+        if (version_compare(PHP_VERSION, '5.2.0', '>=')){
+            if(!$source = base64_decode($source,true))
+                return "error ".$source."Espaços ".$i;
+
         }
+        else {
+            if(!$source = base64_decode($source))
+                return "error ".$source."Espaços ".$i;
+        }
+
         $insert = $this->insert_email($source,'INBOX'.$this->imap_delimiter.'decifradas');
 
