/**
  * Adds another feed-account for the user.
  * This method will store the account-settings for the feed and immediately
  * store all items related to it. The items itself will be returned with the
  * view variable "items", the account will be available in the view-variable
  * "account".
  */
 public function addFeedAction()
 {
     /*@REMOVE@*/
     if (!$this->_helper->connectionCheck()) {
         /**
          * @see Conjoon_Error_Factory
          */
         require_once 'Conjoon/Error/Factory.php';
         $this->view->success = false;
         $this->view->error = Conjoon_Error_Factory::createError("Unexpected connection failure while trying to add feed account. " . "Please try again.", Conjoon_Error::LEVEL_WARNING, Conjoon_Error::DATA)->getDto();
         return;
     }
     /*@REMOVE@*/
     /**
      * @see Conjoon_Modules_Groupware_Feeds_Account_Facade
      */
     require_once 'Conjoon/Modules/Groupware/Feeds/Account/Facade.php';
     $result = Conjoon_Modules_Groupware_Feeds_Account_Facade::getInstance()->addAccountAndImport(array('deleteInterval' => $this->_request->getParam('deleteInterval'), 'name' => $this->_request->getParam('name'), 'requestTimeout' => $this->_request->getParam('requestTimeout'), 'updateInterval' => $this->_request->getParam('updateInterval'), 'uri' => $this->_request->getParam('uri')), $this->_helper->registryAccess()->getUserId());
     if (!empty($result)) {
         $this->view->success = true;
         $this->view->error = null;
         $this->view->account = $result['account'];
         $this->view->items = $result['items'];
     }
 }
 /**
  * Controller action for uploading files.
  * The method allows for only one file to be processed. It will send back
  * either an error obejct to the view or a File_Dto upon successfull
  * processing.
  *
  */
 public function uploadFileAction()
 {
     // first of, extract the file key
     $fileKey = array_pop(array_keys($_FILES));
     /**
      * @see Conjoon_Modules_Groupware_Files_Facade
      */
     require_once 'Conjoon/Modules/Groupware/Files/Facade.php';
     $facade = Conjoon_Modules_Groupware_Files_Facade::getInstance();
     $upload = $facade->generateUploadObject();
     if (!$upload->isValid()) {
         // generate the error message
         $message = $upload->getMessages();
         $messages = array();
         foreach ($message as $m) {
             $messages[] = $m;
         }
         /**
          * @see Conjoon_Error_Factory
          */
         require_once 'Conjoon/Error/Factory.php';
         $error = Conjoon_Error_Factory::createError(implode("\n", $messages), Conjoon_Error::LEVEL_WARNING, Conjoon_Error::INPUT)->getDto();
         $this->view->success = false;
         $this->view->error = $error;
         return;
     }
     $fileDto = $facade->uploadFileToTempFolderForUser($upload, $this->_helper->registryAccess->getUserId());
     if (!$fileDto) {
         /**
          * @see Conjoon_Error_Factory
          */
         require_once 'Conjoon/Error/Factory.php';
         $error = Conjoon_Error_Factory::createError("Sorry, I could not upload this file. Something went wrong", Conjoon_Error::LEVEL_WARNING, Conjoon_Error::INPUT)->getDto();
         $this->view->success = false;
         $this->view->error = $error;
         return;
     }
     // we will silently add the old id to Dto so the client can identify the
     // uploaded record properly
     $fileDto->oldId = $fileKey;
     $fileDto->folderId = $fileDto->groupwareFilesFoldersId;
     unset($fileDto->groupwareFilesFoldersId);
     $this->view->success = true;
     $this->view->files = array($fileDto);
 }
 /**
  * Returns the feed item (dto) with it's content.
  *
  */
 public function getFeedContentAction()
 {
     /**
      * @see Conjoon_Modules_Groupware_Feeds_Item_Facade
      */
     require_once 'Conjoon/Modules/Groupware/Feeds/Item/Facade.php';
     $item = Conjoon_Modules_Groupware_Feeds_Item_Facade::getInstance()->getFeedContent($this->_request->getParam('id'), $this->_request->getParam('groupwareFeedsAccountsId'), $this->_helper->registryAccess()->getUserId());
     if ($item == null) {
         /**
          * @see Conjoon_Error_Factory
          */
         require_once 'Conjoon/Error/Factory.php';
         $this->view->success = false;
         $this->view->item = null;
         $this->view->error = Conjoon_Error_Factory::createError("The requested feed item was not found on the server.", Conjoon_Error::LEVEL_ERROR, Conjoon_Error::DATA)->getDto();
     } else {
         $this->view->success = true;
         $this->view->item = $item;
         $this->view->error = null;
     }
 }
 /**
  * Imports a new Twitter account into conjoon.
  * Needed post parameters are "name", "twitterId", "oauthToken" and
  * "oauthTokenSecret".
  * The method will try to connect to the Twitter service to verify
  * the account credentials.
  * If this fails, the following information will be send to the client:
  *  - connectionFailure = true
  *  - success = false
  * Any other error will be communicated to the client. A successfull
  * stored account will be saved in "account" and returned to the client.
  *
  *
  */
 public function addAccountAction()
 {
     $name = $this->_request->getParam('name');
     $oauthToken = $this->_request->getParam('oauthToken');
     $oauthTokenSecret = $this->_request->getParam('oauthTokenSecret');
     $twitterId = $this->_request->getParam('twitterId');
     $updateInterval = $this->_request->getParam('updateInterval');
     /**
      * @see Zend_Registry
      */
     require_once 'Zend/Registry.php';
     /**
      * @see Conjoon_Keys
      */
     require_once 'Conjoon/Keys.php';
     $config = Zend_Registry::get(Conjoon_Keys::REGISTRY_CONFIG_OBJECT);
     $consumerKey = $config->application->twitter->oauth->consumerKey;
     $consumerSecret = $config->application->twitter->oauth->consumerSecret;
     /**
      * @see Conjoon_Modules_Default_Registry_Facade
      */
     require_once 'Conjoon/Modules/Default/Registry/Facade.php';
     $protocolContext = Conjoon_Modules_Default_Registry_Facade::getInstance()->getValueForKeyAndUserId('/server/environment/protocol', $this->_helper->registryAccess()->getUserId());
     /**
      * @see Conjoon_Service_Twitter_Proxy
      */
     require_once 'Conjoon/Service/Twitter/Proxy.php';
     $proxy = new Conjoon_Service_Twitter_Proxy(array('oauth_token' => $oauthToken, 'oauth_token_secret' => $oauthTokenSecret, 'user_id' => $twitterId, 'screen_name' => $name, 'consumer_key' => $consumerKey, 'consumer_secret' => $consumerSecret, 'protocol_context' => $protocolContext));
     $dto = $proxy->accountVerifyCredentials();
     /**
      * @see Conjoon_Error
      */
     require_once 'Conjoon/Error.php';
     if ($dto instanceof Conjoon_Error) {
         $this->view->success = false;
         $this->view->error = $dto->getDto();
         $this->view->connectionFailure = true;
         return;
     }
     /**
      * @see Conjoon_Modules_Service_Twitter_Account_Model_Account
      */
     require_once 'Conjoon/Modules/Service/Twitter/Account/Model/Account.php';
     $model = new Conjoon_Modules_Service_Twitter_Account_Model_Account();
     $id = $model->addAccountForUserId(array('name' => $name, 'update_interval' => $updateInterval, 'oauth_token' => $oauthToken, 'oauth_token_secret' => $oauthTokenSecret, 'twitter_id' => $twitterId), $this->_helper->registryAccess()->getUserId());
     if ($id == 0) {
         /**
          * @see Conjoon_Error_Factory
          */
         require_once 'Conjoon/Error/Factory.php';
         $this->view->error = Conjoon_Error_Factory::createError("Could not write the data for the Twitter account into the datastorage.", Conjoon_Error::LEVEL_ERROR);
         $this->view->success = false;
         return;
     }
     /**
      * @see Conjoon_Builder_Factory
      */
     require_once 'Conjoon/Builder/Factory.php';
     Conjoon_Builder_Factory::getBuilder(Conjoon_Keys::CACHE_TWITTER_ACCOUNTS, Zend_Registry::get(Conjoon_Keys::REGISTRY_CONFIG_OBJECT)->toArray())->remove(array('userId' => $this->_helper->registryAccess()->getUserId()));
     $dto->updateInterval = $updateInterval;
     $dto->password = "******";
     $dto->name = $name;
     $dto->id = $id;
     $this->view->success = true;
     $this->view->account = $dto;
 }
 /**
  * Returns the account dto for the specified account id, or an instance of
  * Conjoon_Error if an error occurs
  *
  * @param $accountId
  * @return account dto or an instance of Conjoon_Error
  *
  */
 protected function getAccountDto($accountId)
 {
     if (isset($this->accountDtoCache[$accountId])) {
         return $this->accountDtoCache[$accountId];
     }
     /**
      * @see Conjoon_Error_Factory
      */
     require_once 'Conjoon/Error/Factory.php';
     if ($accountId <= 0) {
         $error = Conjoon_Error_Factory::createError("Could not process the request: No account-id provided.", Conjoon_Error::LEVEL_ERROR)->getDto();
         return $error;
     }
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     $decoratedModel = new Conjoon_BeanContext_Decorator('Conjoon_Modules_Service_Twitter_Account_Model_Account');
     $accountDto = $decoratedModel->getAccountAsDto($accountId);
     if (!$accountDto) {
         $error = Conjoon_Error_Factory::createError("Could not switch friendship: No account matches " . "the id \"" . $accountId . "\".", Conjoon_Error::LEVEL_CRITICAL);
         return $error;
     }
     return $this->accountDtoCache[$accountId] = $accountDto;
     return $accountDto;
 }
 /**
  * Bulk sends emails. Awaits the parameter ids as a numeric array with the ids of
  * the emails which should get send.
  *
  */
 public function bulkSendAction()
 {
     /*@REMOVE@*/
     if (!$this->_helper->connectionCheck()) {
         /**
          * @see Conjoon_Error_Factory
          */
         require_once 'Conjoon/Error/Factory.php';
         $this->view->success = false;
         $this->view->sentItems = array();
         $this->view->error = null;
         $this->view->contextReferencedItems = array();
         $this->view->error = Conjoon_Error_Factory::createError("Unexpected connection failure while trying to bulk-send emails. " . "Please try again.", Conjoon_Error::LEVEL_WARNING, Conjoon_Error::DATA)->getDto();
         return;
     }
     /*@REMOVE@*/
     $toSend = $_POST['ids'];
     if ($this->_helper->conjoonContext()->getCurrentContext() == self::CONTEXT_JSON) {
         require_once 'Zend/Json.php';
         $toSend = Zend_Json::decode($toSend, Zend_Json::TYPE_ARRAY);
     }
     $date = null;
     if (isset($_POST['date'])) {
         require_once 'Conjoon/Filter/DateIso8601.php';
         $dateFilter = new Conjoon_Filter_DateIso8601();
         $date = $dateFilter->filter((int) $_POST['date']);
     }
     /**
      * @see Conjoon_Filter_EmailRecipients
      */
     require_once 'Conjoon/Filter/EmailRecipients.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Item_Filter_ItemResponse
      */
     require_once 'Conjoon/Modules/Groupware/Email/Item/Filter/ItemResponse.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Address
      */
     require_once 'Conjoon/Modules/Groupware/Email/Address.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Draft
      */
     require_once 'Conjoon/Modules/Groupware/Email/Draft.php';
     /**
      * @see Conjoon_BeanContext_Inspector
      */
     require_once 'Conjoon/BeanContext/Inspector.php';
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     /**
      * @see Conjoon_Util_Array
      */
     require_once 'Conjoon/Util/Array.php';
     /**
      * @see Conjoon_Keys
      */
     require_once 'Conjoon/Keys.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Draft_Model_Draft
      */
     require_once 'Conjoon/Modules/Groupware/Email/Draft/Model/Draft.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Draft_Filter_DraftInput
      */
     require_once 'Conjoon/Modules/Groupware/Email/Draft/Filter/DraftInput.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Sender
      */
     require_once 'Conjoon/Modules/Groupware/Email/Sender.php';
     $auth = Zend_Registry::get(Conjoon_Keys::REGISTRY_AUTH_OBJECT);
     $userId = $auth->getIdentity()->getId();
     $draftFilter = new Conjoon_Modules_Groupware_Email_Draft_Filter_DraftInput(array(), Conjoon_Filter_Input::CONTEXT_CREATE);
     $draftModel = new Conjoon_Modules_Groupware_Email_Draft_Model_Draft();
     $accountDecorator = new Conjoon_BeanContext_Decorator('Conjoon_Modules_Groupware_Email_Account_Model_Account');
     $recipientsFilter = new Conjoon_Filter_EmailRecipients();
     $newVersions = array();
     $sendItems = array();
     $contextReferencedItems = array();
     $errors = array();
     foreach ($toSend as $pathInfo) {
         $remoteInfo = array();
         $id = $pathInfo['id'];
         $path = $pathInfo['path'];
         $account = null;
         $remoteAttachments = array();
         // check if path is remote!
         $isRemote = $this->isRemotePath($path, $userId);
         if ($isRemote) {
             $rawDraft = $this->getRawImapMessage($id, $path);
             if (empty($rawDraft)) {
                 continue;
             }
             //we have to post the existing attachments of the remote draft
             // again when assembling the message to send.
             // Otherwise the sender would not know which attachments should get send
             // along with the message
             $remoteAttachments = $rawDraft['attachments'];
             foreach ($remoteAttachments as &$remoteAttachment) {
                 $remoteAttachment['metaType'] = 'emailAttachment';
                 $remoteAttachment['name'] = $remoteAttachment['fileName'];
             }
             $remoteInfo = array('uid' => $id, 'account' => $isRemote, 'path' => $path);
             $rawDraft['groupwareEmailAccountsId'] = $isRemote->id;
             $account = $accountDecorator->getAccountAsEntity($rawDraft['groupwareEmailAccountsId'], $userId);
         } else {
             $rawDraft = $draftModel->getDraft($id, $userId);
             $account = $accountDecorator->getAccountAsEntity($rawDraft['groupware_email_accounts_id'], $userId);
         }
         // no account found?
         if (!$account) {
             /**
              * @todo think about using the standard account as a fallback or use at last
              * an error message to inform the user that the account used to write this email
              * is not available anymore
              */
             continue;
         }
         $id = (int) $id;
         if ($id <= 0) {
             continue;
         }
         if (empty($rawDraft)) {
             continue;
         }
         Conjoon_Util_Array::camelizeKeys($rawDraft);
         $rawDraft['to'] = $recipientsFilter->filter($rawDraft['to']);
         $rawDraft['cc'] = $recipientsFilter->filter($rawDraft['cc']);
         $rawDraft['bcc'] = $recipientsFilter->filter($rawDraft['bcc']);
         // create the message object here
         $to = array();
         $cc = array();
         $bcc = array();
         foreach ($rawDraft['cc'] as $dcc) {
             $add = new Conjoon_Modules_Groupware_Email_Address($dcc);
             $cc[] = $add;
         }
         foreach ($rawDraft['bcc'] as $dbcc) {
             $add = new Conjoon_Modules_Groupware_Email_Address($dbcc);
             $bcc[] = $add;
         }
         foreach ($rawDraft['to'] as $dto) {
             $add = new Conjoon_Modules_Groupware_Email_Address($dto);
             $to[] = $add;
         }
         $rawDraft['to'] = $to;
         $rawDraft['cc'] = $cc;
         $rawDraft['bcc'] = $bcc;
         $message = Conjoon_BeanContext_Inspector::create('Conjoon_Modules_Groupware_Email_Draft', $rawDraft, true);
         if ($date !== null) {
             $message->setDate($date);
         }
         try {
             $transport = $this->getTransportForAccount($account);
             $assembleInformation = Conjoon_Modules_Groupware_Email_Sender::getAssembledMail($message, $account, $remoteAttachments, array(), $this->getCurrentAppUser()->getId(), $transport);
             $assembledMail = $assembleInformation['message'];
             $postedAttachments = $assembleInformation['postedAttachments'];
             $mail = Conjoon_Modules_Groupware_Email_Sender::send($assembledMail);
         } catch (Exception $e) {
             $errors[] = array('subject' => $message->getSubject(), 'accountName' => $account->getName(), 'reason' => $e->getMessage());
             continue;
         }
         if ($isRemote) {
             /**
              * @see Conjoon_Modules_Groupware_Email_ImapHelper
              */
             require_once 'Conjoon/Modules/Groupware/Email/ImapHelper.php';
             $uId = $remoteInfo['uid'];
             $account = $remoteInfo['account'];
             $path = $remoteInfo['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(json_encode($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();
             // get the account for the root folder first
             $imapAccount = $facade->getImapAccountForFolderIdAndUserId($pathInfo['rootId'], $userId);
             if ($imapAccount && !empty($pathInfo) && $facade->isRemoteFolder($pathInfo['rootId'])) {
                 // if remote, where is the referenced mail stored?
                 $globalName = $facade->getAssembledGlobalNameForAccountAndPath($imapAccount, $pathInfo['path']);
                 /**
                  * @see Conjoon_Modules_Groupware_Email_ImapHelper
                  */
                 require_once 'Conjoon/Modules/Groupware/Email/ImapHelper.php';
                 /**
                  * @see Conjoon_Mail_Storage_Imap
                  */
                 require_once 'Conjoon/Mail/Storage/Imap.php';
                 $protocol = Conjoon_Modules_Groupware_Email_ImapHelper::reuseImapProtocolForAccount($imapAccount);
                 $storage = new Conjoon_Mail_Storage_Imap($protocol);
                 // get the number of the message by it's unique id
                 $storage->selectFolder($globalName);
                 $messageNumber = $storage->getNumberByUniqueId($uId);
                 // move from sent folder
                 $sentGlobalName = $this->getGlobalNameForFolderType($imapAccount, 'SENT');
                 if (!$sentGlobalName) {
                     continue;
                 }
                 $storage->copyMessage($messageNumber, $sentGlobalName);
                 $storage->selectFolder($sentGlobalName);
                 $newMessageNumber = $storage->countMessages();
                 $storage->selectFolder($globalName);
                 $storage->removeMessage($storage->getNumberByUniqueId($uId));
                 $storage->close();
             }
             // put email into sent folder
             $protocol = Conjoon_Modules_Groupware_Email_ImapHelper::reuseImapProtocolForAccount($imapAccount);
             $storage = new Conjoon_Mail_Storage_Imap($protocol);
             // read out single item
             $item = $this->getSingleImapListItem($account, $userId, $newMessageNumber, $sentGlobalName);
             $newVersions[$uId] = $item['id'];
             $sendItems[] = $item;
         } else {
             // if the email was send successfully, save it into the db and
             // return the params savedId (id of the newly saved email)
             // and savedFolderId (id of the folder where the email was saved in)
             $itemDecorator = new Conjoon_BeanContext_Decorator('Conjoon_Modules_Groupware_Email_Item_Model_Item', new Conjoon_Modules_Groupware_Email_Item_Filter_ItemResponse(array(), Conjoon_Filter_Input::CONTEXT_RESPONSE), false);
             $item = $itemDecorator->saveSentEmailAsDto($message, $account, $userId, $mail, '');
             if (!$item) {
                 continue;
             }
             $sendItems[] = $item;
             $cri = $itemDecorator->getReferencedItemAsDto($item->id, $userId);
             if (!empty($cri)) {
                 $contextReferencedItems[] = $cri;
             }
         }
     }
     if (!empty($errors)) {
         /**
          * @see Conjoon_Error
          */
         require_once 'Conjoon/Error.php';
         $m = array();
         $m[] = "One or more messages could not be sent:";
         for ($i = 0, $len = count($errors); $i < $len; $i++) {
             $m[] = "Message " . ($i + 1) . ":";
             $m[] = "Subject: \"" . $errors[$i]['subject'] . "\"";
             $m[] = "Account: " . $errors[$i]['accountName'];
             $m[] = "Failure reason: " . $errors[$i]['reason'];
         }
         $errorMessage = implode("\n", $m);
         $error = new Conjoon_Error();
         $error->setLevel(Conjoon_Error::LEVEL_WARNING);
         $error->setType(Conjoon_Error::DATA);
         $error->setMessage($errorMessage);
     }
     $this->view->newVersions = $newVersions;
     $this->view->success = true;
     $this->view->sentItems = $sendItems;
     $this->view->error = isset($error) ? $error->getDto() : null;
     $this->view->contextReferencedItems = $contextReferencedItems;
 }
 /**
  * Renames the folder with the specified it to the specified value.
  * Post vars:
  * id       : the id of the folder that gets renamed
  * name     : the new name of the node
  * parentId : the id of the current parent folder
  * path     : the path of this node in the tree. This is relevant for
  * IMAP mailboxes which get renamed
  */
 public function renameFolderAction()
 {
     /**
      * @see Conjoon_Modules_Groupware_Email_Folder_Facade
      */
     require_once 'Conjoon/Modules/Groupware/Email/Folder/Facade.php';
     $facade = Conjoon_Modules_Groupware_Email_Folder_Facade::getInstance();
     /**
      * @see Conjoon_Text_Parser_Mail_MailboxFolderPathJsonParser
      */
     require_once 'Conjoon/Text/Parser/Mail/MailboxFolderPathJsonParser.php';
     $parser = new Conjoon_Text_Parser_Mail_MailboxFolderPathJsonParser();
     try {
         $pathParts = $parser->parse($this->_request->getParam('path'));
     } catch (Conjoon_Text_Parser_Exception $e) {
         /**
          * @see Conjoon_Error
          */
         require_once 'Conjoon/Error.php';
         $error = Conjoon_Error::fromException($e);
         $this->view->success = false;
         $this->view->error = $error->getDto();
         return;
     }
     $name = $this->_request->getParam('name');
     $userId = $this->_helper->registryAccess->getUserId();
     try {
         $folder = $facade->renameFolderForPathAndUserId($name, $pathParts, $userId);
         if ($folder === false) {
             /**
              * @see Conjoon_Error_Factory
              */
             require_once 'Conjoon/Error/Factory.php';
             $error = Conjoon_Error_Factory::createError("Could not rename the specified folder.", Conjoon_Error::LEVEL_WARNING)->getDto();
             $this->view->success = false;
             $this->view->error = $error;
             return;
         }
     } catch (Exception $e) {
         /**
          * @see Conjoon_Error
          */
         require_once 'Conjoon/Error.php';
         $this->view->success = true;
         $this->view->error = Conjoon_Error::fromException($e)->getDto();
         return;
     }
     $this->view->success = true;
     $this->view->error = null;
     $this->view->folder = $folder;
 }