Index: trunk/expressoMail1_2/inc/class.imap_functions.inc.php
===================================================================
--- trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5212)
+++ trunk/expressoMail1_2/inc/class.imap_functions.inc.php	(revision 5216)
@@ -2329,244 +2329,128 @@
             return $contentType;
     }
-
-	 /**
-     * Metodo que retorna todas as pastas do usuario logado.
-     * @param $params array opcional para repassar os argumentos ao metodo.
-     * Se usar $params['noSharedFolders'] = true, ira retornar todas as pastas do usuário logado,
-     * excluindo as compartilhadas para ele.
-     * Se usar $params['folderType'] = "default" irá retornar somente as pastas defaults
-     * Se usar $params['folderType'] = "personal" irá retornar somente as pastas pessoais
-     * Se usar $params['folderType'] = null irá retornar todas as pastas
-     * @return Retorna um array contendo as seguintes informacoes de cada pasta: folder_unseen,
-     * folder_id, folder_name, folder_parent e folder_hasChildren.
-     */
+    
+	function getFolderPos(&$array , $find)
+	{            
+		foreach($array as $i => $v)
+			if($v['id'] === $find)
+				return $i;
+		return false;
+	}
+	
+        /**
+        * Ordenas as pastas padrões do usuario na ordem INBOX > SENT > DRAFTS > SPAM > TRASH > OTHERS
+        *
+        * @license    http://www.gnu.org/copyleft/gpl.html GPL
+        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+        * @sponsor    Caixa Econômica Federal
+        * @author     Cristiano Corrêa Schmidt
+        * @access     public
+        */
+	function orderDefaultFolders( &$folders , $user)
+	{
+		$principals = array();
+		for($x = 0; $x < 5 ; $x++)
+		{
+			switch ($x) {
+				case 0:                             
+					if( ($p = $this->getFolderPos($folders , $user )) || $p === 0 )
+						$principals[] = $folders[$p];
+					break;
+				case 1:
+					if( ($p = $this->getFolderPos($folders , $user . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'] )) || $p === 0 )
+						$principals[] = $folders[$p];
+					break;
+				case 2:
+					if( ($p = $this->getFolderPos($folders , $user . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'] )) || $p === 0 )
+						$principals[] = $folders[$p];
+					break;
+				case 3:
+					if( ($p = $this->getFolderPos($folders , $user . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'] )) || $p === 0 )
+						$principals[] = $folders[$p];
+					break;
+				case 4:
+					if( ($p = $this->getFolderPos($folders , $user . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'] )) || $p === 0  )
+						$principals[] = $folders[$p];                                           
+					break;
+			}
+			if($p !== false)
+				unset($folders[$p]);
+		}
+		$folders = array_merge($principals, $folders);
+	}
+        
+        /**
+        * Retorna lista de pastas do usuario no padrão que a lib javascript espera.
+        *
+        * @license    http://www.gnu.org/copyleft/gpl.html GPL
+        * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+        * @sponsor    Caixa Econômica Federal
+        * @author     Cristiano Corrêa Schmidt
+        * @access     public
+        */
 	function get_folders_list($params = null)
 	{
-		$mbox_stream = $this->open_mbox();
-		if($params &&  array_key_exists('onload', $params)   &&  $params['onload'] && $_SESSION['phpgw_info']['expressomail']['server']['certificado']){
-			$this->delete_mailbox(array("del_past" => "INBOX".$this->imap_delimiter."decifradas"));
-		}
-
-		$inbox = 'INBOX';
-		$drafts = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
-		$sent = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
-		$spam = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
-		$trash = $inbox . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
-
-		if(array_key_exists('uid2cn', $_SESSION['phpgw_info']['user']['preferences']['expressoMail'] ))
-		$uid2cn = $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn']; 
+		///Define Variaveis
+		$prefixShared = 'user'; //Prefixo das pastas compartilhadas
+		$uid2cn = (isset($_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'])) ? $_SESSION['phpgw_info']['user']['preferences']['expressoMail']['uid2cn'] : false; 
+		$mboxStream = $this->open_mbox(); //abre conexão imap
+		$currentFolder = isset($params['folder']) ? $params['folder'] : 'INBOX';
+		$folders = array();
+		$return = array();
+		///////////////////////////////////////////////////////////////
+                    
+		if( isset($params['onload']) && $_SESSION['phpgw_info']['expressomail']['server']['certificado'])
+			$this->delete_mailbox(array('del_past' => 'INBOX'.$this->imap_delimiter.'decifradas')); //Deleta Pasta decifradas
+		
+		session_write_close(); // Free others requests 
+		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}"; 
+		
+		if ( isset($params['noSharedFolders']) )
+			$folders_list = array_merge(imap_getmailboxes($mboxStream, $serverString, 'INBOX' ), imap_getmailboxes($mboxStream, $serverString, 'INBOX/*' ) );
 		else
-			$uid2cn = false;
-		// Free others requests 
-		session_write_close(); 
-
-		$serverString = "{".$this->imap_server.":".$this->imap_port.$this->imap_options."}"; 
-		
-		if ( $params && isset($params['noSharedFolders']) )
-			$folders_list = array_merge(imap_getmailboxes($mbox_stream, $serverString, 'INBOX' ), imap_getmailboxes($mbox_stream, $serverString, 'INBOX/*' ) );
-		else
-			$folders_list = imap_getmailboxes($mbox_stream, $serverString, '*' );
+			$folders_list = imap_getmailboxes($mboxStream, $serverString, '*' );
 
 		$folders_list = array_slice($folders_list,0,$this->foldersLimit); 
 
-		$tmp = array(); 
-		$resultMine = array(); 
-		$resultSharedMine = array(); 
-		$resultDefault = array(); 
-		$resultSharedDefault = array(); 
-		$aux = "";
-		$qtd = -1 ;
-
-		if (is_array($folders_list)) {
-			reset($folders_list);
-			$this->ldap = new ldap_functions();
-
-			$i = 0;
-			while (list($key, $val) = each($folders_list)) {
-				$status = imap_status($mbox_stream, $val->name, SA_UNSEEN);
-
-				//$tmp_folder_id = explode("}", imap_utf7_decode($val->name));
-				$tmp_folder_id = explode("}", $val->name );
-
-				$folderUser = trim( strpos( $tmp_folder_id[1], $this->imap_delimiter , 5 ) );
-
-				$folderUser = trim( substr( $tmp_folder_id[1], 0, $folderUser ) );
-
-				$Permission = true;
-
-				if( $folderUser != "INBOX" && $folderUser != "" )
-				{
-					$Permission = @imap_getacl( $mbox_stream, $folderUser );
-				}
-				$tmp_folder_id[1] = mb_convert_encoding( $tmp_folder_id[1], "ISO-8859-1", "UTF7-IMAP" );
-
-				if( $tmp_folder_id[1]=='INBOX'.$this->imap_delimiter.'decifradas')
-				{
-					continue;
-				}
-				
-				if(isset($status->unseen))
-					$result[$i]['folder_unseen'] = $status->unseen;
-				
-				$folder_id = $tmp_folder_id[1];
-				$result[$i]['folder_id'] = $folder_id;
-
-				$tmp_folder_parent = explode($this->imap_delimiter, $folder_id);
-				$result[$i]['folder_name'] = array_pop($tmp_folder_parent);
-				$result[$i]['folder_name'] = $result[$i]['folder_name'] == 'INBOX' ? 'Inbox' : $result[$i]['folder_name'];
+		if (!is_array($folders_list)) return false;
+			if($uid2cn)
+				$this->ldap = new ldap_functions();
+                
+		foreach ($folders_list as $i => $v ) //Separando Pastas e informações
+		{
+			$folderId = substr($v->name,(strpos($v->name , '}') + 1));
+			$nameArray = explode($this->imap_delimiter, $folderId);
+			$nameCount = count($nameArray);
+			$decifrada = mb_convert_encoding('INBOX'.$this->imap_delimiter.'decifradas','UTF7-IMAP','ISO-8859-1'); //Ignorar esta pasta decifrada
+			$parent = ($nameCount > 1 && $nameArray[($nameCount - 2)] !== 'INBOX') ? implode($this->imap_delimiter, array_slice($nameArray, 0, ($nameCount - 1))): ''; //Pega folder pai
+			if($nameArray[0] === 'user')
+				$folders[$prefixShared.$this->imap_delimiter.$nameArray[1]][] = array('id' => $folderId , 'stream' => $v->name , 'attributes' => $v->attributes , 'name' => $nameArray[($nameCount-1)] , 'user' => $nameArray[1] ,'parent' => $parent);
+			else if( $folderId !== $decifrada) //Escapa pasta decifrada
+				$folders['INBOX'][] =  array('id' => $folderId , 'stream' => $v->name , 'attributes' => $v->attributes ,'name' => $nameArray[($nameCount-1)] , 'parent' => $parent);
+		}
+		unset($folders_list); //destroy array de objetos desnecessarios
+		foreach($folders as $i => $v) //Ordenando e resgatando novas informações
+		{
+			$this->orderDefaultFolders($folders[$i] , $i);  //Ordenando Pastas Padrões
 			
-				if ($uid2cn && substr($folder_id,0,4) == 'user') {
-					//$this->ldap = new ldap_functions();
-					if ($cn = $this->ldap->uid2cn($result[$i]['folder_name'])) {
-						$result[$i]['folder_name'] = $cn;
-					}
-				}
-
-				$tmp_folder_parent = implode($this->imap_delimiter, $tmp_folder_parent);
-				$result[$i]['folder_parent'] = $tmp_folder_parent == 'INBOX' ? '' : $tmp_folder_parent;
-
-				if (($val->attributes == 32) && ($result[$i]['folder_name'] != 'Inbox'))
-					$result[$i]['folder_hasChildren'] = 1;
-				else
-					$result[$i]['folder_hasChildren'] = 0;
-				$user = explode($this->imap_delimiter , $tmp_folder_id[1]);
-				switch ($tmp_folder_id[1]) {
-					case $inbox:
-					case $drafts:
-					case $sent:
-					case $spam:
-					case $trash:
-						$resultDefault[]=$result[$i];
-						break;
-					case "user". $this->imap_delimiter . $user[1]:
-					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']:
-					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']:
-					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']:
-					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']:
-						if($aux != $user[1]){
-							$aux = $user[1];
-							$qtd += 1;
-						}
-						if( isset($resultSharedDefault[$qtd]) && !is_array($resultSharedDefault[$qtd]))
-							$resultSharedDefault[$qtd] = array();
-						$resultSharedDefault[$qtd][]=$result[$i];
-						break;	
-					default:
-						if($user[0] == $inbox)
-							$resultMine[]=$result[$i];
-						else{
-							if($aux != $user[1]){
-								$aux = $user[1];
-								$qtd += 1;
-							}
-							if(!is_array($resultSharedDefault[$qtd]))
-								$resultSharedMine[$qtd] = array();
-							$resultSharedMine[$qtd][]=$result[$i];
-						}
-
-				}
-                            $i++;
-			}
-		}
-
-		if ( $params && !array_key_exists('noQuotaInfo',$params) ) {
-			//Get quota info of current folder
-			$current_folder = "INBOX";
-			if($params && isset($params['folder']))
-				$current_folder = $params['folder'];
-
-			$arr_quota_info = $this->get_quota(array('folder_id' => $current_folder));
-		} else {
-			$arr_quota_info = array();
-		}
-
-		$result2 = array();
-		
-		// Sorting resultMine
-		if(count($resultMine)){
-			foreach ($resultMine as $folder_info)
+			foreach ($folders[$i] as $ii => $vv)
 			{
-				$array_tmp[] = $folder_info['folder_id'];
-			}
-	
-			if(is_array($array_tmp))
-			{
-				natcasesort($array_tmp);
-		
-				foreach ($array_tmp as $key => $folder_id)
-				{
-					$result2[] = $resultMine[$key];
-				}
-			}
-		}
-		// Sorting resultDefault
-		$resultDefault2 = array();
-		
-		foreach ($resultDefault as $key => $folder_id)
-		{
-
-			switch ($resultDefault[$key]['folder_id']) {
-				case $inbox: 
-					$resultDefault2[0] = $resultDefault[$key];
-					break;
-				case $drafts: 
-					$resultDefault2[1] = $resultDefault[$key];
-					break;
-				case $sent: 
-					$resultDefault2[2] = $resultDefault[$key];
-					break;
-				case $spam: 
-					$resultDefault2[3] = $resultDefault[$key];
-					break;
-				case $trash: 
-					$resultDefault2[4] = $resultDefault[$key];
-					break;
-			}
-		}
-		//RE-ORDENA INDICES
-		ksort($resultDefault2);
-		$shareds = array();
-		if(!empty($resultSharedDefault))
-		for($i = array_shift(array_keys($resultSharedDefault)); $i <= $qtd; $i++){			
-			foreach ($resultSharedDefault[$i] as $key => $folder_id)
-			{
-				$user = explode($this->imap_delimiter , $resultSharedDefault[$i][$key]['folder_id']);
-
-				switch ($resultSharedDefault[$i][$key]['folder_id']) {
-					case "user". $this->imap_delimiter . $user[1]: 
-						$resultSharedDefault2[0] = $resultSharedDefault[$i][$key];
-						break;
-					case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']:  
-						$resultSharedDefault2[1] = $resultSharedDefault[$i][$key];
-						break;	
-					case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']:  
-						$resultSharedDefault2[2] = $resultSharedDefault[$i][$key];
-						break;
-					case "user". $this->imap_delimiter . $user[1]. $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']:  
-						$resultSharedDefault2[3] = $resultSharedDefault[$i][$key];
-						break;
-					case "user". $this->imap_delimiter . $user[1] . $this->imap_delimiter . $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']:
-						$resultSharedDefault2[4] = $resultSharedDefault[$i][$key];
-						break;
-				}
-			}
-			if($resultDefault2 != null)
-				$shareds = array_merge($shareds, $resultSharedDefault2);
-			if(isset($resultSharedMine[$i]) && $resultSharedMine[$i] != null)
-				$shareds = array_merge($shareds, $resultSharedMine[$i]);
-			$resultSharedDefault2 = array();
-		}
-		if ( $params && isset($params['folderType']) && $params['folderType'] == 'default' )
-			return array_merge($resultDefault2, $arr_quota_info);
-
-		if ( $params && array_key_exists('folderType', $params) && $params['folderType'] == 'personal' )
-			return array_merge($result2, $arr_quota_info);
-
-		// Merge default folders and personal
-		$result2 = array_merge($resultDefault2, $result2);
-		if(!empty($shareds))
-			$result2 = array_merge($result2, $shareds);
-		return array_merge($result2, $arr_quota_info);
-	}
+				$append = array();				
+				$append['folder_id'] = mb_convert_encoding($vv['id'],'ISO-8859-1','UTF7-IMAP');//DECODIFICA ID DAS PASTAS COM ACENTOS
+				$append['folder_name'] = (($uid2cn && isset($vv['user'])) && ($cn = $this->ldap->uid2cn($vv['user']))) ? $cn : $vv['name'];
+				$append['folder_name'] = mb_convert_encoding($append['folder_name'],'ISO-8859-1','UTF7-IMAP');//DECODIFICA NOME DAS PASTAS COM ACENTOS
+				$status = imap_status($mboxStream, $vv['stream'], SA_UNSEEN); //Resgata Numero de mensagens não lidas
+				$append['folder_unseen'] = isset($status->unseen) ? $status->unseen : 0 ;
+				$append['folder_hasChildren'] = (($vv['attributes'] == 32) && ($vv['name'] != 'INBOX')) ? 1 : 0;
+				$append['folder_parent'] = $vv['parent'];
+				$return[] = $append;
+			}
+		}
+		
+		$quotaInfo =  (!isset($params['noQuotaInfo'])) ? $this->get_quota( array('folder_id' => $currentFolder)) : false; //VERIFICA SE O USUARIO TEM COTA
+		
+		return ( ( is_array($quotaInfo) ) ?  array_merge($return, $quotaInfo) : $return );        
+	}
+    
 
 	function create_mailbox($arr)
