/**
  * 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 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;
 }
 /**
  *
  * @param type $paths
  * @return type
  */
 protected function _getFoldersInfo($paths)
 {
     $return = array();
     foreach ($paths as $tmp) {
         $tmp = is_array($tmp) ? explode(self::IMAPDELIMITER, $tmp['path']) : explode(self::IMAPDELIMITER, $tmp);
         if (empty($tmp[0])) {
             array_shift($tmp);
         }
         $userId = array_shift($tmp);
         $folderId = array_pop($tmp);
         $folder = Expressomail_Backend_Folder::decodeFolderUid($folderId);
         $return[$folderId] = array($userId, Expressomail_Model_Folder::decodeFolderName($folder['globalName']));
     }
     return $return;
 }