/**
  * Sets up the fixture.
  * This method is called before a test is executed.
  *
  * @access protected
  */
 protected function setUp()
 {
     $this->_account = Expressomail_Controller_Account::getInstance()->search()->getFirstRecord();
     $this->_controller = Expressomail_Controller_Folder::getInstance();
     $this->_imap = Expressomail_Backend_ImapFactory::factory($this->_account);
     // fill folder cache first
     $this->_controller->search($this->_getFolderFilter(''));
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     foreach ($this->_foldersToDelete as $foldername) {
         try {
             Expressomail_Controller_Folder::getInstance()->delete($this->_account->getId(), $foldername);
         } catch (Expressomail_Exception_IMAP $fei) {
             // do nothing
         }
     }
     Tinebase_TransactionManager::getInstance()->rollBack();
 }
 /**
  * update message cache
  *
  * @param string $_folder
  * @param integer $_time in seconds
  * @param integer $_updateFlagFactor 1 = update flags every time, x = update flags roughly each xth run (10 by default)
  * @return Expressomail_Model_Folder folder status (in cache)
  * @throws Expressomail_Exception
  */
 public function updateCache($_folder, $_time = 10, $_updateFlagFactor = 10)
 {
     $folder = Expressomail_Controller_Folder::getInstance()->get($_folder, false);
     return $folder;
 }
 /**
  * get folder
  *
  * @return Felamimail_Model_Folder
  */
 public function getFolder($_folderName = null, $_account = NULL)
 {
     $folderName = $_folderName !== null ? $_folderName : $this->_testFolderName;
     $account = $_account !== NULL ? $_account : $this->_account;
     $filter = new Expressomail_Model_FolderFilter(array(array('field' => 'globalname', 'operator' => 'equals', 'value' => ''), array('field' => 'account_id', 'operator' => 'equals', 'value' => $account->getId())));
     $result = Expressomail_Controller_Folder::getInstance()->search($filter);
     $folder = $result->filter('localname', $folderName)->getFirstRecord();
     if (empty($folder)) {
         $folder = Expressomail_Controller_Folder::getInstance()->create($account, $_folderName);
     }
     return $folder;
 }
 /**
  * move messages from one folder to another folder within the same email account
  * 
  * @param Tinebase_Record_RecordSet $_messages
  * @param Expressomail_Model_Folder $_targetFolder
  */
 protected function _moveMessagesInFolderOnSameAccount(Tinebase_Record_RecordSet $_messages, Expressomail_Model_Folder $_targetFolder)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Move ' . count($_messages) . ' message(s) to ' . $_targetFolder->globalname);
     }
     $firstMessage = $_messages->getFirstRecord();
     $folder = Expressomail_Controller_Folder::getInstance()->get($firstMessage->folder_id);
     $imapBackend = $this->_getBackendAndSelectFolder(NULL, $folder);
     $imapMessageUids = array();
     foreach ($_messages as $message) {
         $imapMessageUids[] = $message->messageuid;
         if (count($imapMessageUids) >= 50) {
             $this->_moveBatchOfMessages($imapMessageUids, $_targetFolder->globalname, $imapBackend);
             $imapMessageUids = array();
         }
     }
     // the rest
     if (count($imapMessageUids) > 0) {
         $this->_moveBatchOfMessages($imapMessageUids, $_targetFolder->globalname, $imapBackend);
     }
 }
 /**
  * create new folders or get existing folders from db and return record set
  *
  * @param array $_folders
  * @param Expressomail_Model_Account $_account
  * @param string $_parentFolder
  * @return Tinebase_Record_RecordSet of Expressomail_Model_Folder
  * 
  * @todo    move delete sync to extra function
  */
 protected function _getOrCreateFolders(array $_folders, $_account, $_parentFolder)
 {
     $parentFolder = $_parentFolder !== NULL ? $_parentFolder : '';
     $result = new Tinebase_Record_RecordSet('Expressomail_Model_Folder');
     $systemFolders = Expressomail_Controller_Folder::getInstance()->getSystemFolders($_account);
     // get configured account standard folders here
     if (strtolower($_account->sent_folder) != $systemFolders[2]) {
         $systemFolders[2] = strtolower($_account->sent_folder);
     }
     if (isset($systemFolders[5]) && strtolower($_account->trash_folder) != $systemFolders[5]) {
         $systemFolders[5] = strtolower($_account->trash_folder);
     }
     //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($systemFolders, TRUE));
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_folders, TRUE));
     }
     // do some mapping and save folder in db (if it doesn't exist
     foreach ($_folders as $folderData) {
         try {
             $folderData['localName'] = Expressomail_Model_Folder::decodeFolderName($folderData['localName']);
             $folderData['globalName'] = Expressomail_Model_Folder::decodeFolderName($folderData['globalName']);
             $folder = Expressomail_Controller_Folder::getInstance()->getByBackendAndGlobalName($_account->getId(), $folderData['globalName']);
             $folder->is_selectable = $folderData['isSelectable'];
             $folder->imap_status = Expressomail_Model_Folder::IMAP_STATUS_OK;
             $folder->has_children = $folderData['hasChildren'] == '1';
             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Update cached folder ' . $folderData['globalName']);
             }
         } catch (Tinebase_Exception_NotFound $tenf) {
             // create new folder
             if (empty($folderData['localName'])) {
                 // skip
                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                     Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Do not add folder ' . $folderData['globalName'] . '. Localname is empty.');
                 }
                 continue;
             } else {
                 $delimiter = strlen($folderData['delimiter']) === 1 ? $folderData['delimiter'] : '';
                 $folder = new Expressomail_Model_Folder(array('localname' => $folderData['localName'], 'globalname' => $folderData['globalName'], 'is_selectable' => $isSelectable, 'has_children' => $folderData['hasChildren'] == '1', 'account_id' => $_account->getId(), 'imap_timestamp' => Tinebase_DateTime::now(), 'imap_status' => Expressomail_Model_Folder::IMAP_STATUS_OK, 'user_id' => Tinebase_Core::getUser()->getId(), 'parent' => $parentFolder, 'system_folder' => in_array(strtolower($folderData['localName']), $systemFolders), 'delimiter' => $delimiter));
                 // update delimiter setting of account
                 if ($folder->delimiter && $folder->delimiter !== $_account->delimiter && $folder->localname === 'INBOX') {
                     $_account->delimiter = $folder->delimiter;
                     $_account = Expressomail_Controller_Account::getInstance()->update($_account);
                 }
                 if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                     Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Adding new folder ' . $folderData['globalName'] . ' to cache.');
                 }
                 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                     Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . print_r($folder->toArray(), true));
                 }
                 $folder = $this->_backend->create($folder);
             }
         }
         $result->addRecord($folder);
     }
     return $result;
 }
 /**
  * save message in folder (target folder can be within a different account)
  *
  * @param string|Expressomail_Model_Folder $_folder globalname or folder record
  * @param Expressomail_Model_Message $_message
  * @return Expressomail_Model_Message
  */
 public function saveMessageInFolder($_folder, $_message)
 {
     $sourceAccount = Expressomail_Controller_Account::getInstance()->get($_message->account_id);
     $folder = $_folder instanceof Expressomail_Model_Folder ? $_folder : Expressomail_Controller_Folder::getInstance()->getByBackendAndGlobalName($_message->account_id, $_folder);
     $targetAccount = $_message->account_id == $folder->account_id ? $sourceAccount : Expressomail_Controller_Account::getInstance()->get($folder->account_id);
     $this->_resolveOriginalMessage($_message);
     $mailToAppend = $this->createMailForSending($_message, $sourceAccount);
     $transport = new Expressomail_Transport();
     $mailAsString = $transport->getRawMessage($mailToAppend, $this->_getAdditionalHeaders($_message));
     $flags = $folder->globalname === $targetAccount->drafts_folder ? array(Zend_Mail_Storage::FLAG_DRAFT) : null;
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Appending message ' . $_message->subject . ' to folder ' . $folder->globalname . ' in account ' . $targetAccount->name);
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $mailAsString);
     }
     try {
         Expressomail_Backend_ImapFactory::factory($targetAccount)->appendMessage($mailAsString, $folder->globalname, $flags);
     } catch (Zend_Mail_Protocol_Exception $e) {
         if ($folder->system_folder) {
             Expressomail_Backend_ImapFactory::factory($targetAccount)->createFolder($folder->localname, $folder->parent);
             Expressomail_Backend_ImapFactory::factory($targetAccount)->appendMessage($mailAsString, $folder->globalname, $flags);
         } else {
             throw $e;
         }
     }
     // update original_id of saved message
     $res = Expressomail_Backend_ImapFactory::factory($targetAccount)->examineFolder($folder->globalname);
     $_messageid = Expressomail_Backend_Message::createMessageId($_message->account_id, $folder->id, $res['uidnext'] - 1);
     $_message->original_id = $_messageid;
     return $_message;
 }
 /**
  * get Syncroton_Model_Folder folders recursively by parentFolder
  *
  * @param Expressomail_Model_Folder $parentFolder
  * @param array $result
  * @return array of Syncroton_Model_Folder
  */
 protected function _getFolders($parentFolder = NULL, &$result = array())
 {
     $globalname = $parentFolder ? $parentFolder->globalname : '';
     $account = $this->_getAccount();
     if (!$account) {
         return array();
     }
     $filter = new Expressomail_Model_FolderFilter(array(array('field' => 'globalname', 'operator' => 'startswith', 'value' => $globalname), array('field' => 'account_id', 'operator' => 'equals', 'value' => $account->getId())));
     try {
         $folders = Expressomail_Controller_Folder::getInstance()->search($filter);
     } catch (Expressomail_Exception_IMAPInvalidCredentials $feiic) {
         Tinebase_Exception::log($feiic, null, array('accountname' => $account->name));
         return array();
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " Found " . count($folders) . ' subfolders of folder "' . $globalname . '"');
     }
     foreach ($folders as $folder) {
         if (!$folder->is_selectable) {
             continue;
         }
         $serverId = md5($folder->getId());
         $result[$serverId] = new Syncroton_Model_Folder(array('serverId' => $serverId, 'parentId' => $parentFolder ? md5($parentFolder->getId()) : 0, 'displayName' => substr($folder->localname, 0, 254), 'type' => $this->_getFolderType($folder), 'bigfolderid' => $folder->getId()));
         if ($folder->has_children) {
             $this->_getFolders($folder, $result);
         }
     }
     return $result;
 }
 /**
  * Gets one entry (by id)
  *
  * @param string $_id
  * @param boolean $_useCache true to get folder from cache
  * @return Tinebase_Record_Interface
  * @throws Tinebase_Exception_NotFound
  * 
  * @todo test to do a getQuota() shoudn't be hardcoded
  * 
  */
 public function get($_id, $_useCache = TRUE)
 {
     $cache = Tinebase_Core::getCache();
     $cacheKey = 'Expressomail_Model_Folder_' . $_id;
     $folderFromCache = $_useCache ? $cache->load($cacheKey) : FALSE;
     if ($folderFromCache) {
         return $folderFromCache;
     }
     $folderDecoded = self::decodeFolderUid($_id);
     if (isset($folderDecoded['accountId'])) {
         $imap = Expressomail_Backend_ImapFactory::factory($folderDecoded['accountId'], TRUE);
         $folder = $imap->getFolders('', $folderDecoded['globalName'], $this->_accounts[$folderDecoded['accountId']]);
         //$status = $imap->examineFolder($folderDecoded['globalName']);
         $status = $imap->getFolderStatus($folderDecoded['globalName']);
         if ($status === FALSE) {
             // we can not access folder, create Model as unselectable
             $globalname = $folderDecoded['globalName'];
             $auxlocalname = explode(self::IMAPDELIMITER, $globalname);
             $localname = array_pop($auxlocalname);
             $translate = Tinebase_Translation::getTranslation("Expressomail");
             $newFolder = new Expressomail_Model_Folder(array('id' => $_id, 'account_id' => Tinebase_Core::getPreference('Expressomail')->{Expressomail_Preference::DEFAULTACCOUNT}, 'localname' => $localname == 'user' ? $translate->_("Shared Folders") : $localname, 'globalname' => $folderDecoded['globalName'], 'parent' => $globalname === 'user' ? '' : substr($globalname, 0, strrpos($globalname, self::IMAPDELIMITER)), 'delimiter' => self::IMAPDELIMITER, 'is_selectable' => 0, 'has_children' => 1, 'system_folder' => 1, 'imap_status' => Expressomail_Model_Folder::IMAP_STATUS_OK, 'imap_timestamp' => Tinebase_DateTime::now(), 'cache_status' => 'complete', 'cache_timestamp' => Tinebase_DateTime::now(), 'cache_job_lowestuid' => 0, 'cache_job_startuid' => 0, 'cache_job_actions_est' => 0, 'cache_job_actions_done' => 0), true);
             $cache->save($newFolder, $cacheKey);
             return $newFolder;
         }
         $globalName = $folderDecoded['globalName'];
         if ($globalName == 'INBOX' || $globalName == 'user') {
             $folder[$folderDecoded['globalName']]['parent'] = '';
         } else {
             $folder[$folderDecoded['globalName']]['parent'] = substr($globalName, 0, strrpos($globalName, self::IMAPDELIMITER));
         }
         /*
          * @todo must see if it is not better do this on the model directly
          */
         $systemFolders = FALSE;
         if (strtolower($globalName) === 'inbox' || strtolower($folder[$folderDecoded['globalName']]['parent']) === 'user') {
             $systemFolders = TRUE;
         } else {
             if (strtolower($folder[$folderDecoded['globalName']]['parent']) === 'inbox' && strtolower($folder[$folderDecoded['globalName']]['localName']) !== 'inbox') {
                 $systemFolders = in_array(strtolower($folder[$folderDecoded['globalName']]['localName']), Expressomail_Controller_Folder::getInstance()->getSystemFolders($folderDecoded['accountId']));
             } else {
                 if (preg_match('/^user\\/[^\\/]+$/i', $folder[$folderDecoded['globalName']]['parent'])) {
                     $systemFolders = in_array(strtolower($folder[$folderDecoded['globalName']]['localName']), Expressomail_Controller_Folder::getInstance()->getSystemFolders($folderDecoded['accountId']));
                 }
             }
         }
         $localName = Expressomail_Model_Folder::decodeFolderName($folder[$folderDecoded['globalName']]['localName']);
         if (preg_match("/^user\\/[0-9]{11}\$/", Expressomail_Model_Folder::decodeFolderName($folder[$folderDecoded['globalName']]['globalName']))) {
             try {
                 $aux = Tinebase_User::getInstance()->getFullUserByLoginName($localName)->toArray();
                 $localName = $aux["accountFullName"];
             } catch (Exception $exc) {
             }
         }
         $expressomailSession = Expressomail_Session::getSessionNamespace();
         $userNameSpace = $imap->getUserNameSpace() . self::IMAPDELIMITER;
         $arrDecodedFolder = explode(self::IMAPDELIMITER, $folderDecoded['globalName']);
         if ($folderDecoded['globalName'] === 'INBOX' || $folderDecoded['globalName'] === 'INBOX' . self::IMAPDELIMITER . 'Arquivo Remoto' || substr($folderDecoded['globalName'], 0, strlen($userNameSpace)) === $userNameSpace && (!isset($arrDecodedFolder[2]) || $arrDecodedFolder[2] === 'Arquivo Remoto')) {
             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Getting quota from IMAP for ' . $folderDecoded['globalName']);
             }
             $quota = $imap->getQuota($folderDecoded['globalName']);
             $expressomailSession->quota[$folderDecoded['globalName']] = $quota;
         } else {
             if ($arrDecodedFolder[0] === 'INBOX' && isset($arrDecodedFolder[1]) && $arrDecodedFolder[1] === 'Arquivo Remoto') {
                 $globalNameFolder = $arrDecodedFolder[0] . self::IMAPDELIMITER . $arrDecodedFolder[1];
             } else {
                 $globalNameFolder = $arrDecodedFolder[0];
             }
             if ($arrDecodedFolder[0] !== 'INBOX') {
                 $globalNameFolder .= isset($arrDecodedFolder[1]) ? self::IMAPDELIMITER . $arrDecodedFolder[1] : '';
             }
             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Getting quota from Session for ' . $folderDecoded['globalName']);
             }
             $quota = isset($expressomailSession->quota[$globalNameFolder]) ? $expressomailSession->quota[$globalNameFolder] : 0;
         }
         $return = new Expressomail_Model_Folder(array('id' => $_id, 'account_id' => $folderDecoded['accountId'], 'localname' => $localName, 'globalname' => Expressomail_Model_Folder::decodeFolderName($folder[$folderDecoded['globalName']]['globalName']), 'parent' => Expressomail_Model_Folder::decodeFolderName($folder[$folderDecoded['globalName']]['parent']), 'delimiter' => $folder[$folderDecoded['globalName']]['delimiter'], 'is_selectable' => $folder[$folderDecoded['globalName']]['isSelectable'], 'has_children' => $folder[$folderDecoded['globalName']]['hasChildren'], 'system_folder' => $systemFolders, 'imap_status' => Expressomail_Model_Folder::IMAP_STATUS_OK, 'imap_uidvalidity' => $status['uidvalidity'], 'imap_totalcount' => array_key_exists('messages', $status) ? $status['messages'] : '', 'imap_timestamp' => Tinebase_DateTime::now(), 'cache_status' => 'complete', 'cache_totalcount' => array_key_exists('messages', $status) ? $status['messages'] : '', 'cache_recentcount' => array_key_exists('recent', $status) ? $status['recent'] : '', 'cache_unreadcount' => array_key_exists('unseen', $status) ? $status['unseen'] : '', 'cache_timestamp' => Tinebase_DateTime::now(), 'cache_job_lowestuid' => 0, 'cache_job_startuid' => 0, 'cache_job_actions_est' => 0, 'cache_job_actions_done' => 0, 'quota_usage' => !empty($quota) ? $quota['STORAGE']['usage'] : 0, 'quota_limit' => !empty($quota) ? $quota['STORAGE']['limit'] : 0), true);
         $cache->save($return, $cacheKey);
         return $return;
     }
 }
 /**
  * create new system folder
  *
  * @param Expressomail_Model_Account $_account
  * @param string $_systemFolder
  * @return Expressomail_Model_Folder
  */
 protected function _createSystemFolder(Expressomail_Model_Account $_account, $_systemFolder)
 {
     Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Folder not found: ' . $_systemFolder . '. Trying to add it.');
     $splitFolderName = Expressomail_Model_Folder::extractLocalnameAndParent($_systemFolder, $_account->delimiter);
     try {
         $result = Expressomail_Controller_Folder::getInstance()->create($_account, $splitFolderName['localname'], $splitFolderName['parent']);
     } catch (Expressomail_Exception_IMAPServiceUnavailable $feisu) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $feisu->getMessage());
         }
         // try again with INBOX as parent because some IMAP servers can not handle namespaces correctly
         $result = Expressomail_Controller_Folder::getInstance()->create($_account, $splitFolderName['localname'], 'INBOX');
     }
     return $result;
 }
 /**
  * get folder
  *
  * @return Felamimail_Model_Folder
  */
 protected function _getFolder($_folderName = null)
 {
     $folderName = $_folderName !== null ? $_folderName : $this->_testFolderName;
     $filter = new Expressomail_Model_FolderFilter(array(array('field' => 'globalname', 'operator' => 'equals', 'value' => ''), array('field' => 'account_id', 'operator' => 'equals', 'value' => $this->_account->getId())));
     $result = Expressomail_Controller_Folder::getInstance()->search($filter);
     $folder = $result->filter('localname', $folderName)->getFirstRecord();
     if (empty($folder)) {
         print_r($result->toArray());
         throw new Exception('folder not found');
     }
     return $folder;
 }
 /**
  * Gets one entry (by id)
  *
  * @param integer|Tinebase_Record_Interface $_id
  * @param $_getDeleted get deleted records
  * @return Tinebase_Record_Interface
  * @throws Tinebase_Exception_NotFound
  */
 public function get($_id, $_getDeleted = FALSE)
 {
     /*
     Tinebase_Core::getLogger()->alert(__METHOD__ . '#####::#####' . __LINE__ . ' Message get = $_id ' . print_r($_id,true));
     Tinebase_Core::getLogger()->alert(__METHOD__ . '#####::#####' . __LINE__ . ' Message get = $_getDeleted' . print_r($_getDeleted,true));
     */
     $retorno = null;
     $decodedIds = self::decodeMessageId($_id);
     if ($decodedIds['accountId']) {
         $uid = $decodedIds['messageUid'];
         $folder = Expressomail_Controller_Folder::getInstance()->get($decodedIds['folderId']);
         $globalname = Expressomail_Backend_Folder::decodeFolderUid($decodedIds['folderId']);
         $accountId = $decodedIds['accountId'];
         $imap = Expressomail_Backend_ImapFactory::factory($accountId);
         $imap->selectFolder($globalname['globalName']);
         // we're getting just one message
         $messages = $imap->getSummary($uid, $uid, TRUE, $folder->getId());
         // $folder->getId() = ugly hack, have to try to find another solution
         if (count($messages) === 0) {
             throw new Tinebase_Exception_NotFound("Message number {$uid} not found!");
         }
         $message = array_shift($messages);
         $retorno = $this->_createModelMessage($message, $folder);
     }
     return $retorno;
 }
 /**
  * Returns registry data of expressomail.
  * 
  * @see Tinebase_Application_Json_Abstract
  *
  * @return mixed array 'variable name' => 'data'
  *        
  * @todo get default account data (host, port, ...) from preferences?
  */
 public function getRegistryData()
 {
     try {
         $accounts = $this->searchAccounts('');
     } catch (Exception $e) {
         Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Could not get accounts: ' . $e->getMessage());
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $e->getTraceAsString());
         }
         $accounts = array('results' => array(), 'totalcount' => 0);
     }
     $supportedFlags = Expressomail_Controller_Message_Flags::getInstance()->getSupportedFlags();
     $extraSenderAccounts = array();
     foreach ($accounts['results'] as $key => $account) {
         try {
             // build a imap backend so the system folder can be created if necessary
             $accountModel = Expressomail_Controller_Account::getInstance()->get($account['id']);
             $accountModel->resolveCredentials(FALSE);
             // force update the user credentials
             $imapConfig = $imapConfig = Tinebase_Config::getInstance()->get(Tinebase_Config::IMAP, new Tinebase_Config_Struct());
             $config = new stdClass();
             $config->{'host'} = $imapConfig->{'host'};
             $config->{'port'} = $imapConfig->{'port'};
             $config->{'ssl'} = $imapConfig->{'ssl'};
             $config->{'user'} = $accountModel->getUsername();
             $config->{'password'} = $accountModel->{'password'};
             $imap = Expressomail_Backend_ImapFactory::factory($account['id']);
             if ($imap->createDefaultImapSystemFoldersIfNecessary($config)) {
                 try {
                     // add the namespace 'INBOX/' to the new folders
                     $capabilities = $imap->getCapabilityAndNamespace();
                     Expressomail_Controller_Account::getInstance()->updateNamespacesAndDelimiter($accountModel, $capabilities);
                     // update account info in backend and session
                     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Updating capabilities for account: ' . $accountModel->name);
                     }
                     Expressomail_Controller_Account::getInstance()->getBackend()->update($accountModel);
                     // save capabilities in SESSION
                     Expressomail_Session::getSessionNamespace()->account[$accountModel->getId()] = $capabilities;
                 } catch (Exception $zdse) {
                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $zdse->getTraceAsString());
                     }
                 }
             }
         } catch (Exception $e) {
             if (Tinebase_Core::isLogLevel(Zend_Log::ERR)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Exception: ' . $e->getMessage());
             }
         }
         try {
             $extraSenderAccounts = Expressomail_Controller_Folder::getInstance()->getUsersWithSendAsAcl($account['id']);
         } catch (Expressomail_Exception_IMAPFolderNotFound $ex) {
             if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                 Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . $ex->getMessage());
             }
             // Ignore this exception here, it happens when INBOX folder is unaccessible.
         } catch (Expressomail_Exception_IMAPServiceUnavailable $ex) {
             // Ignoring this Exception here.
         }
         unset($account['host']);
         unset($account['port']);
         unset($account['ssl']);
         unset($account['smtp_hostname']);
         unset($account['smtp_port']);
         unset($account['smtp_ssl']);
         unset($account['smtp_auth']);
         $accounts['results'][$key] = $account;
     }
     $result = array('extraSenderAccounts' => $extraSenderAccounts, 'accounts' => $accounts, 'supportedFlags' => array('results' => $supportedFlags, 'totalcount' => count($supportedFlags)), 'aspellDicts' => Tinebase_Core::getConfig()->aspellDicts);
     // TODO: get balanceid cookie name from config
     $balanceIdCookieName = 'BALANCEID';
     if (isset($_COOKIE[$balanceIdCookieName])) {
         $result['balanceId'] = array('cookieName' => $balanceIdCookieName, 'cookieValue' => $_COOKIE[$balanceIdCookieName]);
     }
     $result['vacationTemplates'] = $this->getVacationMessageTemplates();
     $config = Tinebase_Core::getConfig();
     $result['useKeyEscrow'] = $config->certificate->active && $config->certificate->useKeyEscrow;
     $config = Expressomail_Controller::getInstance()->getConfigSettings(false);
     // add autoSaveDraftsInterval to client registry
     $result['autoSaveDraftsInterval'] = $config->autoSaveDraftsInterval;
     // add reportPhishingEmail to client registry
     $result['reportPhishingEmail'] = $config->reportPhishingEmail;
     return $result;
 }
 /**
  * get folder
  *
  * @return Expressomail_Model_Folder
  */
 public function getFolder($_folderName = null, $_account = NULL)
 {
     $folderName = $_folderName !== null ? $_folderName : $this->_testFolderName;
     $account = $_account !== NULL ? $_account : $this->_account;
     if ($_folderName == 'INBOX') {
         $filter = new Expressomail_Model_FolderFilter(array(array('field' => 'globalname', 'operator' => 'equals', 'value' => ''), array('field' => 'account_id', 'operator' => 'equals', 'value' => $account->getId())));
     } else {
         $filter = new Expressomail_Model_FolderFilter(array(array('field' => 'globalname', 'operator' => 'startswith', 'value' => 'INBOX'), array('field' => 'account_id', 'operator' => 'equals', 'value' => $account->getId())));
     }
     $result = Expressomail_Controller_Folder::getInstance()->search($filter);
     $folder = $result->filter(strpos($_folderName, '/') === FALSE ? 'localname' : 'globalname', $folderName)->getFirstRecord();
     if (empty($folder)) {
         $_folderName = strpos($_folderName, 'INBOX/') == 0 ? substr($_folderName, 5) : $_folderName;
         $folder = Expressomail_Controller_Folder::getInstance()->create($account, $_folderName, 'INBOX');
     }
     return $folder;
 }
 /**
  * get mailbox
  *
  * @param string $name
  * @param boolean $createFolder
  * @return Felamimail_Model_Folder|NULL
  */
 protected function _getFolder($name, $createFolder = TRUE)
 {
     //      Expressomail_Controller_Cache_Folder::getInstance()->update($this->_account->getId());
     try {
         $folder = Expressomail_Controller_Folder::getInstance()->getByBackendAndGlobalName($this->_account->getId(), $name);
     } catch (Tinebase_Exception_NotFound $tenf) {
         $folder = $createFolder ? Expressomail_Controller_Folder::getInstance()->create($this->_account, $name) : NULL;
     }
     return $folder;
 }
 /**
  * Check folder
  *
  * @param   string $_usrAccountId;
  * @param   string $_folderId;
  * @return  string $_globalName;
  * @throws  Tinebase_Exception;
  *
  */
 private function _inspectFolderBeforeSchedule($_usrAccountId, $_folderId)
 {
     $_folder = Expressomail_Controller_Folder::getInstance()->get($_folderId);
     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' - Fetched FOLDER core object: ' . print_r($_folder, true));
     if ($_folder) {
         $_globalName = $_folder->globalname;
         if ($this->_isSharedFolder($_globalName) !== false) {
             throw new Tinebase_Exception("Export schedule is not allowed on shared folders!");
         }
         $_accountId = $_folder->account_id;
         $_checkAccount = $this->_checkFolderAccount($_usrAccountId, $_accountId);
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . '- Fetched mail directory global name for mail dir scheduler: ' . $_globalName);
         if ($_checkAccount) {
             return $_globalName;
         } else {
             Tinebase_Core::getLogger()->error(__METHOD__ . '::' . __LINE__ . ' - Tine user account is different from Expressomail account!');
             throw new Tinebase_Exception("Detected account inconsistence on request operation!");
         }
     } else {
         Tinebase_Core::getLogger()->error(__METHOD__ . '::' . __LINE__ . ' - Fetched mail directory for mail dir scheduler does not exist or is invalid: ' . print_r($_folder, true));
         throw new Tinebase_Exception("Specified folder does not exist at mail system!");
     }
 }