コード例 #1
0
 /**
  *
  * @param array $options An associative array with the following
  * key value/pairs:
  *   - id: The id of the feed item to return
  * @param Conjoon_BeanContext_Decoratable $model
  *
  * @return Conjoon_Modules_Groupware_Feeds_Item_Dto
  */
 protected function _build(array $options, Conjoon_BeanContext_Decoratable $model)
 {
     $accountId = $options['accountId'];
     /**
      * @see Conjoon_Modules_Groupware_Feeds_Item_Filter_Item
      */
     require_once 'Conjoon/Modules/Groupware/Feeds/Item/Filter/Item.php';
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     $itemResponseFilter = new Conjoon_Modules_Groupware_Feeds_Item_Filter_Item(array(), Conjoon_Filter_Input::CONTEXT_RESPONSE);
     $itemModel = new Conjoon_BeanContext_Decorator($model, $itemResponseFilter);
     return $itemModel->getItemsForAccountAsDto($accountId);
 }
コード例 #2
0
 public function processAction()
 {
     require_once 'Conjoon/Auth/Adapter/Db.php';
     /**
      * @todo Filter username and password!
      */
     $username = $this->_getParam('username');
     $password = $this->_getParam('password');
     $rememberMe = (bool) $this->_getParam('rememberMe');
     $lastUserRequest = (int) $this->_getParam('lastUserRequest');
     // Special case - the app was started and the user wants to re-login
     // since his session was lost. Check if the user object as returned by the
     // data storage has a property lastLogin which may not be greater than
     // the "lastUserRequest"-parameter - if that is teh case, most likely another
     // user has logged in so the user has to completely restart the application -
     // a redirect to the base url will happen
     if ($lastUserRequest) {
         /**
          * @see Conjoon_Modules_Default_User_Model_User
          */
         require_once 'Conjoon/Modules/Default/User/Model/User.php';
         $userTable = new Conjoon_Modules_Default_User_Model_User();
         /**
          * @see Conjoon_BeanContext_Decorator
          */
         require_once 'Conjoon/BeanContext/Decorator.php';
         $decorator = new Conjoon_BeanContext_Decorator($userTable);
         $userDto = $decorator->getUserForUserNameCredentialsAsDto($username, md5($password));
         if ($userDto && $lastUserRequest <= $userDto->lastLogin) {
             // special case - send an auth token failure with the response
             $this->_response->setHttpResponseCode(401);
             /**
              * @see Conjoon_Error
              */
             require_once 'Conjoon/Error.php';
             $error = new Conjoon_Error();
             $error->setCode(-1);
             $error->setLevel(Conjoon_Error::LEVEL_ERROR);
             $error->setFile(__FILE__);
             $error->setLine(__LINE__);
             $error->setMessage("Someone has signed in with your user credentials. Please sign in again.");
             $error->setType(Conjoon_Error::TOKEN_FAILURE);
             $this->view->tokenFailure = true;
             /**
              * @todo create filter
              */
             unset($userDto->authToken);
             $this->view->user = $userDto;
             $this->view->success = false;
             $this->view->error = $error->getDto();
             return;
         }
     }
     $auth = Zend_Registry::get(Conjoon_Keys::REGISTRY_AUTH_OBJECT);
     $authAdapter = new Conjoon_Auth_Adapter_Db(array('username' => $username, 'password' => $password, 'remember_me' => $rememberMe));
     // if the result is valid, the return value of the adapter will
     // be stored automatically in the supplied storage object
     // from the auth object
     $result = $auth->authenticate($authAdapter);
     if ($result->isValid()) {
         $user = $result->getIdentity();
         if ($rememberMe && $user->getRememberMeToken() != null) {
             $this->setAutoLoginCookies(md5($user->getUserName()), $user->getRememberMeToken(), time() + 2592000);
         }
         $this->view->success = true;
     } else {
         $this->view->error = 'Wrong username or password';
         $this->view->success = false;
     }
 }
コード例 #3
0
 /**
  * Returns either a cached list of feed accounts for a user, or
  * the accounts out of the database.
  *
  * @param array $options An associative array with the following
  * key value/pairs:
  *   - userId: the id of the user to fetch all feed accounts for
  * @param Conjoon_BeanContext_Decoratable $model
  *
  * @return Array an array with instances of
  * Conjoon_Modules_Groupware_Feeds_Account_Model_Account_Dto
  */
 protected function _build(array $options, Conjoon_BeanContext_Decoratable $model)
 {
     $userId = $options['userId'];
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     $decoratedModel = new Conjoon_BeanContext_Decorator($model);
     $accounts = $decoratedModel->getAccountsForUserAsDto($userId);
     return $accounts;
 }
コード例 #4
0
ファイル: Auth.php プロジェクト: ThorstenSuckow/conjoon
 /**
  * Called before teh disptach loop gets processed.
  *
  * This callback allows for proxy or filter behavior.  By altering the
  * request and resetting its dispatched flag (via
  * {@link Zend_Controller_Request_Abstract::setDispatched() setDispatched(false)}),
  * the current action may be skipped.
  *
  * The method checks for an authenticated user. It does also compare the
  * authToken property of teh user with the auth_token field in the db - if the
  * authToken is set in the db and does not equal to the authToken in the session,
  * then it is assumed that another user has signed in with the same credentials, and
  * the user's current session will be invalidated.
  *
  * @param  Zend_Controller_Request_Abstract $request
  * @return void
  */
 public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
 {
     // check here if the user's authentity is already set
     if (!$this->auth->hasIdentity()) {
         /**
          * @see Conjoon_Keys
          */
         require_once 'Conjoon/Keys.php';
         if (isset($_COOKIE[Conjoon_Keys::COOKIE_REMEMBERME_UNAME]) && isset($_COOKIE[Conjoon_Keys::COOKIE_REMEMBERME_TOKEN])) {
             /**
              * @see Conjoon_Auth_Adapter_Db
              */
             require_once 'Conjoon/Auth/Adapter/Db.php';
             $authAdapter = new Conjoon_Auth_Adapter_Db(array('cookie' => array('name' => $_COOKIE[Conjoon_Keys::COOKIE_REMEMBERME_UNAME], 'remember_me_token' => $_COOKIE[Conjoon_Keys::COOKIE_REMEMBERME_TOKEN])));
             // if the result is valid, the return value of the adapter will
             // be stored automatically in the supplied storage object
             // from the auth object
             $this->auth->authenticate($authAdapter);
         }
     }
     if ($this->auth->hasIdentity()) {
         // identity is set. Now check for auth token equality
         $currentUser = $this->auth->getIdentity();
         /**
          * @see Conjoon_BeanContext_Decorator
          */
         require_once 'Conjoon/BeanContext/Decorator.php';
         /**
          * @see Conjoon_Modules_Default_User_Model_User
          */
         require_once 'Conjoon/Modules/Default/User/Model/User.php';
         $decorator = new Conjoon_BeanContext_Decorator(new Conjoon_Modules_Default_User_Model_User());
         $tokenedUser = $decorator->getUserAsDto($currentUser->getId());
         // check whether the token in the DB equals to the token in the session
         if ($tokenedUser->authToken != $currentUser->getAuthToken()) {
             // the application needs to query the registry. That's okay since no secret data will
             // be transported if the registry sees that there's no login
             if ($request->action == 'get.entries' && $request->controller == 'registry' && $request->module == 'default') {
                 return;
             }
             // user wants to log out - this is needed to sign in again since the
             // active session will prevent from continue with using the app
             if ($request->action == 'logout' && $request->controller == 'reception' && $request->module == 'default') {
                 return;
             }
             // does not equal - someone has logged in currently
             // with the same user credentials.
             // redirect to appropriate controller action
             $request->setModuleName('default');
             $request->setControllerName('reception');
             $request->setActionName('auth.token.failure');
         }
         return;
     }
     // the user wants to login and requested the login controller's process
     // action. Let him pass!
     if ($request->action == 'process' && $request->controller == 'reception' && $request->module == 'default') {
         return;
     }
     // user wants to log out - okay
     if ($request->action == 'logout' && $request->controller == 'reception' && $request->module == 'default') {
         return;
     }
     // resource not available.
     if ($request->action == 'resource.not.available' && $request->controller == 'index' && $request->module == 'default') {
         return;
     }
     // the application needs to query the registry. That's okay since no secret data will
     // be transported if the registry sees that there's no login
     if ($request->action == 'get.entries' && $request->controller == 'registry' && $request->module == 'default') {
         return;
     }
     // anything other means the user is not logged in
     $request->setModuleName('default')->setControllerName('reception')->setActionName('index')->setDispatched(false);
 }
コード例 #5
0
ファイル: Builder.php プロジェクト: ThorstenSuckow/conjoon
 /**
  * Returns either a cached list of twitter accounts for a user, or
  * the accounts out of the database which will immediately be validated
  * against the twitter service (network access)
  *
  * @param array $options An associative array with the following
  * key value/pairs:
  *   - userId: the id of the user to fetch al twitter accounts for
  * @param Conjoon_BeanContext_Decoratable $model
  *
  * @return Array anr array with instances of
  * Conjoon_Modules_Service_Twitter_Account_Model_Account
  */
 protected function _build(array $options, Conjoon_BeanContext_Decoratable $model)
 {
     $userId = $options['userId'];
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     $decoratedModel = new Conjoon_BeanContext_Decorator($model);
     $accounts = $decoratedModel->getAccountsForUserAsDto($userId);
     /**
      * @see Conjoon_Service_Twitter
      */
     require_once 'Conjoon/Service/Twitter.php';
     /**
      * @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', $userId);
     for ($i = 0, $len = count($accounts); $i < $len; $i++) {
         $dto =& $accounts[$i];
         try {
             /**
              * @todo move to separate model
              */
             /**
              * @see Zend_Oauth_Token_Access
              */
             require_once 'Zend/Oauth/Token/Access.php';
             $accessToken = new Zend_Oauth_Token_Access();
             $accessToken->setParams(array('oauth_token' => $dto->oauthToken, 'oauth_token_secret' => $dto->oauthTokenSecret, 'user_id' => $dto->twitterId, 'screen_name' => $dto->name));
             $twitter = new Conjoon_Service_Twitter(array('username' => $dto->name, 'accessToken' => $accessToken));
             $response = $twitter->userShow($dto->name);
             $dto->twitterId = $response->id_str;
             $dto->twitterName = $response->name;
             $dto->twitterScreenName = $response->screen_name;
             $dto->twitterLocation = $response->location;
             $dto->twitterProfileImageUrl = $protocolContext === 'https' ? $response->profile_image_url_https : $response->profile_image_url;
             $dto->twitterUrl = $response->url;
             $dto->twitterProtected = $response->protected;
             $dto->twitterDescription = $response->description;
             $dto->twitterFollowersCount = $response->followers_count;
         } catch (Exception $e) {
             Conjoon_Log::log("Could not retrieve account information for twitter " . "account: \"" . $e->getMessage() . "\"", Zend_Log::INFO);
             // ignore
         }
         $dto->oauthTokenSecret = str_pad("", strlen($dto->oauthTokenSecret), '*');
     }
     return $accounts;
 }
コード例 #6
0
 /**
  * Saves a draft into the outbox folder of the user.
  */
 public function moveToOutboxAction()
 {
     /**
      * @see Conjoon_Modules_Groupware_Email_Draft_Filter_DraftInput
      */
     require_once 'Conjoon/Modules/Groupware/Email/Draft/Filter/DraftInput.php';
     $data = array();
     try {
         // the filter will transform the "message" into bodyHtml and bodyText, depending
         // on the passed format. both will only be filled if format equals to "multipart"
         $filter = new Conjoon_Modules_Groupware_Email_Draft_Filter_DraftInput($_POST, Conjoon_Filter_Input::CONTEXT_CREATE);
         $data = $filter->getProcessedData();
         $postedPath = $data['path'];
     } catch (Exception $e) {
         require_once 'Conjoon/Error.php';
         $error = Conjoon_Error::fromFilter($filter, $e);
         $this->view->success = false;
         $this->view->error = $error->getDto();
         $this->view->item = null;
         return;
     }
     /**
      * @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';
     // create the message object here
     $to = array();
     $cc = array();
     $bcc = array();
     $postedAttachments = $data['attachments'];
     $data['attachments'] = array();
     $removeAttachmentIds = $data['removedAttachments'];
     unset($data['removedAttachments']);
     foreach ($data['cc'] as $dcc) {
         $add = new Conjoon_Modules_Groupware_Email_Address($dcc);
         $cc[] = $add;
     }
     foreach ($data['bcc'] as $dbcc) {
         $add = new Conjoon_Modules_Groupware_Email_Address($dbcc);
         $bcc[] = $add;
     }
     foreach ($data['to'] as $dto) {
         $add = new Conjoon_Modules_Groupware_Email_Address($dto);
         $to[] = $add;
     }
     $data['cc'] = $cc;
     $data['to'] = $to;
     $data['bcc'] = $bcc;
     // get the specified account for the user
     require_once 'Conjoon/BeanContext/Decorator.php';
     require_once 'Conjoon/Keys.php';
     $accountDecorator = new Conjoon_BeanContext_Decorator('Conjoon_Modules_Groupware_Email_Account_Model_Account');
     $auth = Zend_Registry::get(Conjoon_Keys::REGISTRY_AUTH_OBJECT);
     $userId = $auth->getIdentity()->getId();
     $account = $accountDecorator->getAccountAsEntity($data['groupwareEmailAccountsId'], $userId);
     // no account found?
     if (!$account) {
         $this->view->error = $this->getErrorDto('Error while moving email to the outbox folder', 'Could not find specified account.', Conjoon_Error::LEVEL_ERROR);
         $this->view->success = false;
         $this->view->item = null;
         return;
     }
     $draft = Conjoon_BeanContext_Inspector::create('Conjoon_Modules_Groupware_Email_Draft', $data, true);
     if ($account->getProtocol() == 'IMAP') {
         return $this->moveImapToOutbox($account, $draft, $userId, $postedAttachments, $removeAttachmentIds);
     }
     $draft = Conjoon_BeanContext_Inspector::create('Conjoon_Modules_Groupware_Email_Draft', $data, true);
     $updateCache = false;
     // check whether we need to apply attachments for a previously saved
     // draft
     if ($draft->getId() > 0) {
         $updateCache = true;
         /**
          * @see Conjoon_Modules_Groupware_Email_Attachment_Filter_AttachmentResponse
          */
         require_once 'Conjoon/Modules/Groupware/Email/Attachment/Filter/AttachmentResponse.php';
         $attDecorator = new Conjoon_BeanContext_Decorator('Conjoon_Modules_Groupware_Email_Attachment_Model_Attachment', new Conjoon_Modules_Groupware_Email_Attachment_Filter_AttachmentResponse(array(), Conjoon_Modules_Groupware_Email_Attachment_Filter_AttachmentResponse::CONTEXT_RESPONSE));
         $atts = $attDecorator->getAttachmentsForItemAsEntity($draft->getId());
         $draft->setAttachments($atts);
     }
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Item_Filter_ItemResponse
      */
     require_once 'Conjoon/Modules/Groupware/Email/Item/Filter/ItemResponse.php';
     $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->moveDraftToOutboxAsDto($draft, $account, $userId, $data['type'], $data['referencesId'], $postedAttachments, $removeAttachmentIds);
     if (!$item) {
         $this->view->error = $this->getErrorDto('Error while saving email', 'The email could not be stored into the database.', Conjoon_Error::LEVEL_ERROR);
         $this->view->success = false;
         $this->view->item = null;
         return;
     }
     if ($updateCache) {
         /**
          * @see Conjoon_Modules_Groupware_Email_Message_Facade
          */
         require_once 'Conjoon/Modules/Groupware/Email/Message/Facade.php';
         // update cache
         Conjoon_Modules_Groupware_Email_Message_Facade::getInstance()->removeMessageFromCache($item->id, $this->_helper->registryAccess()->getUserId(), $postedPath);
     }
     $this->view->error = null;
     $this->view->success = true;
     $this->view->item = $item;
 }
コード例 #7
0
 /**
  * This action will update email accounts according to the POST params
  * that come along with the request.
  * Depending of the current context the action was called, the format of the
  * POST params will differ: For json, it will be an array holding json-encoded parameters.
  * Despite all different formats the POST params may come in, each request sends
  * values for 'updated' and 'deleted' accounts: 'deleted' as an array, holding all
  * ids that should become deleted, and 'updated' an array holding information about
  * the records that get edited, represented by specific associative array, representing
  * the fields of the record.
  * The view will await values assigned to 'updated_failed' and 'deleted_failed', whereas
  * 'deleted_failed' is an array containing all ids that couldn't be deleted, and
  * 'updated_failed' an array containing the records (in associative array notation)
  * that could not be updated.
  *
  * Note: If any error in the user-input was detected, no update-action will happen, but
  * deltes may already have been submitted to the underlying datastore.
  * The first error found in the passed data will be returned as an error of the type
  * Conjoon_Error_Form, containing the fields that where errorneous.
  *
  */
 public function updateEmailAccountsAction()
 {
     require_once 'Conjoon/Modules/Groupware/Email/Account/Filter/Account.php';
     require_once 'Conjoon/Util/Array.php';
     require_once 'Conjoon/Modules/Groupware/Email/Account/Model/Account.php';
     $toDelete = array();
     $toUpdate = array();
     $deletedFailed = array();
     $updatedFailed = array();
     $model = new Conjoon_Modules_Groupware_Email_Account_Model_Account();
     $data = array();
     $error = null;
     if ($this->_helper->conjoonContext()->getCurrentContext() == self::CONTEXT_JSON) {
         require_once 'Zend/Json.php';
         $toDelete = Zend_Json::decode($_POST['deleted'], Zend_Json::TYPE_ARRAY);
         $toUpdate = Zend_Json::decode($_POST['updated'], Zend_Json::TYPE_ARRAY);
     }
     $numToUpdate = count($toUpdate);
     $numToDelete = count($toDelete);
     if ($numToUpdate != 0 || $numToDelete != 0) {
         /**
          * @see Conjoon_Builder_Factory
          */
         require_once 'Conjoon/Builder/Factory.php';
         Conjoon_Builder_Factory::getBuilder(Conjoon_Keys::CACHE_EMAIL_ACCOUNTS, Zend_Registry::get(Conjoon_Keys::REGISTRY_CONFIG_OBJECT)->toArray())->cleanCacheForTags(array('userId' => Zend_Registry::get(Conjoon_Keys::REGISTRY_AUTH_OBJECT)->getIdentity()->getId()));
     }
     $userId = $this->_helper->registryAccess()->getUserId();
     for ($i = 0; $i < $numToDelete; $i++) {
         $affected = $model->deleteAccount($toDelete[$i], $userId);
         if ($affected == 0) {
             $deletedFailed[] = $toDelete[$i];
         }
     }
     $folderMappingData = array();
     for ($i = 0; $i < $numToUpdate; $i++) {
         $_ = $toUpdate[$i];
         $folderMappingData[$toUpdate[$i]['id']] = $toUpdate[$i]['folderMappings'];
         $filter = new Conjoon_Modules_Groupware_Email_Account_Filter_Account($_, Conjoon_Filter_Input::CONTEXT_UPDATE);
         try {
             $data[$i] = $filter->getProcessedData();
             Conjoon_Util_Array::underscoreKeys($data[$i]);
         } catch (Zend_Filter_Exception $e) {
             require_once 'Conjoon/Error.php';
             $error = Conjoon_Error::fromFilter($filter, $e);
             $this->view->success = false;
             $this->view->updatedFailed = array($_['id']);
             $this->view->deletedFailed = $deletedFailed;
             $this->view->error = $error->getDto();
             return;
         }
     }
     $createdLocalRootMailFolders = array();
     $removedLocalRootMailFolders = array();
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     $decoratedFolderModel = new Conjoon_BeanContext_Decorator('Conjoon_Modules_Groupware_Email_Folder_Model_Folder', null, false);
     $decoratedAccountModel = new Conjoon_BeanContext_Decorator('Conjoon_Modules_Groupware_Email_Account_Model_Account');
     /**
      * @see Conjoon_Modules_Groupware_Email_Folder_Model_Folder
      */
     require_once 'Conjoon/Modules/Groupware/Email/Folder/Model/Folder.php';
     $folderModel = new Conjoon_Modules_Groupware_Email_Folder_Model_Folder();
     /**
      * @see Conjoon_Modules_Groupware_Email_Folder_Model_FoldersAccounts
      */
     require_once 'Conjoon/Modules/Groupware/Email/Folder/Model/FoldersAccounts.php';
     $foldersAccounts = new Conjoon_Modules_Groupware_Email_Folder_Model_FoldersAccounts();
     for ($i = 0, $len = count($data); $i < $len; $i++) {
         $id = $data[$i]['id'];
         unset($data[$i]['id']);
         // check here for duplicates
         $duplicates = $model->getAccountWithNameForUser($data[$i]['name'], $userId);
         $affected = 0;
         if (!empty($duplicates)) {
             for ($a = 0, $lena = count($duplicates); $a < $lena; $a++) {
                 if ($duplicates[$a]['id'] != $id) {
                     $affected = -1;
                     break;
                 }
             }
         }
         if ($affected != -1) {
             $affected = $model->updateAccount($id, $data[$i]);
             $entityManager = Zend_Registry::get(Conjoon_Keys::DOCTRINE_ENTITY_MANAGER);
             // update folderMappings
             if (isset($folderMappingData[$id])) {
                 $fmRep = $entityManager->getRepository('\\Conjoon\\Data\\Entity\\Mail\\DefaultFolderMappingEntity');
                 for ($u = 0, $lenu = count($folderMappingData[$id]); $u < $lenu; $u++) {
                     if (isset($folderMappingData[$id][$u]['id']) && empty($folderMappingData[$id][$u]['path'])) {
                         $updEnt = $fmRep->findById($folderMappingData[$id][$u]['id']);
                         $updEnt->setGlobalName("");
                         $fmRep->register($updEnt);
                     } else {
                         if (isset($folderMappingData[$id][$u]['id']) && !empty($folderMappingData[$id][$u]['path'])) {
                             /**
                              * @see \Conjoon\Data\Entity\Mail\DefaultFolderMappingEntity
                              */
                             require_once 'Conjoon/Data/Entity/Mail/DefaultFolderMappingEntity.php';
                             /**
                              * @see Conjoon_Modules_Groupware_Email_ImapHelper
                              */
                             require_once 'Conjoon/Modules/Groupware/Email/ImapHelper.php';
                             $accDto = $decoratedAccountModel->getAccountAsDto($id, $userId);
                             $delim = Conjoon_Modules_Groupware_Email_ImapHelper::getFolderDelimiterForImapAccount($accDto);
                             $p = $folderMappingData[$id][$u]['path'];
                             array_shift($p);
                             array_shift($p);
                             $globalName = implode($delim, $p);
                             $updEnt = $fmRep->findById($folderMappingData[$id][$u]['id']);
                             $updEnt->setGlobalName($globalName);
                             $fmRep->register($updEnt);
                             continue;
                         }
                     }
                 }
                 $fmRep->flush();
             }
             // take care of folder heirarchies
             if ($affected != -1) {
                 /**
                  * @todo Facade
                  */
                 $hasSeparateFolderHierarchy = array_key_exists('has_separate_folder_hierarchy', $data[$i]) ? (bool) (int) $data[$i]['has_separate_folder_hierarchy'] : null;
                 // get org protocol of account so it cannot be changed from
                 // the outside
                 $orgAccount = $model->getAccount($id, $userId);
                 $orgProtocol = $orgAccount['protocol'];
                 if ($hasSeparateFolderHierarchy !== null && strtolower($orgProtocol) !== 'imap') {
                     // the original folder ids, before remapping occures
                     $oldAccountFolderIds = $foldersAccounts->getFolderIdsForAccountId($id);
                     // read out folder base data of folder for associated account
                     $rootFolderBaseData = $decoratedFolderModel->getAnyRootMailFolderBaseDataAsDto($id, $userId);
                     if (!$rootFolderBaseData) {
                         throw new RuntimeException("No root folder base data available.");
                     }
                     if (!$hasSeparateFolderHierarchy) {
                         // do nothing if type is already accounts_root and
                         // separateFolderHierarchy = false is submitted;
                         // but if the type is root and the folderHierarchy
                         // (i.e. "root) should be removed,
                         // we need to switch from root to accounts_root
                         if ($rootFolderBaseData->type == 'root') {
                             // check first if accounts_root exist!
                             $accountsRootFolderId = $folderModel->getAccountsRootMailFolderBaseData($userId);
                             // accounts root not yet existing
                             if (!$accountsRootFolderId) {
                                 $folderModel->createFolderBaseHierarchyAndMapAccountIdForUserId($id, $userId);
                             } else {
                                 $newFolderIds = $folderModel->getFoldersForAccountsRoot($userId);
                                 // accounts root already existing.
                                 // remove the root and remap to accounts_root
                                 foreach ($oldAccountFolderIds as $oldFolderId) {
                                     $folderModel->deleteFolder($oldFolderId, $userId, false);
                                 }
                                 $removedLocalRootMailFolders[$id] = $rootFolderBaseData;
                                 $foldersAccounts->mapFolderIdsToAccountId($newFolderIds, $id);
                             }
                             $createdLocalRootMailFolders[$id] = $decoratedFolderModel->getAnyRootMailFolderBaseDataAsDto($id, $userId);
                         }
                     } else {
                         // do nothing if the type is already root which means
                         // there already exists a separate folder hierarchy
                         // if the type is accounts_root, we need to switch
                         // to a root hierarchy
                         if ($rootFolderBaseData->type == 'accounts_root') {
                             // remove old mappings
                             $foldersAccounts->deleteForAccountId($id);
                             $folderModel->createFolderHierarchyAndMapAccountIdForUserId($id, $userId, $data[$i]['name']);
                             $createdLocalRootMailFolders[$id] = $decoratedFolderModel->getAnyRootMailFolderBaseDataAsDto($id, $userId);
                         }
                     }
                 }
             }
         }
         if ($affected == -1) {
             $updatedFailed[] = $id;
         }
     }
     $this->view->success = empty($updatedFailed) ? true : false;
     $this->view->updatedFailed = $updatedFailed;
     $this->view->deletedFailed = $deletedFailed;
     $this->view->error = null;
     $this->view->createdLocalRootMailFolders = $createdLocalRootMailFolders;
     $this->view->removedLocalRootMailFolders = $removedLocalRootMailFolders;
 }
コード例 #8
0
ファイル: Builder.php プロジェクト: ThorstenSuckow/conjoon
 /**
  *
  * @param array $options An associative array with the following
  * key value/pairs:
  *   - id: The id of the feed item to return
  * @param Conjoon_BeanContext_Decoratable $model
  *
  * @return Conjoon_Modules_Groupware_Feeds_Item_Dto
  */
 protected function _build(array $options, Conjoon_BeanContext_Decoratable $model)
 {
     $id = $options['id'];
     $accountId = $options['accountId'];
     $isImageEnabled = $options['isImageEnabled'];
     /**
      * @see Conjoon_Modules_Groupware_Feeds_Item_Filter_Item
      */
     require_once 'Conjoon/Modules/Groupware/Feeds/Item/Filter/Item.php';
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     $responseType = Conjoon_Modules_Groupware_Feeds_Item_Filter_Item::CONTEXT_ITEM_RESPONSE;
     if ($isImageEnabled) {
         $responseType = Conjoon_Modules_Groupware_Feeds_Item_Filter_Item::CONTEXT_ITEM_RESPONSE_IMG;
     }
     $itemResponseFilter = new Conjoon_Modules_Groupware_Feeds_Item_Filter_Item(array(), $responseType);
     $itemModel = new Conjoon_BeanContext_Decorator($model, $itemResponseFilter);
     $item = $itemModel->getItemAsDto($id);
     return $item;
 }
コード例 #9
0
ファイル: Builder.php プロジェクト: ThorstenSuckow/conjoon
 /**
  *
  * @param array $options An associative array with the following
  * key value/pairs:
  *   - groupwareEmailItemsId: The id of the email message to return
  *   - userId: the id of the user to whom this email message belongs @param Array $options
  * @param Conjoon_BeanContext_Decoratable $model
  *
  * @return Conjoon_Modules_Groupware_Email_Message_Dto
  */
 protected function _build(array $options, Conjoon_BeanContext_Decoratable $model)
 {
     $groupwareEmailItemsId = $options['groupwareEmailItemsId'];
     $userId = $options['userId'];
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Message_Filter_MessageResponse
      */
     require_once 'Conjoon/Modules/Groupware/Email/Message/Filter/MessageResponse.php';
     $messageDecorator = new Conjoon_BeanContext_Decorator($model, new Conjoon_Modules_Groupware_Email_Message_Filter_MessageResponse(array(), Conjoon_Filter_Input::CONTEXT_RESPONSE));
     $message = $messageDecorator->getEmailMessageAsDto($groupwareEmailItemsId, $userId);
     if (!$message) {
         return null;
     }
     require_once 'Conjoon/Modules/Groupware/Email/Attachment/Filter/AttachmentResponse.php';
     $attachmentDecorator = new Conjoon_BeanContext_Decorator('Conjoon_Modules_Groupware_Email_Attachment_Model_Attachment', new Conjoon_Modules_Groupware_Email_Attachment_Filter_AttachmentResponse(array(), Conjoon_Filter_Input::CONTEXT_RESPONSE));
     $attachments = $attachmentDecorator->getAttachmentsForItemAsDto($groupwareEmailItemsId);
     $message->attachments = $attachments;
     return $message;
 }
コード例 #10
0
ファイル: Db.php プロジェクト: ThorstenSuckow/conjoon
 /**
  * This emthod will authenticate a user against a database table.
  * It will also generate a login token that is generated during the
  * login process and will be stored in the db table. The token should then
  * be written into the session - before dispatching any request, it is advised
  * to check whether the session stored token still equals to the token stored
  * in the database - if not, it is likely that another login occured with
  * this user credentials.
  * We assume that the controller set the default adapter
  * for all database operations, thus is available without futher specifying
  * it.
  *
  * @return Zend_Auth_Result
  *
  * @throws Zend_Auth_Adapter_Exception
  */
 public function authenticate()
 {
     $cookieName = $this->cookieName;
     $rememberMeToken = $this->cookieRememberMe;
     $userName = $this->userName;
     $password = $this->password;
     $rememberMe = $this->rememberMe;
     if ($cookieName == "" && $rememberMeToken == "" && (trim($userName) == null || trim($password) == null)) {
         // return a general failure if either username or password
         // equal to <code>null</code>
         return new Zend_Auth_Result(Zend_Auth_Result::FAILURE, $userName, array('Authentication failed. Invalid data.'));
     }
     /**
      * @see Conjoon_Modules_Default_User_Model_User
      */
     require_once 'Conjoon/Modules/Default/User/Model/User.php';
     $userTable = new Conjoon_Modules_Default_User_Model_User();
     // check here if the username exists
     if ($cookieName != "" && $rememberMeToken != "") {
         $count = $userTable->getUserNameCount($cookieName, true);
     } else {
         $count = $userTable->getUserNameCount($userName);
     }
     // rowset! check count()... if this is > 1, 1..n users share the same
     // username, which is a bad thing
     if ($count > 1) {
         return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS, $userName, array('More than one record matches the supplied identity.'));
     } else {
         if ($count == 0) {
             return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, $userName, array('A record with the supplied identity could not be found.'));
         }
     }
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     $decorator = new Conjoon_BeanContext_Decorator($userTable);
     if ($cookieName != "" && $rememberMeToken != "") {
         $user = $decorator->getUserForHashedUsernameAndRememberMeTokenAsEntity($cookieName, $rememberMeToken);
     } else {
         $user = $decorator->getUserForUserNameCredentialsAsEntity($userName, md5($password));
     }
     // <code>null</code> means, that no user was found with the
     // username/ password combination
     if ($user === null) {
         return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID, $userName, array('Supplied credential is invalid.'));
     }
     // we have a match - generate a token and store it into the database
     $token = md5(uniqid(rand(), true));
     $where = $userTable->getAdapter()->quoteInto('id = ?', $user->getId());
     $time = time();
     $updData = array('auth_token' => $token, 'last_login' => $time);
     if ($cookieName == "" && $rememberMeToken == "") {
         $rememberMeToken = $rememberMe === true ? md5(uniqid(rand(), true)) : null;
         $updData['remember_me_token'] = $rememberMeToken;
         $user->setRememberMeToken($rememberMeToken);
     }
     $userTable->update($updData, $where);
     if (!$user->getLastLogin()) {
         $user->setLastLogin(-1);
     }
     $user->setAuthToken($token);
     // anything else from here on matches.
     return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $user, array('Authentication successful.'));
 }
コード例 #11
0
ファイル: Builder.php プロジェクト: ThorstenSuckow/conjoon
 /**
  * Returns either a cached list of email accounts for a user, or
  * the accounts out of the database.
  *
  * @param array $options An associative array with the following
  * key value/pairs:
  *   - userId: the id of the user to fetch all email accounts for
  * @param Conjoon_BeanContext_Decoratable $model
  *
  * @return Array an array with instances of
  * Conjoon_Modules_Groupware_Feeds_Account_Model_Account
  */
 protected function _build(array $options, Conjoon_BeanContext_Decoratable $model)
 {
     $userId = $options['userId'];
     /**
      * @see Conjoon_BeanContext_Decorator
      */
     require_once 'Conjoon/BeanContext/Decorator.php';
     $decoratedModel = new Conjoon_BeanContext_Decorator($model);
     $accounts = $decoratedModel->getAccountsForUserAsDto($userId);
     /**
      * @see Conjoon_Modules_Groupware_Email_ImapHelper
      */
     require_once 'Conjoon/Modules/Groupware/Email/ImapHelper.php';
     /**
      * @see Conjoon_Modules_Groupware_Email_Folder_Facade
      */
     require_once 'Conjoon/Modules/Groupware/Email/Folder/Facade.php';
     $facade = Conjoon_Modules_Groupware_Email_Folder_Facade::getInstance();
     for ($i = 0, $len = count($accounts); $i < $len; $i++) {
         $dto =& $accounts[$i];
         if ($dto->protocol == 'IMAP') {
             $folderMappings =& $dto->folderMappings;
             $folder = null;
             try {
                 $folder = $facade->getRootFolderForAccountId($dto, $userId);
                 $folder = $folder[0];
             } catch (Exception $e) {
                 // connection exception ignore
             }
             for ($a = 0, $lena = count($folderMappings); $a < $lena; $a++) {
                 if (!$folder) {
                     // connection exception, ignore
                     $folderMappings[$a]['globalName'] = "";
                     $folderMappings[$a]['delimiter'] = "";
                     $folderMappings[$a]['path'] = array();
                     continue;
                 }
                 try {
                     $folderMappings[$a]['delimiter'] = Conjoon_Modules_Groupware_Email_ImapHelper::getFolderDelimiterForImapAccount($dto);
                     $folderMappings[$a]['path'] = array_merge(array('root', $folder['id']), Conjoon_Modules_Groupware_Email_ImapHelper::splitFolderForImapAccount($folderMappings[$a]['globalName'], $dto));
                 } catch (Exception $e) {
                     // connection exception, ignore
                     $folderMappings[$a]['globalName'] = "";
                     $folderMappings[$a]['delimiter'] = "";
                     $folderMappings[$a]['path'] = array();
                 }
             }
         }
         if (!$dto->isOutboxAuth) {
             $dto->usernameOutbox = "";
             $dto->passwordOutbox = "";
         }
         $dto->passwordOutbox = str_pad("", strlen($dto->passwordOutbox), '*');
         $dto->passwordInbox = str_pad("", strlen($dto->passwordInbox), '*');
     }
     return $accounts;
 }
コード例 #12
0
 /**
  * Returns the email items based on the passed POST-parameters to the client.
  * Possible POST parameters are:
  *
  * start - the index in the datastore from where to read the first record
  * limit - the number of records to return
  * dir   - the sort direction, either ASC or DESC
  * sort  - the field to sort. Fields are based upon the properties of the
  *         Conjoon_Modules_Groupware_Email_ItemDto-class and have to be substituted
  *         to their appropriate representatives in the underlying datamodel.
  * groupwareEmailFoldersId - the id of the folder, for which the items should be loaded.
  *                           if this parameter is missing, all emails from all accounts
  *                           will be fetched
  * minDate - this argument is optional - if passed, all emails with a fetched_timestamp
  *           equal to or greater than minDate will be fetched
  *
  *
  * The assigned view variables are:
  *
  * items - an array with objects of Conjoon_Modules_Groupware_Email_ItemDto
  * totalCount - the total count of records available for the requested folder
  *              for this user, or the total count of latest emails for the
  *              user since minDate
  * version - the version property for Ext.ux.grid.BufferedStore
  * pendingItems - if a folder id other than 0 was supplied, the number of
  * pending items will be read out and assigned to this view-variable
  *
  */
 public function getEmailItemsAction()
 {
     require_once 'Conjoon/Modules/Groupware/Email/Item/Filter/Request.php';
     require_once 'Conjoon/Util/Array.php';
     require_once 'Conjoon/Keys.php';
     $auth = Zend_Registry::get(Conjoon_Keys::REGISTRY_AUTH_OBJECT);
     $userId = $auth->getIdentity()->getId();
     $CONTEXT_REQUEST_LATEST = Conjoon_Modules_Groupware_Email_Item_Filter_Request::CONTEXT_REQUEST_LATEST;
     $CONTEXT_REQUEST = Conjoon_Modules_Groupware_Email_Item_Filter_Request::CONTEXT_REQUEST;
     if (isset($_POST['minDate']) && !isset($_POST['groupwareEmailFoldersId'])) {
         $context = $CONTEXT_REQUEST_LATEST;
     } else {
         $context = $CONTEXT_REQUEST;
     }
     $itemRequestFilter = new Conjoon_Modules_Groupware_Email_Item_Filter_Request($_POST, $context);
     try {
         $filteredData = $itemRequestFilter->getProcessedData();
     } catch (Zend_Filter_Exception $e) {
         $this->view->success = true;
         $this->view->error = null;
         $this->view->items = array();
         $this->view->version = 1;
         $this->view->totalCount = 0;
         return;
     }
     $sortInfo = array('sort' => $filteredData['sort'], 'dir' => $filteredData['dir'], 'limit' => $filteredData['limit'], 'start' => $filteredData['start']);
     require_once 'Conjoon/BeanContext/Decorator.php';
     require_once 'Conjoon/Modules/Groupware/Email/Item/Filter/ItemResponse.php';
     $itemResponseFilter = new Conjoon_Modules_Groupware_Email_Item_Filter_ItemResponse(array(), Conjoon_Filter_Input::CONTEXT_RESPONSE);
     $pendingItems = -1;
     if ($context == $CONTEXT_REQUEST) {
         // 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($filteredData['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 ($facade->isRemoteFolder((int) $pathInfo['rootId'])) {
             /**
              * @see Conjoon_Modules_Groupware_Email_Item_ItemListRequestFacade
              */
             require_once 'Conjoon/Modules/Groupware/Email/Item/ItemListRequestFacade.php';
             $listFacade = Conjoon_Modules_Groupware_Email_Item_ItemListRequestFacade::getInstance();
             $itemData = $listFacade->getEmailItemList($pathInfo, $userId, $sortInfo, true);
             $this->view->success = true;
             $this->view->error = null;
             $this->view->items = $itemData['items'];
             $this->view->version = 1;
             $this->view->totalCount = $itemData['totalCount'];
             $this->view->pendingItems = $itemData['pendingItems'];
             return;
         }
         // get the number of emails currently available for this folder
         // and this user
         require_once 'Conjoon/Modules/Groupware/Email/Item/Model/Item.php';
         require_once 'Conjoon/Modules/Groupware/Email/Folder/Model/Folder.php';
         $folderModel = new Conjoon_Modules_Groupware_Email_Folder_Model_Folder();
         $itemModel = new Conjoon_Modules_Groupware_Email_Item_Model_Item();
         $totalCount = $folderModel->getItemCountForFolderAndUser($filteredData['groupwareEmailFoldersId'], $userId);
         if ($totalCount == 0) {
             $this->view->success = true;
             $this->view->error = null;
             $this->view->items = array();
             $this->view->version = 1;
             $this->view->totalCount = 0;
             $this->view->pendingItems = 0;
             return;
         }
         $decoratedModel = new Conjoon_BeanContext_Decorator($itemModel, $itemResponseFilter);
         $rows = $decoratedModel->getEmailItemsForAsDto($userId, $filteredData['groupwareEmailFoldersId'], $sortInfo);
         $pendingItems = $folderModel->getPendingCountForFolderAndUser($filteredData['groupwareEmailFoldersId'], $userId);
     } else {
         if ($context == $CONTEXT_REQUEST_LATEST) {
             require_once 'Conjoon/BeanContext/Decorator.php';
             require_once 'Conjoon/Modules/Groupware/Email/Item/Filter/ItemResponse.php';
             require_once 'Conjoon/Modules/Groupware/Email/Item/Model/Inbox.php';
             $itemInboxModel = new Conjoon_Modules_Groupware_Email_Item_Model_Inbox();
             $totalCount = $itemInboxModel->getLatestItemCount($userId, $filteredData['minDate']);
             if ($totalCount == 0) {
                 $this->view->success = true;
                 $this->view->error = null;
                 $this->view->items = array();
                 $this->view->version = 1;
                 $this->view->totalCount = 0;
                 return;
             }
             $decoratedModel = new Conjoon_BeanContext_Decorator($itemInboxModel, $itemResponseFilter);
             $rows = $decoratedModel->getLatestEmailItemsForAsDto($userId, $filteredData['minDate'], $sortInfo);
         }
     }
     $this->view->success = true;
     $this->view->error = null;
     $this->view->items = $rows;
     $this->view->pendingItems = $pendingItems;
     $this->view->version = 1;
     $this->view->totalCount = $totalCount;
 }
コード例 #13
0
 /**
  * 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;
 }
コード例 #14
0
 /**
  * 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;
 }