Index: /branches/2.4/prototype/adapters/ExpressoAdapter.php
===================================================================
--- /branches/2.4/prototype/adapters/ExpressoAdapter.php	(revision 7443)
+++ /branches/2.4/prototype/adapters/ExpressoAdapter.php	(revision 7443)
@@ -0,0 +1,151 @@
+<?php
+class ExpressoAdapter extends Resource {
+
+	private $cannotModifyHeader;
+	private $expressoVersion;
+	private $request;
+	private $params;
+	private $result;
+	private $error;	
+	private $id;
+	
+	function __construct($id){
+		$GLOBALS['phpgw_info'] = array(
+				'flags' => array(
+						'currentapp'        	=> 'login',
+						'noheader'              => True,
+						'disable_Template_class' => True
+				)
+		);
+		
+		include_once(__DIR__.'/../../header.inc.php');
+		$this->expressoVersion = substr($GLOBALS['phpgw_info']['server']['versions']['phpgwapi'],0,3);
+		$this->setCannotModifyHeader(false);
+	}
+	
+	protected function setRequest($request){
+		$this->request = $request;
+	}
+	
+	public function getRequest(){
+		return $this->request;
+	}
+	
+	protected function getExpressoVersion(){
+		return $this->expressoVersion;
+	}
+	
+	protected function setResult($result){
+		$this->result = $result;
+	}
+	
+	public function getResult(){
+		return $this->result;
+	}
+	
+	protected function setId($id){
+		$this->id = $id;
+	}
+	
+	public function getId(){
+		return $this->id;
+	}
+	
+	protected function setParams($params){		
+		$this->params = $params;
+	}
+	
+	public function getParams(){	
+		return $this->params;
+	}
+	
+	public function getParam($param){
+		return mb_convert_encoding($this->params->$param, "ISO_8859-1", "UTF8");
+	}
+	
+	public function setError($error) {
+		$this-> error = $error;
+	}
+	
+	protected function getError() {
+		return $this-> error;
+	}
+	
+	protected function setCannotModifyHeader($boolean){
+		$this-> cannotModifyHeader = $boolean;
+	}
+	protected function getCannotModifyHeader(){
+		return $this-> cannotModifyHeader;
+	}
+
+	public function post($request){
+		if(!$request->data)
+			$request->data = $_POST;
+		$this->setRequest($request);		
+		if(!is_array($request->data))
+			parse_str(urldecode($request->data), &$request->data);
+		$data = (object)$request->data;		
+		if($data){
+			if($data->params){								
+				$this->setParams(json_decode($data->params));
+			}
+			if($data->id)
+				$this->setId($data->id);
+		}
+	}	
+	
+	public function get($request){
+		$response = new Response($request);
+		$response->code = Response::OK;
+		$response->addHeader('content-type', 'text/html');		
+		$response->body = "<H4>Metodo GET nao permitido para este recurso.</H4>";		
+		return $response;
+	}
+	
+	public function getResponse(){
+		$response = new Response($this->getRequest());
+		
+		if($this->getCannotModifyHeader())
+			return $response;
+		
+		$response->code = Response::OK;
+		$response->addHeader('content-type', 'application/json');
+
+		if($this->getId())
+			$body['id']	= $this->getId();
+		if($this->getResult())
+			$body['result']	= $this->getResult();
+		else {
+			Errors::runException("E_UNKNOWN_ERROR");			
+		}
+		
+		
+		$response->body = json_encode($body);
+		
+		return $response;
+	}
+	
+	protected function isLoggedIn(){
+		if($this->getParam('auth') != null) {
+			list($sessionid, $kp3) = explode(":", $this->getParam('auth'));
+			if(!$GLOBALS['phpgw']->session->verify() && $GLOBALS['phpgw']->session->verify($sessionid, $kp3)){									
+				return $sessionid;
+			}
+			else{
+				Errors::runException("LOGIN_AUTH_INVALID");							
+			}
+		}
+		elseif($sessionid = $GLOBALS['_COOKIE']['sessionid']) {
+			if($GLOBALS['phpgw']->session->verify($sessionid)) {
+				return $sessionid;
+			}
+			else{
+				Errors::runException("LOGIN_NOT_LOGGED_IN");
+			}
+		}
+		else{
+			Errors::runException("LOGIN_NOT_LOGGED_IN");			
+		}		
+	}	
+			
+}
Index: /branches/2.4/prototype/adapters/CalendarAdapter.php
===================================================================
--- /branches/2.4/prototype/adapters/CalendarAdapter.php	(revision 7443)
+++ /branches/2.4/prototype/adapters/CalendarAdapter.php	(revision 7443)
@@ -0,0 +1,19 @@
+<?php
+
+class CalendarAdapter extends ExpressoAdapter {
+	public function __construct($id){
+		parent::__construct($id);
+	}
+
+	protected function getUserId(){
+		return $GLOBALS['phpgw_info']['user']['account_id'];
+	}
+
+	protected function getDb(){
+		return $GLOBALS['phpgw']->db;
+	}
+
+	protected function getTimezoneOffset(){
+		return $GLOBALS['phpgw']->datetime->tz_offset;
+	}
+}
Index: /branches/2.4/prototype/adapters/CatalogAdapter.php
===================================================================
--- /branches/2.4/prototype/adapters/CatalogAdapter.php	(revision 7443)
+++ /branches/2.4/prototype/adapters/CatalogAdapter.php	(revision 7443)
@@ -0,0 +1,119 @@
+<?php
+
+
+class CatalogAdapter extends ExpressoAdapter {	
+	private $minArgumentSearch;
+	private $userId;
+	private $ldapCatalog;
+
+	public function __construct($id){
+		parent::__construct($id);
+		$prefs = $GLOBALS['phpgw']->preferences->read();
+		$this-> setMinArgumentSearch($prefs['expressoMail']['search_characters_number'] ? $prefs['expressoMail']['search_characters_number'] : "4");
+	}
+	
+	protected function setMinArgumentSearch($minArgumentSearch){
+		$this->minArgumentSearch = $minArgumentSearch;
+	}
+	
+	protected function getMinArgumentSearch(){
+		return $this-> minArgumentSearch;
+	}
+	
+	protected function getUserId(){
+		return $GLOBALS['phpgw_info']['user']['account_id'];
+	}		
+
+	
+	protected function getLdapCatalog(){
+		if(!$this->ldapCatalog) {
+			$catalog_config = CreateObject("contactcenter.bo_ldap_manager");
+			$_SESSION['phpgw_info']['expressomail']['ldap_server'] = $catalog_config ? $catalog_config->srcs[1] : null;
+			$this->ldapCatalog = CreateObject("expressoMail1_2.ldap_functions");
+		}
+	
+		return $this->ldapCatalog;
+	}
+	
+	protected function getDb(){
+		return $GLOBALS['phpgw']->db;
+	}	
+	
+	protected function getUserLdapAttrs($mail)
+	{
+		$filter="(&(phpgwAccountType=u)(mail=".$mail."))";
+		$ldap_context = $_SESSION['phpgw_info']['expressomail']['ldap_server']['dn'];
+		$justthese = array("dn", 'jpegPhoto','givenName', 'sn'); 
+		$ds = $this->getLdapCatalog()->ds;
+		if ($ds){
+			$sr = @ldap_search($ds, $ldap_context, $filter, $justthese);	
+			if ($sr) {
+				$entry = ldap_first_entry($ds, $sr);
+				if($entry) {									
+					$givenName = @ldap_get_values_len($ds, $entry, "givenname");
+					$sn = @ldap_get_values_len($ds, $entry, "sn");
+					$contactHasImagePicture = (@ldap_get_values_len($ds, $entry, "jpegphoto") ? 1 : 0);
+					$dn = ldap_get_dn($ds, $entry);
+					return array(
+						"contactID" => urlencode($dn),
+						"contactFirstName" => $givenName[0],
+						"contactLastName" 	=> $sn[0],
+						"contactHasImagePicture" => $contactHasImagePicture 
+					);
+				}
+			}
+		}
+		return false;
+	}
+	
+	protected function getUserLdapPhoto($contactID) {		
+		$ldap_context = $_SESSION['phpgw_info']['expressomail']['ldap_server']['dn'];
+		$justthese = array("dn", 'jpegPhoto','givenName', 'sn');
+		$this->getLdapCatalog()->ldapConnect(true);
+		$ds = $this->getLdapCatalog()->ds;		
+		
+		if ($ds){
+			$resource = @ldap_read($ds, $contactID, "phpgwaccounttype=u");
+			$n_entries = @ldap_count_entries($ds, $resource);
+
+			if ( $n_entries == 1) {			
+				$first_entry = ldap_first_entry($ds, $resource);
+				$obj = ldap_get_attributes($ds, $first_entry);
+				
+				if($obj['jpegPhoto']){
+					return ldap_get_values_len( $ds, $first_entry, "jpegPhoto");
+				}
+			}								
+		}
+		return false;
+	}	
+	
+	protected function getGlobalContacts($search, $uidNumber){
+		$contacts = array();
+		$params = array ("search_for" => $search);
+ 		$result = $this->getLdapCatalog()->quicksearch($params);
+ 		// Reconnect for searching other attributes.
+ 		$this->getLdapCatalog()->ldapConnect(true);
+		foreach($result as $i => $row) {
+			if(is_int($i)) {
+				$contacts[$i] = array(
+					'contactMails'	=> array($result[$i]['mail']),
+					'contactPhones'	=> array($result[$i]['phone']),
+					'contactAlias' => "",					
+					'contactFullName' 	=> ($result[$i]['cn'] != null ? mb_convert_encoding($row['cn'],"UTF8", "ISO_8859-1") : ""),
+					'contactBirthDate'	=> "",
+					'contactNotes' 		=> ""
+				);
+				// Buscar atributos faltantes. 
+				$otherAttrs = $this->getUserLdapAttrs($result[$i]['mail']);
+				if(is_array($otherAttrs))
+					$contacts[$i] = array_merge($otherAttrs, $contacts[$i]);				
+			}
+		}
+		// Force ldap close
+		ldap_close($this->getLdapCatalog()->ds);		
+		$result = array ('contacts' => $contacts);
+		$this->setResult($result);
+		return $this->getResponse();
+	}
+}
Index: /branches/2.4/prototype/adapters/MailAdapter.php
===================================================================
--- /branches/2.4/prototype/adapters/MailAdapter.php	(revision 7443)
+++ /branches/2.4/prototype/adapters/MailAdapter.php	(revision 7443)
@@ -0,0 +1,182 @@
+<?php
+
+class MailAdapter extends ExpressoAdapter {
+	protected $defaultFolders;
+	protected $imap;
+
+	protected function formatMailObject($str) {
+		$str = html_entity_decode($str);
+		$str = preg_replace('/[<>\'"]/', '', $str);
+		$return = array();            
+		if(preg_match('/[[:alnum:]\._\-]+@[[:alnum:]_\-\.]+/',$str, $matches1) &&
+			preg_match('/[[:alnum:]\._\-\ ]+/',$str, $matches2)){            		            
+			return array(					            
+            		'fullName' 	  => mb_convert_encoding(str_replace($matches1[0],'', $str), "UTF8", "ISO_8859-1"),
+					'mailAddress' => $matches1[0]
+					);
+        }
+        else{            	
+           	return array('mailAddress' => $str);           	
+		}		
+    }
+    
+	protected function loadLang($lang_user){		
+		$fn = PHPGW_INCLUDE_ROOT."/expressoMail1_2/setup/phpgw_".$lang_user.'.lang';
+		if (file_exists($fn)){
+			$fp = fopen($fn,'r');
+			while ($data = fgets($fp,16000)){
+				list($message_id,$app_name,$null,$content) = explode("\t",substr($data,0,-1));
+				$_SESSION['phpgw_info']['expressomail']['lang'][$message_id] = $content;
+			}
+			fclose($fp);
+		}
+	}
+	
+		
+	protected function getImap(){
+		if($this->imap == null) {
+			$c = CreateObject('phpgwapi.config','expressoMail1_2');
+			$c->read_repository();
+			$current_config = $c->config_data;
+			$boemailadmin	= CreateObject('emailadmin.bo');
+			$emailadmin_profile = $boemailadmin->getProfileList();
+			$_SESSION['phpgw_info']['expressomail']['email_server'] = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
+			
+			$preferences = $GLOBALS['phpgw']->preferences->read();
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail'] = $preferences['expressoMail'];
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['outoffice'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['outoffice'];
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['telephone_number'] = $GLOBALS['phpgw_info']['user']['telephonenumber'];
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_cache'] = $current_config['expressoMail_enable_cache'];
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['use_x_origin'] = $current_config['expressoMail_use_x_origin'];
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['number_of_contacts'] = $current_config['expressoMail_Number_of_dynamic_contacts'] ? $current_config['expressoMail_Number_of_dynamic_contacts'] : "0";
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['notification_domains'] = $current_config['expressoMail_notification_domains'];
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['search_result_number'] : "50";
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['search_characters_number'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['search_characters_number'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['search_characters_number'] : "4";			
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_attachment_size'] = $current_config['expressoMail_Max_attachment_size'] ? $current_config['expressoMail_Max_attachment_size']."M" : ini_get('upload_max_filesize');
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_msg_size'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_msg_size'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_msg_size'] : "0";
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['imap_max_folders'] = $current_config['expressoMail_imap_max_folders'];
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['max_email_per_page'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_email_per_page'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['max_email_per_page'] : "50";
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['extended_info'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['extended_info']?$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['extended_info'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['extended_info']:'0';
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['from_to_sent'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['from_to_sent'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['from_to_sent'] : "0";
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['return_recipient_deafault'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['return_recipient_deafault'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['return_recipient_deafault'] : "0";			
+			$_SESSION['phpgw_info']['user']['preferences']['expressoMail']['quick_search_default'] = $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['quick_search_default'] ? $GLOBALS['phpgw_info']['user']['preferences']['expressoMail']['quick_search_default'] : 1;
+			
+			
+			$this->loadLang( $GLOBALS['phpgw_info']['user']['preferences']['common']['lang']);														
+			$_SESSION['phpgw_info']['expressomail']['user']['userid'] = $GLOBALS['phpgw_info']['user']['userid'];
+			$_SESSION['phpgw_info']['expressomail']['user']['passwd'] = $GLOBALS['phpgw_info']['user']['passwd'];
+			$_SESSION['phpgw_info']['expressomail']['user']['email'] = $GLOBALS['phpgw']->preferences->values['email'];
+			
+			
+			$this->imap = CreateObject("expressoMail1_2.imap_functions");
+			
+			if($this->defaultFolders == null) {
+				$sent   = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'] = empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder']) ?
+							$this->imap->functions->getLang("Sent") : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSentFolder'];
+				$spam   = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'] = empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder']) ?
+							$this->imap->functions->getLang("Spam"): $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultSpamFolder'];
+				$drafts = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'] = empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder']) ?
+							$this->imap->functions->getLang("Drafts") : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultDraftsFolder'];
+				$trash  = $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'] = empty($_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder']) ?
+							$this->imap->functions->getLang("Trash") : $_SESSION['phpgw_info']['expressomail']['email_server']['imapDefaultTrashFolder'];
+
+				$this->defaultFolders = array (
+						'INBOX' => 0,
+						'INBOX'.$this->imap->imap_delimiter.$spam   => 2,
+						'INBOX'.$this->imap->imap_delimiter.$sent   => 1,
+						'INBOX'.$this->imap->imap_delimiter.$drafts => 4,
+						'INBOX'.$this->imap->imap_delimiter.$trash  => 3
+					);					
+			}
+		}
+				
+		return $this->imap;
+	}
+		
+	protected function messageExists($folderID,$msgID) {
+		 $info_msg = $this -> getImap()-> get_info_msg(
+				array( 'msg_folder'	 => urlencode($folderID),
+						'msg_number' => $msgID				
+				));
+
+		if($info_msg['status_get_msg_info'] == 'false'){
+			return false;
+		} else {
+			return true;
+		}
+	}
+	
+	protected function getMessage(){				
+		$info_msg = $this -> getImap()-> get_info_msg(
+				array( 'msg_folder'	 => urlencode($this->getParam('folderID')),
+						'msg_number' => $this->getParam('msgID')				
+				));
+
+		if($info_msg['status_get_msg_info'] == 'false'){
+			return false;
+		}
+		
+		$msg['msgID']    = $info_msg['msg_number'];
+		$msg['folderID'] = $info_msg['msg_folder'];
+		//$msg['msgDate']	 =  $info_msg['fulldate'];
+		$msg['msgDate']  =  $info_msg['msg_day']." ".$info_msg['msg_hour'];
+		if($info_msg['from']) {
+			$msg['msgFrom']['fullName'] 	= $info_msg['from']['name'];
+			$msg['msgFrom']['mailAddress'] 	= $info_msg['from']['email'];
+		}
+		if($info_msg['sender'] != null){
+			$msg['msgSender']['fullName'] 	= $info_msg['sender']['name'];
+			$msg['msgSender']['mailAddress']= $info_msg['sender']['email'];
+		}		
+		if($info_msg['toaddress2'] != null){
+			$toaddresses = explode(",",$info_msg['toaddress2']);
+			if(count($toaddresses) > 1) {
+				foreach ($toaddresses as $i => $toaddress){
+					$msg['msgTo'][$i] = $this->formatMailObject($toaddress);
+				}
+			}
+			else{
+				$msg['msgTo'][0] = $this->formatMailObject($info_msg['toaddress2']);
+			}
+		}
+		if($info_msg['cc'] != null) {
+			$ccaddresses = explode(",",$info_msg['cc']);
+			if(count($ccaddresses) > 1) {
+				foreach ($ccaddresses as $i => $ccaddress){
+					$msg['msgCC'][$i] = $this->formatMailObject($ccaddress);
+				}
+			}
+			else{
+				$msg['msgCC'][0] = $this->formatMailObject($info_msg['cc']);
+			}
+		}		
+		if($info_msg['reply_toaddress'] != null) {
+			$msg['msgReplyTo'][0] = $this->formatMailObject($info_msg['reply_toaddress']);
+		}						
+		$msg['msgSubject']  = ($info_msg['subject'] ? mb_convert_encoding($info_msg['subject'],"UTF8", "ISO_8859-1") : "");		
+		$msg['msgHasAttachments'] = "0";
+		if(count($info_msg['attachments']) > 0) {
+			$msg['msgAttachments'] = array();
+			foreach($info_msg['attachments'] as $i => $attachment){
+				$msg['msgAttachments'][] = array (
+					'attachmentID'			=> "".$attachment['pid'],
+					'attachmentIndex'		=> "".$i,
+					'attachmentName' 		=> $attachment['name'],
+					'attachmentSize'		=> "".$attachment['fsize'],
+					'attachmentEncoding'	=> $attachment['encoding']
+				);
+			}
+			$msg['msgHasAttachments'] = "1";
+		}
+		$msg['msgFlagged'] 	= $info_msg['Flagged'] == "F" ? "1" : "0";
+		$msg['msgForwarded']= $info_msg['Forwarded'] == "F" ? "1" : "0";
+		$msg['msgAnswered'] = $info_msg['Answered'] == "A" ? "1" : "0";
+		$msg['msgDraft']	= $info_msg['Draft'] == "X" ? "1" : "0";
+		$msg['msgSeen'] 	= $info_msg['Unseen'] == "U" ? "0" : "1";				
+		$msg['msgSize'] 	= $info_msg['Size'];
+		$msg['msgBody']		= ($info_msg['body'] ? mb_convert_encoding($info_msg['body'],"UTF8", "ISO_8859-1") : "");		
+		
+		return $msg;		
+	}
+		
+}
Index: /branches/2.4/prototype/library/utils/Errors.php
===================================================================
--- /branches/2.4/prototype/library/utils/Errors.php	(revision 7443)
+++ /branches/2.4/prototype/library/utils/Errors.php	(revision 7443)
@@ -0,0 +1,50 @@
+<?php
+
+final class Errors {
+		
+	private static $sInstance;
+	private $errors;
+	
+	public static function getInstance(){
+		if (!self::$sInstance) {
+			self::$sInstance = new Errors();
+		}
+		return self::$sInstance;
+	}
+	
+	function __construct(){
+		$this->errors = array();
+		if($handle = fopen(__DIR__."/../../config/Errors.tsv", "r")){	
+			while (!feof($handle)) {
+				$line = trim(fgets($handle,1024));
+				if($line == null || $line[0] == "#")
+					continue;
+				$error = preg_split("/[\t]+/", $line);
+				if(is_array($error)&& count($error) == 3) {
+					$this->errors[] = array("code" => $error[0], "key" => $error[1], "message" => $error[2]);
+				}
+			}
+		}	
+	}
+	
+	static public function runException($needle, $argument = false){		
+		$error = false;
+		$type = (is_int($needle) ? "code" : "key");
+		foreach( Errors::getInstance()->errors as $value ){
+			if($value[$type] == $needle){
+				$error = $value;
+				break;
+			}
+		}
+		
+		if($error['message'] && $argument){
+			$error['message'] = str_replace("%1", $argument, $error['message']);
+		}		
+		if(!$error){
+			Errors::getInstance()->runException("E_UNKNOWN_ERROR");
+		}		
+		
+		throw new ResponseException($error['message'], $error['code']);		 
+	}	
+		
+}
