/**
  * show temporary image
  *
  * @param  string  $tempImageId
  */
 public function showTempImage($tempImageId)
 {
     //$this->checkAuth();
     // close session to allow other requests
     Expressomail_Session::getSessionNamespace()->lock();
     $clientETag = null;
     $ifModifiedSince = null;
     if (isset($_SERVER['If_None_Match'])) {
         $clientETag = trim($_SERVER['If_None_Match'], '"');
         $ifModifiedSince = trim($_SERVER['If_Modified_Since'], '"');
     } elseif (isset($_SERVER['HTTP_IF_NONE_MATCH']) && isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
         $clientETag = trim($_SERVER['HTTP_IF_NONE_MATCH'], '"');
         $ifModifiedSince = trim($_SERVER['HTTP_IF_MODIFIED_SINCE'], '"');
     }
     // todo: change to use PECL FileInfo library
     $contentType = mime_content_type(Tinebase_Core::getTempDir() . '/' . $tempImageId);
     $image = file_get_contents(Tinebase_Core::getTempDir() . '/' . $tempImageId);
     $serverETag = sha1($fileData);
     // cache for 3600 seconds
     $maxAge = 3600;
     header('Cache-Control: private, max-age=' . $maxAge);
     header("Expires: " . gmdate('D, d M Y H:i:s', Tinebase_DateTime::now()->addSecond($maxAge)->getTimestamp()) . " GMT");
     // overwrite Pragma header from session
     header("Pragma: cache");
     // if the cache id is still valid
     if ($clientETag == $serverETag) {
         header("Last-Modified: " . $ifModifiedSince);
         header("HTTP/1.0 304 Not Modified");
         header('Content-Length: 0');
     } else {
         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
         header('Content-Type: ' . $contentType);
         header("Content-Disposition: inline");
         header('Etag: "' . $serverETag . '"');
         flush();
         die($image);
     }
 }
 /**
  * set from in mail to be sent
  *
  * @param Expressomail_mail $_mail
  * @param Expressomail_Model_Account $_account
  * @param Expressomail_Model_Message $_message
  */
 protected function _setMailFrom(Zend_Mail $_mail, Expressomail_Model_Account $_account, Expressomail_Model_Message $_message = NULL)
 {
     $_mail->clearFrom();
     $from = isset($_account->from) && !empty($_account->from) ? $_account->from : Tinebase_Core::getUser()->accountFullName;
     isset($_message->from_name) ? $from = $_message->from_name : ($from = $from);
     $user = Tinebase_Core::getUser();
     try {
         $allowedEmails = Expressomail_Session::getSessionNamespace()->allowedEmails[$user->accountId];
     } catch (Zend_Session_Exception $zse) {
         Tinebase_Core::getLogger()->warn(__METHOD__ . "::" . __LINE__ . ":: It was not possible to get Expressomail Session Namespace");
         $allowedEmails = array($user->accountEmailAddress);
     }
     $email = $_message !== NULL && !empty($_message->from_email) ? $_message->from_email : $_account->email;
     if (array_search($email, $allowedEmails) === FALSE) {
         throw new Tinebase_Exception_Record_NotAllowed('You Can\'t send a email with this FROM address: ' . $email);
         Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . 'User with id: ' . $user->accountId . 'tried to send email with address not allowed:  ' . $email);
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Set from for mail: ' . $email . ' / ' . $from);
     }
     $_mail->setFrom($email, $from);
 }
 /**
  * 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;
     }
 }
 /**
  * get imap server capabilities and save delimiter / personal namespace in account
  *
  * @param Expressomail_Model_Account $_account
  * @return array capabilities
  */
 public function updateCapabilities(Expressomail_Model_Account $_account, Expressomail_Backend_ImapProxy $_imapBackend = NULL)
 {
     $expressomailSession = Expressomail_Session::getSessionNamespace();
     if (isset($expressomailSession->account) && is_array($expressomailSession->account) && array_key_exists($_account->getId(), $expressomailSession->account)) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Getting capabilities of account ' . $_account->name . ' from SESSION.');
         }
         return $expressomailSession->account[$_account->getId()];
     }
     $imapBackend = $_imapBackend !== NULL ? $_imapBackend : $this->_getIMAPBackend($_account, TRUE);
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Getting capabilities of account ' . $_account->name);
     }
     // get imap server capabilities and save delimiter / personal namespace in account
     $capabilities = $imapBackend->getCapabilityAndNamespace();
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($capabilities, TRUE));
     }
     $this->updateNamespacesAndDelimiter($_account, $capabilities);
     // check if server has 'CHILDREN' support
     $_account->has_children_support = in_array('CHILDREN', $capabilities['capabilities']) ? 1 : 0;
     try {
         if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
             Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Updating capabilities for account: ' . $_account->name);
         }
         $this->_backend->update($_account);
     } catch (Zend_Db_Statement_Exception $zdse) {
         Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Could not update account: ' . $zdse->getMessage());
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $zdse->getTraceAsString());
         }
     }
     // save capabilities in SESSION
     $expressomailSession->account[$_account->getId()] = $capabilities;
     return $capabilities;
 }
 /**
  * test reset account capabilities
  */
 public function testResetAccountCapabilities()
 {
     $capabilities = $this->_controller->updateCapabilities($this->_account);
     $account = clone $this->_account;
     $account->host = 'unittest.org';
     $account->type = Expressomail_Model_Account::TYPE_USER;
     $this->_controller->update($account);
     $this->assertFalse(array_key_exists($this->_account->getId(), Expressomail_Session::getSessionNamespace()->account), print_r(Expressomail_Session::getSessionNamespace()->account, TRUE));
 }
 /**
  * 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;
 }