/**
  * the singleton pattern
  *
  * @return Expressomail_Controller_Account
  */
 public static function getInstance()
 {
     if (self::$_instance === NULL) {
         self::$_instance = new Expressomail_Controller_Account();
     }
     return self::$_instance;
 }
 /**
  * factory function to return a selected account/imap backend class
  *
  * @param   string|Expressomail_Model_Account $_accountId
  * @return  Expressomail_Backend_ImapProxy
  * @throws  Expressomail_Exception_IMAPInvalidCredentials
  */
 public static function factory($_accountId, $_readOnly = FALSE)
 {
     $accountId = $_accountId instanceof Expressomail_Model_Account ? $_accountId->getId() : $_accountId;
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Getting IMAP backend for account id ' . $accountId);
     }
     if (!isset(self::$_backends[$accountId])) {
         // get imap config from account
         $account = $_accountId instanceof Expressomail_Model_Account ? $_accountId : Expressomail_Controller_Account::getInstance()->get($_accountId);
         $imapConfig = $account->getImapConfig();
         // we need to instantiate a new imap backend
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Connecting to server ' . $imapConfig['host'] . ':' . $imapConfig['port'] . ' (' . (array_key_exists('ssl', $imapConfig) ? $imapConfig['ssl'] : 'none') . ')' . ' with username ' . $imapConfig['user']);
         }
         try {
             self::$_backends[$accountId] = new Expressomail_Backend_ImapProxy($imapConfig, $_readOnly);
             if (Tinebase_Core::get(Tinebase_Core::SERVER_CLASS_NAME) !== 'ActiveSync_Server_Http') {
                 Expressomail_Controller_Account::getInstance()->updateCapabilities($account, self::$_backends[$accountId]);
             }
         } catch (Expressomail_Exception_IMAPInvalidCredentials $feiic) {
             // add account and username to Expressomail_Exception_IMAPInvalidCredentials
             $feiic->setAccount($account)->setUsername($imapConfig['user']);
             throw $feiic;
         }
     }
     return self::$_backends[$accountId];
 }
 /**
  * factory function to return a selected account/imap backend class
  *
  * @param   string|Expressomail_Model_Account $_accountId
  * @return  Expressomail_Backend_Sieve
  */
 public static function factory($_accountId)
 {
     $accountId = $_accountId instanceof Expressomail_Model_Account ? $_accountId->getId() : $_accountId;
     if (!isset(self::$_backends[$accountId])) {
         $account = $_accountId instanceof Expressomail_Model_Account ? $_accountId : Expressomail_Controller_Account::getInstance()->get($accountId);
         // get imap config from account to connect with sieve server
         $sieveConfig = $account->getSieveConfig();
         // we need to instantiate a new sieve backend
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Connecting to server ' . $sieveConfig['host'] . ':' . $sieveConfig['port'] . ' (secure: ' . (array_key_exists('ssl', $sieveConfig) && $sieveConfig['ssl'] !== FALSE ? $sieveConfig['ssl'] : 'none') . ') with user ' . $sieveConfig['username']);
         }
         $expressomailConfig = Expressomail_Config::getInstance();
         $sieveBackendDefinition = $expressomailConfig->getDefinition(Expressomail_Config::SIEVEBACKEND);
         $backendClassName = self::$_availableBackends[$sieveBackendDefinition['default']];
         $expressomailSettings = $expressomailConfig->get(Expressomail_Config::EXPRESSOMAIL_SETTINGS);
         $backendName = isset($expressomailSettings[Expressomail_Config::SIEVEBACKEND]) ? $expressomailSettings[Expressomail_Config::SIEVEBACKEND] : $sieveBackendDefinition['default'];
         if ($sieveBackendName != $sieveBackendDefinition['default']) {
             if (Tinebase_Helper::checkClassExistence(self::$_availableBackends[$backendName], true)) {
                 $backendClassName = self::$_availableBackends[$backendName];
             }
         }
         self::$_backends[$accountId] = new $backendClassName($sieveConfig);
     }
     return self::$_backends[$accountId];
 }
 /**
  * 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(''));
 }
 /**
  * event handler function
  * 
  * all events get routed through this function
  *
  * @param Tinebase_Event_Abstract $_eventObject the eventObject
  */
 protected function _handleEvent(Tinebase_Event_Abstract $_eventObject)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . ' (' . __LINE__ . ') handle event of type ' . get_class($_eventObject));
     }
     switch (get_class($_eventObject)) {
         case 'Tinebase_Event_User_ChangeCredentialCache':
             Expressomail_Controller_Account::getInstance()->updateCredentialsOfAllUserAccounts($_eventObject->oldCredentialCache);
             break;
     }
 }
 /**
  * factory function to return a selected account/imap backend class
  *
  * @param   string|Expressomail_Model_Account $_accountId
  * @return  Expressomail_Backend_Sieve
  */
 public static function factory($_accountId)
 {
     $accountId = $_accountId instanceof Expressomail_Model_Account ? $_accountId->getId() : $_accountId;
     if (!isset(self::$_backends[$accountId])) {
         $account = $_accountId instanceof Expressomail_Model_Account ? $_accountId : Expressomail_Controller_Account::getInstance()->get($accountId);
         // get imap config from account to connect with sieve server
         $sieveConfig = $account->getSieveConfig();
         // we need to instantiate a new sieve backend
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Connecting to server ' . $sieveConfig['host'] . ':' . $sieveConfig['port'] . ' (secure: ' . (array_key_exists('ssl', $sieveConfig) && $sieveConfig['ssl'] !== FALSE ? $sieveConfig['ssl'] : 'none') . ') with user ' . $sieveConfig['username']);
         }
         self::$_backends[$accountId] = new Expressomail_Backend_Sieve($sieveConfig);
     }
     return self::$_backends[$accountId];
 }
 /**
  * Sets up the fixture.
  * This method is called before a test is executed.
  *
  * @access protected
  */
 protected function setUp()
 {
     // get (or create) test accout
     $this->_account = Expressomail_Controller_Account::getInstance()->search()->getFirstRecord();
     // init controller and imap backend
     $this->_controller = Felamimail_Controller_Cache_Message::getInstance();
     $this->_imap = Expressomail_Backend_ImapFactory::factory($this->_account);
     try {
         $this->_imap->createFolder($this->_testFolderName, '', $this->_account->delimiter);
     } catch (Zend_Mail_Storage_Exception $zmse) {
         // exists
     }
     $this->_imap->selectFolder($this->_testFolderName);
     // init folder cache and get INBOX
     //Expressomail_Controller_Cache_Folder::getInstance()->update($this->_account->getId());
     $this->_folder = $this->_getFolder($this->_testFolderName);
     $this->_emailTestClass = new Expressomail_Controller_MessageTest();
     $this->_emailTestClass->setup();
 }
 /**
  * send Zend_Mail message via smtp
  *
  * @param  mixed      $accountId
  * @param  Zend_Mail  $mail
  * @param  boolean    $saveInSent
  * @param  Expressomail_Model_Message $originalMessage
  * @return Zend_Mail
  */
 public function sendZendMail($accountId, Zend_Mail $mail, $saveInSent = false, $originalMessage = NULL)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Sending message with subject ' . $mail->getSubject());
     }
     if ($originalMessage !== NULL) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Original Message subject: ' . $originalMessage->subject . ' / Flag to set: ' . var_export($originalMessage->flags, TRUE));
         }
         // this is required for adding the reply/forward flag in _sendMailViaTransport()
         $originalMessage->original_id = $originalMessage;
     }
     // increase execution time (sending message with attachments can take a long time)
     $oldMaxExcecutionTime = Tinebase_Core::setExecutionLifeTime(300);
     // 5 minutes
     // get account
     $account = $accountId instanceof Expressomail_Model_Account ? $accountId : Expressomail_Controller_Account::getInstance()->get($accountId);
     $this->_setMailFrom($mail, $account);
     $this->_setMailHeaders($mail, $account);
     $this->_sendMailViaTransport($mail, $account, $originalMessage, $saveInSent);
     // reset max execution time to old value
     Tinebase_Core::setExecutionLifeTime($oldMaxExcecutionTime);
     return $mail;
 }
 /**
  * get all folders for ActiveSync
  *
  * @param string|Expressomail_Model_Account $_account
  * @return array
  */
 public function getFoldersAS($_account)
 {
     $account = $_account instanceof Expressomail_Model_Account ? $_account : Expressomail_Controller_Account::getInstance()->get($_account);
     return $this->_backend->getAllFoldersAS($account);
 }
 /**
  * set and get vacation sieve script
  * 
  * @see 0007768: Sieve - Vacation notify frequency not being set (Cyrus)
  */
 public function testGetSetVacation()
 {
     $vacationData = $this->_getVacationData();
     $this->_sieveTestHelper($vacationData);
     // check if script was activated
     $activeScriptName = Expressomail_Controller_Sieve::getInstance()->getActiveScriptName($this->_account->getId());
     $this->assertEquals($this->_testSieveScriptName, $activeScriptName);
     $updatedAccount = Expressomail_Controller_Account::getInstance()->get($this->_account->getId());
     $this->assertTrue((bool) $updatedAccount->sieve_vacation_active);
     $result = $this->_json->getVacation($this->_account->getId());
     $this->assertEquals($this->_account->email, $result['addresses'][0]);
     $sieveBackend = Expressomail_Backend_SieveFactory::factory($this->_account->getId());
     if (preg_match('/dbmail/i', $sieveBackend->getImplementation())) {
         $translate = Tinebase_Translation::getTranslation('Felamimail');
         $vacationData['subject'] = sprintf($translate->_('Out of Office reply from %1$s'), Tinebase_Core::getUser()->accountFullName);
     }
     foreach (array('reason', 'enabled', 'subject', 'days') as $field) {
         $this->assertEquals($vacationData[$field], $result[$field], 'vacation data mismatch: ' . $field);
     }
 }
 /**
  * get expressomail account
  *
  * @return Expressomail_Model_Account|NULL
  */
 protected function _getAccount()
 {
     if ($this->_account === NULL) {
         $defaultAccountId = Tinebase_Core::getPreference('Expressomail')->{Expressomail_Preference::DEFAULTACCOUNT};
         if (empty($defaultAccountId)) {
             if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                 Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " no default account set. Can't sync any folders.");
             }
             return NULL;
         }
         try {
             $this->_account = Expressomail_Controller_Account::getInstance()->get($defaultAccountId);
         } catch (Tinebase_Exception_NotFound $ten) {
             return NULL;
         }
     }
     return $this->_account;
 }
 /**
  * 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 ids of all inboxes for accounts of current user
  *
  * @return array
  */
 public function getAllInboxes()
 {
     $return = array();
     $accounts = Expressomail_Controller_Account::getInstance()->search();
     //        $folderFilter = new Expressomail_Model_FolderFilter(array(
     //            array('field' => 'account_id', 'operator' => 'in', 'value' => $accounts->getArrayOfIds()),
     //            array('field' => 'globalname', 'operator' => 'equals', 'value' => 'INBOX')
     //        ));
     //        $folderIds = Expressomail_Controller_Folder::getInstance()->search($folderFilter, NULL, TRUE);
     foreach ($accounts as $account) {
         // Should be true to every imap server
         $return[] = '/' . $account->id . '/' . $this->encodeFolderUid('INBOX', $account->id);
     }
     //        //get array of /account_id/id
     //        for ($it = $folderIds->getIterator(), $it->rewind(); $it->valid(); $it->next())
     //        {
     //            $folder = $it->current();
     //            $return[] = self::IMAPDELIMITER.$folder->account_id.self::IMAPDELIMITER.$folder->id;
     //        }
     return $return;
 }
 /**
  * get folder ids of all inboxes for accounts of current user
  *
  * @return array
  */
 protected function _getFolderIdsOfAllInboxes()
 {
     $accounts = Expressomail_Controller_Account::getInstance()->search();
     $folderFilter = new Expressomail_Model_FolderFilter(array(array('field' => 'account_id', 'operator' => 'in', 'value' => $accounts->getArrayOfIds()), array('field' => 'localname', 'operator' => 'equals', 'value' => 'INBOX')));
     $folderBackend = new Expressomail_Backend_Folder();
     $folderIds = $folderBackend->search($folderFilter, NULL, TRUE);
     return $folderIds;
 }
 /**
  * check the rules
  * 
  * @param Expressomail_Model_Sieve_Rule $_rule
  * @param string|Expressomail_Model_Account $_accountId
  * @throws Expressomail_Exception_Sieve
  */
 protected function _checkRule($_rule, $_accountId)
 {
     $account = $_accountId instanceof Expressomail_Model_Account ? $_accountId : Expressomail_Controller_Account::getInstance()->get($_accountId);
     if ($_rule->action_type === Expressomail_Sieve_Rule_Action::REDIRECT && $_rule->enabled) {
         if ($account->email === $_rule->action_argument) {
             throw new Expressomail_Exception_Sieve('It is not allowed to redirect emails to self (' . $account->email . ')! Please change the recipient.');
         }
         $domains = $this->getAllowedSieveRedirectDomains();
         if ($domains) {
             $domain = substr($_rule->action_argument, strpos($_rule->action_argument, '@') + 1);
             $domains = str_replace(' ', '', $domains);
             $domains = str_replace('.', '\\.', $domains);
             $domains = str_replace(',', '|', $domains);
             if (preg_match('/' . $domains . '/', $domain) != 1) {
                 throw new Expressomail_Exception_Sieve('It is not allowed to redirect to this domain  ' . $_rule->action_argument);
             }
         }
     }
 }
 /**
  * get message content (body, headers and attachments)
  *
  * @param Expressomail_Model_Message $_message
  * @param Expressomail_Model_Account $_account
  * @param string $_partId
  */
 protected function _getCompleteMessageContent(Expressomail_Model_Message $_message, Expressomail_Model_Account $_account, $_partId = NULL)
 {
     $mimeType = $_account->display_format == Expressomail_Model_Account::DISPLAY_HTML || $_account->display_format == Expressomail_Model_Account::DISPLAY_CONTENT_TYPE ? Zend_Mime::TYPE_HTML : Zend_Mime::TYPE_TEXT;
     $headers = $this->getMessageHeaders($_message, $_partId, true);
     $attachments = $this->getAttachments($_message, $_partId);
     $this->_attachments = $attachments;
     $body = $this->getMessageBody($_message, $_partId, $mimeType, $_account, true);
     $signature = $this->getDigitalSignature($_message, $_partId);
     if ($signature['ret_type'] == 'cipher') {
         $smimeEml = $signature['content'];
         unset($signature);
     } else {
         $smimeEml = '';
     }
     if ($_partId === null) {
         $message = $_message;
         $message->body = $body;
         $message->headers = $headers;
         $message->attachments = $attachments;
         // make sure the structure is present
         $message->structure = $message->structure;
         $message->signature_info = $signature;
         $message->smimeEml = $smimeEml;
     } else {
         // create new object for rfc822 message
         $structure = $_message->getPartStructure($_partId, FALSE);
         $message = new Expressomail_Model_Message(array('messageuid' => $_message->messageuid, 'folder_id' => $_message->folder_id, 'received' => $_message->received, 'size' => array_key_exists('size', $structure) ? $structure['size'] : 0, 'partid' => $_partId, 'body' => $body, 'headers' => $headers, 'attachments' => $attachments, 'signature_info' => $signature, 'smimeEml' => $smimeEml, 'structure' => $structure));
         $message->parseHeaders($headers);
         $message->parseSmime($message->structure);
         $structure = array_key_exists('messageStructure', $structure) ? $structure['messageStructure'] : $structure;
         $message->parseStructure($structure);
     }
     if (!$_partId) {
         $message->sendReadingConfirmation();
     }
     if (isset($message['signature_info']) && $message['signature_info']) {
         if ($message['signature_info']['ret_type'] == 'signature') {
             $signature['smime'] = Expressomail_Smime::TYPE_ENVELOPED_DATA_VALUE;
             $extract1_headers = 'application/pkcs7';
             $extract1a_headers = 'name="smime.p7m"';
             $extract1b_headers = 'MIME-Version: 1.0';
             $extract2_headers = $message['headers']['content-disposition'];
             $extract3_headers = $message['headers']['content-transfer-encoding'];
             $imapBackend = $this->_getBackendAndSelectFolder($_message->folder_id);
             $contentHeaders = preg_replace("/(?<!\\r)\\n/", "\r\n", $imapBackend->getRawContent($_message->messageuid, 'HEADER'));
             $header_lines = explode(chr(0xd) . chr(0xa), $contentHeaders);
             $newHeaders = '';
             foreach ($header_lines as $line) {
                 if (strpos($line, $extract1_headers) === false && strpos($line, $extract1a_headers) === false && strpos($line, $extract1b_headers) === false && strpos($line, $extract2_headers) === false && strpos($line, $extract3_headers) === false) {
                     $newHeaders = $newHeaders . $line . chr(0xd) . chr(0xa);
                 }
             }
             $newHeaders = substr($newHeaders, 0, -4) . 'MIME-Version: 1.0' . chr(0xd) . chr(0xa);
             $msg = $newHeaders . $message['signature_info']['content'];
             $msg = preg_replace("/(?<!\\r)\\n/", "\r\n", $msg);
             $account = Expressomail_Controller_Account::getInstance()->get($message->account_id);
             $folder = Expressomail_Controller_Folder::getInstance()->getByBackendAndGlobalName($message->account_id, $account['trash_folder']);
             $_messageUid = Expressomail_Controller_Message::getInstance()->appendMessage($folder, $msg);
             $_messageid = Expressomail_Backend_Message::createMessageId($account['id'], $folder['id'], $_messageUid);
             $messageB = Expressomail_Controller_Message::getInstance()->getCompleteMessage($_messageid, Null, false);
             $messageB['signature_info'] = $message['signature_info'];
             return $messageB;
         }
     }
     return $message;
 }
 /**
  * Check folder account
  *
  * @param   string $_usrAccountId
  * @param   string $_folderId
  * @return  bool
  */
 private function _checkFolderAccount($_usrAccountId, $_folderAccount)
 {
     $_expressomailId = Expressomail_Controller_Account::getInstance()->get($_folderAccount);
     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . '- Fetched ACCOUNT for Expressomail account: ' . $_expressomailId);
     if ($_expressomailId->user_id === $_usrAccountId) {
         return true;
     } else {
         return false;
     }
 }
 /**
  * move messages to trash
  * 
  * @param Tinebase_Record_RecordSet $_messagesInFolder
  * @param string $_folderId
  * @return boolean did we move messages?
  */
 protected function _moveMessagesToTrash(Tinebase_Record_RecordSet $_messagesInFolder, $_folderId)
 {
     // messages should be moved to trash -> need to determine the trash folder for the account of the folder that contains the messages
     $targetFolder = Expressomail_Controller_Account::getInstance()->getSystemFolder($_messagesInFolder->getFirstRecord()->account_id, Expressomail_Model_Folder::FOLDER_TRASH);
     if ($_folderId === $targetFolder->id) {
         return FALSE;
     }
     try {
         $this->_moveMessagesInFolderOnSameAccount($_messagesInFolder, $targetFolder);
     } catch (Tinebase_Exception_NotFound $tenf) {
         if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
             Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' No trash folder found - skipping messages in this folder.');
         }
         return FALSE;
     }
     return TRUE;
 }
 /**
  * returns TRUE if account has capability (i.e. QUOTA, CONDSTORE, ...)
  * 
  * @param $_capability
  * @return boolean
  */
 public function hasCapability($_capability)
 {
     $capabilities = Expressomail_Controller_Account::getInstance()->updateCapabilities($this);
     return in_array($_capability, $capabilities['capabilities']);
 }
 /**
  * Compare order of Expressomail_Model_Message acording to Tinebase_Model_Pagination
  * @param Expressomail_Model_Message $msg1
  * @param Expressomail_Model_Message $msg2
  * @return int
  *
  * @todo Convert int security value in Expressomail_Smime to corresponding string type
  */
 public function compare($msg1, $msg2)
 {
     switch ($this->_pagination->sort) {
         case 'received':
             // Integer
             $value1 = $msg1[$this->_pagination->sort];
             $value2 = $msg2[$this->_pagination->sort];
         case 'sent':
             // Integer
             $value1 = isset($value1) ? $value1 : $msg1['header']['date'];
             $value2 = isset($value2) ? $value2 : $msg2['header']['date'];
             $value1 = intval(Expressomail_Message::convertDate($value1)->format("U"));
             $value2 = intval(Expressomail_Message::convertDate($value2)->format("U"));
         case 'size':
             // Integer
             $value1 = isset($value1) ? $value1 : intval($msg1[$this->_pagination->sort]);
             $value2 = isset($value2) ? $value2 : intval($msg2[$this->_pagination->sort]);
             return $this->compareIntegers($value1, $value2);
         case 'folder_id':
             // Strings
             $folders = array();
             $translate = Tinebase_Translation::getTranslation('Expressomail');
             foreach (array($msg1, $msg2) as $msg) {
                 $folder = Expressomail_Backend_Folder::decodeFolderUid($msg[$this->_pagination->sort]);
                 // Optimization! Only create the account object once for every sort operation.
                 $account = array_key_exists($folder['accountId'], $this->_accountMap) ? $this->_accountMap[$folder['accountId']] : ($this->_accountMap[$folder['accountId']] = Expressomail_Controller_Account::getInstance()->get($folder['accountId']));
                 $aux1 = explode('/', $folder['globalName']);
                 $aux2 = '';
                 foreach ($aux1 as $value) {
                     $aux2 .= $translate->_($value) . '/';
                 }
                 $folders[] = $account->name . '/' . substr($aux2, 0, strlen($aux2) - 1);
             }
             list($value1, $value2) = $folders;
             //TODO: Should use a static method implemented on Model_Message or Expressomail_Smime
         //TODO: Should use a static method implemented on Model_Message or Expressomail_Smime
         case 'smime':
             $value1 = isset($value1) ? $value1 : $this->processSmimeValue($msg1['structure']);
             $value2 = isset($value2) ? $value2 : $this->processSmimeValue($msg2['structure']);
         case 'flags':
             // Strings
             if (!isset($value1)) {
                 sort($msg1['flags']);
                 $value1 = implode(',', $msg1['flags']);
             }
             if (!isset($value2)) {
                 sort($msg2['flags']);
                 $value2 = implode(',', $msg2['flags']);
             }
         case 'subject':
             // Strings
             $value1 = isset($value1) ? $value1 : $msg1['header'][$this->_pagination->sort];
             $value2 = isset($value2) ? $value2 : $msg2['header'][$this->_pagination->sort];
         case 'id':
             // Strings
             $value1 = isset($value1) ? $value1 : $msg1[$this->_pagination->sort];
             $value2 = isset($value2) ? $value2 : $msg2[$this->_pagination->sort];
             return $this->compareStrings($value1, $value2);
         case 'sender':
         case 'to':
         case 'from_name':
         case 'from_email':
             // Strings
             list($header, $field) = explode('_', $this->_pagination->sort);
             $field = empty($field) ? 'email' : $field;
             $address1 = Expressomail_Message::convertAddresses($msg1['header'][$header]);
             $address2 = Expressomail_Message::convertAddresses($msg2['header'][$header]);
             return $this->compareStrings(isset($address1[0]) && array_key_exists($field, $address1[0]) ? $address1[0][$field] : '', isset($address2[0]) && array_key_exists($field, $address2[0]) ? $address2[0][$field] : '');
     }
 }
 protected function _getAllFolders()
 {
     $return = array();
     $accounts = Expressomail_Controller_Account::getInstance()->search()->getArrayOfIds();
     $controllerFolder = Expressomail_Controller_Folder::getInstance();
     foreach ($accounts as $account) {
         $return = array_merge($return, $controllerFolder->getFoldersAS($account));
     }
     return $return;
 }
 /**
  * get special options
  *
  * @param string $_value
  * @return array
  */
 protected function _getSpecialOptions($_value)
 {
     $result = array();
     switch ($_value) {
         case self::DEFAULTACCOUNT:
             // get all user accounts
             $accounts = Expressomail_Controller_Account::getInstance()->search();
             foreach ($accounts as $account) {
                 $result[] = array($account->getId(), $account->name);
             }
             break;
         default:
             $result = parent::_getSpecialOptions($_value);
     }
     return $result;
 }
 /**
  * clones the account
  *
  * @return Felamimail_Model_Account
  */
 protected function _cloneAccount()
 {
     $account = clone $this->_account;
     unset($account->id);
     $this->_accountsToDelete[] = $account;
     $account = Expressomail_Controller_Account::getInstance()->create($account);
     return $account;
 }
 /**
  * Sets up the fixture.
  * This method is called before a test is executed.
  *
  * @access protected
  */
 protected function setUp()
 {
     Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
     $this->_controller = Expressomail_Controller_Account::getInstance();
     $this->_account = $this->_controller->search()->getFirstRecord();
 }
 /**
  * Send the reading confirmation in a message who has the correct header and is not seen yet
  *
  * @return void
  */
 public function sendReadingConfirmation()
 {
     if (!is_array($this->headers)) {
         $this->headers = Expressomail_Controller_Message::getInstance()->getMessageHeaders($this->getId(), NULL, TRUE);
     }
     if (array_key_exists('disposition-notification-to', $this->headers) && $this->headers['disposition-notification-to'] && !$this->hasSeenFlag() && !$this->hasReadFlag() && !$this->hasDraftFlag()) {
         $translate = Tinebase_Translation::getTranslation($this->_application);
         $from = Expressomail_Controller_Account::getInstance()->get($this->account_id);
         $arrRet = array();
         preg_match(Tinebase_Mail::EMAIL_ADDRESS_REGEXP, $this->headers['disposition-notification-to'], $arrRet);
         $to = $arrRet[0];
         if ($from->email === $to) {
             return;
         }
         // calculate timezone in "GMT-HH:MM" format
         $dtz = new DateTimeZone(Tinebase_Core::get(Tinebase_Core::USERTIMEZONE));
         $time = new DateTime('now', $dtz);
         $offset = $dtz->getOffset($time);
         $sign = $offset < 0 ? "-" : "+";
         $offset = abs($offset);
         $hours = floor($offset / 3600);
         $hours = $hours < 10 ? '0' . $hours : $hours;
         $minutes = offset % 60;
         $minutes = $minutes < 10 ? '0' . $minutes : $minutes;
         $gmt = '(GMT' . $sign . $hours . ":" . $minutes . ')';
         $subject = $translate->_('Reading Confirmation:') . ' ' . $this->subject;
         $readTime = date('Y-m-d H:i:s');
         $tzReadTime = Tinebase_Translation::dateToStringInTzAndLocaleFormat(Expressomail_Message::convertDate($readTime));
         $tzReceived = Tinebase_Translation::dateToStringInTzAndLocaleFormat(Expressomail_Message::convertDate($this->received));
         $messageBody = $translate->_('Your message:') . ' ' . $this->subject . "\n" . $translate->_('Received on') . ' ' . $tzReceived . ' ' . $gmt . "\n" . $translate->_('Was read by:') . ' ' . $from->from . ' <' . $from->email . '> ' . $translate->_('on') . ' ' . $tzReadTime . ' ' . $gmt;
         //$messageBody         = Expressomail_Message::convertFromTextToHTML($messageBody);
         $readconf = array('to' => $to, 'subject' => $this->subject, 'received' => $this->received, 'from_name' => $from->from, 'from_email' => $from->email, 'read_time' => $readTime);
         $mailPart = new Zend_Mime_Part(serialize($readconf));
         $mailPart->charset = 'UTF-8';
         $mailPart->type = 'text/readconf;';
         $mailPart->encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE;
         $contact = new Addressbook_Model_Contact(array('email' => $to, 'n_fn' => $from->from), true);
         $result = Tinebase_Notification::getInstance()->send(Tinebase_Core::getUser(), array($contact), $subject, $messageBody, $mailPart, NULL);
         Expressomail_Controller_Message_Flags::getInstance()->addFlags($this->getId(), (array) 'Read');
     }
 }
 /**
  * check the rules
  * 
  * @param Expressomail_Model_Sieve_Rule $_rule
  * @param string|Expressomail_Model_Account $_accountId
  * @throws Expressomail_Exception_Sieve
  */
 protected function _checkRule($_rule, $_accountId)
 {
     $account = $_accountId instanceof Expressomail_Model_Account ? $_accountId : Expressomail_Controller_Account::getInstance()->get($_accountId);
     if ($_rule->action_type === Expressomail_Sieve_Rule_Action::REDIRECT && $_rule->enabled) {
         if ($account->email === $_rule->action_argument) {
             throw new Expressomail_Exception_Sieve('It is not allowed to redirect emails to self (' . $account->email . ')! Please change the recipient.');
         }
     }
 }