/**
  * A draft can be loaded from the database if an id was supplied
  * or filled with dummy data if no id was supplied. If no id was supplied,
  * the user wants to create a new email. In this case, the id defaults to
  * -1. If the user requests to save the draft later on, the id will be updated
  * to the value of the auto_increment field of the table.
  * Along with an id the application will need a folder_id so it can tell whether
  * an existing view has to be updated if this draft was edited and the folder
  * is currently visible.
  * Note, that getDraft will also be executed when the user wants to reply to
  * an email or forward an email. in this case, the id defaults to the email to
  * which the user wants to forward/ reply to.
  *
  * The method awaits 4 POST parameters:
  * id - the original message to reply to OR the id of the draft that is being
  * edited
  * type - the context the draft is in: can be either "new", "forward",
  *        "reply", "reply_all" or "edit"
  * name:    the name of an recipient to send this email to
  * address: the address of an recipient to send this email to. If that value is not
  *          empty. id will be set to -1 and type will be set to new. If address equals
  *          to name or if name is left empty, only the address will be used to send the
  *          email to. Address is given presedence in any case
  */
 public function getDraftAction()
 {
     if ($this->_helper->conjoonContext()->getCurrentContext() != self::CONTEXT_JSON) {
         /**
          * see Conjoon_Controller_Action_InvalidContextException
          */
         require_once 'Conjoon/Controller/Action/InvalidContextException.php';
         throw new Conjoon_Controller_Action_InvalidContextException("Invalid context for action, expected \"" . self::CONTEXT_JSON . "\", got \"" . $this->_helper->conjoonContext()->getCurrentContext() . "\"");
     }
     $path = $_POST['path'];
     // check if folder is remote folder
     /**
      * @see Conjoon_Text_Parser_Mail_MailboxFolderPathJsonParser
      */
     require_once 'Conjoon/Text/Parser/Mail/MailboxFolderPathJsonParser.php';
     $parser = new Conjoon_Text_Parser_Mail_MailboxFolderPathJsonParser();
     $pathInfo = $parser->parse($path);
     /**
      * @see Conjoon_Modules_Groupware_Email_Folder_Facade
      */
     require_once 'Conjoon/Modules/Groupware/Email/Folder/Facade.php';
     $facade = Conjoon_Modules_Groupware_Email_Folder_Facade::getInstance();
     if (!empty($pathInfo) && $facade->isRemoteFolder($pathInfo['rootId'])) {
         return $this->getDraftFromRemoteServer($_POST['id'], $path, $_POST['type']);
     }
     /**
      * @see Conjoon_Keys
      */
     require_once 'Conjoon/Keys.php';
     /**
      * @see Conjoon_BeanContext_Inspector
      */
     require_once 'Conjoon/BeanContext/Inspector.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Draft_Filter_DraftResponse
      */
     require_once 'Conjoon/Modules/Groupware/Email/Draft/Filter/DraftResponse.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Account_Model_Account
      */
     require_once 'Conjoon/Modules/Groupware/Email/Account/Model/Account.php';
     /**
      * @see Conjoon_Util_Array
      */
     require_once 'Conjoon/Util/Array.php';
     $auth = Zend_Registry::get(Conjoon_Keys::REGISTRY_AUTH_OBJECT);
     $userId = $auth->getIdentity()->getId();
     $id = (int) $_POST['id'];
     $type = (string) $_POST['type'];
     $accountModel = new Conjoon_Modules_Groupware_Email_Account_Model_Account();
     // create a new draft so that the user is able to write an email from scratch!
     if ($id <= 0) {
         /**
          * @see Conjoon_Modules_Groupware_Email_Draft
          */
         require_once 'Conjoon/Modules/Groupware/Email/Draft.php';
         $standardId = $accountModel->getStandardAccountIdForUser($userId);
         if ($standardId == 0) {
             $this->view->error = $this->getErrorDto('Error while opening draft', 'Please configure an email account first.', Conjoon_Error::LEVEL_ERROR);
             $this->view->draft = null;
             $this->view->success = false;
             return;
         }
         $post = $_POST;
         Conjoon_Util_Array::apply($post, array('groupwareEmailAccountsId' => $standardId, 'groupwareEmailFoldersId' => -1));
         $draftFilter = new Conjoon_Modules_Groupware_Email_Draft_Filter_DraftResponse($post, Conjoon_Modules_Groupware_Email_Draft_Filter_DraftResponse::CONTEXT_NEW);
         $data = $draftFilter->getProcessedData();
         $draft = Conjoon_BeanContext_Inspector::create('Conjoon_Modules_Groupware_Email_Draft', $data);
         $this->view->success = true;
         $this->view->error = null;
         $this->view->draft = $draft->getDto();
         $this->view->type = $type;
         return;
     }
     // load an email to edit, to reply or to forward it
     /**
      * @see Conjoon_Modules_Groupware_Email_Draft_Model_Draft
      */
     require_once 'Conjoon/Modules/Groupware/Email/Draft/Model/Draft.php';
     $draftModel = new Conjoon_Modules_Groupware_Email_Draft_Model_Draft();
     $draftData = $draftModel->getDraft($id, $userId, $type);
     if (empty($draftData)) {
         $this->view->error = $this->getErrorDto('Error while opening draft', 'Could not find the referenced draft.', Conjoon_Error::LEVEL_ERROR);
         $this->view->draft = null;
         $this->view->success = false;
         return;
     }
     switch ($type) {
         case 'reply':
             $context = Conjoon_Modules_Groupware_Email_Draft_Filter_DraftResponse::CONTEXT_REPLY;
             break;
         case 'reply_all':
             $context = Conjoon_Modules_Groupware_Email_Draft_Filter_DraftResponse::CONTEXT_REPLY_ALL;
             break;
         case 'forward':
             $context = Conjoon_Modules_Groupware_Email_Draft_Filter_DraftResponse::CONTEXT_FORWARD;
             break;
         case 'edit':
             $context = Conjoon_Modules_Groupware_Email_Draft_Filter_DraftResponse::CONTEXT_EDIT;
             break;
         default:
             throw new Exception("Type {$type} not supported.");
             break;
     }
     Conjoon_Util_Array::camelizeKeys($draftData);
     $addresses = $accountModel->getEmailAddressesForUser($userId);
     $draftData['userEmailAddresses'] = $addresses;
     /**
      * @ticket CN-708
      * if context is not edit and equals to reply* or forward, read out the
      * "to" address and find the matching account we'll be using for setting as
      * account from which the mail gets edited
      */
     $matchingAccountId = -1;
     if ($context !== Conjoon_Modules_Groupware_Email_Draft_Filter_DraftResponse::CONTEXT_EDIT) {
         $orgTo = $draftData['to'];
         $matchingAccountId = $this->guessMailAccountForAddress($orgTo);
         if ($matchingAccountId > -1) {
             $draftData['groupwareEmailAccountsId'] = $matchingAccountId;
         }
     }
     $draftFilter = new Conjoon_Modules_Groupware_Email_Draft_Filter_DraftResponse($draftData, $context);
     $data = $draftFilter->getProcessedData();
     $templateData = $data;
     // needed for draft forward because of Bean_Inspector
     unset($data['userEmailAddresses']);
     unset($data['from']);
     unset($data['replyTo']);
     if ($type == 'forward') {
         $data['to'] = array();
         $data['cc'] = array();
     }
     // convert email addresses
     /**
      * @see Conjoon_Modules_Groupware_Email_Address
      */
     require_once 'Conjoon/Modules/Groupware/Email/Address.php';
     $to = array();
     $cc = array();
     $bcc = array();
     foreach ($data['to'] as $add) {
         $to[] = new Conjoon_Modules_Groupware_Email_Address($add);
     }
     foreach ($data['cc'] as $add) {
         $cc[] = new Conjoon_Modules_Groupware_Email_Address($add);
     }
     foreach ($data['bcc'] as $add) {
         $bcc[] = new Conjoon_Modules_Groupware_Email_Address($add);
     }
     $data['to'] = $to;
     $data['cc'] = $cc;
     $data['bcc'] = $bcc;
     $draft = Conjoon_BeanContext_Inspector::create('Conjoon_Modules_Groupware_Email_Draft', $data)->getDto();
     if ($type == 'forward') {
         $applicationPath = $this->_helper->registryAccess()->getApplicationPath();
         /**
          * @see Conjoon_Text_PhpTemplate
          */
         require_once 'Conjoon/Text/PhpTemplate.php';
         /**
          * @see Conjoon_Filter_StringWrap
          */
         require_once 'Conjoon/Filter/StringWrap.php';
         /**
          * @see Zend_Filter_HtmlEntities
          */
         require_once 'Zend/Filter/HtmlEntities.php';
         $cfsw = new Conjoon_Filter_StringWrap('[Fwd: ', ']');
         $zfhe = new Zend_Filter_HtmlEntities(array('quotestyle' => ENT_COMPAT, 'charset' => 'UTF-8'));
         $draft->subject = $cfsw->filter($templateData['subject']);
         $templateData['subject'] = $zfhe->filter($templateData['subject']);
         $phpTemplate = new Conjoon_Text_PhpTemplate(array(Conjoon_Text_PhpTemplate::PATH => $applicationPath . '/templates/groupware/email/message.forward.phtml', Conjoon_Text_PhpTemplate::VARS => $templateData));
         $draft->contentTextPlain = $phpTemplate->getParsedTemplate();
     }
     $this->view->success = true;
     $this->view->error = null;
     $this->view->draft = $draft;
     $this->view->type = $type;
 }