/**
  * Add a mailbox.
  */
 public function addAction()
 {
     if (!$this->getMailbox()) {
         $this->isEdit = $this->view->isEdit = false;
         $form = $this->getMailboxForm();
         $this->_mailbox = new \Entities\Mailbox();
         $this->getD2EM()->persist($this->getMailbox());
     } else {
         $this->isEdit = $this->view->isEdit = true;
         $this->view->mailbox = $this->getMailbox();
         $form = $this->getMailboxForm();
         $form->assignEntityToForm($this->getMailbox(), $this, $this->isEdit());
     }
     $this->view->quota_multiplier = $form->getFilterFileSizeMultiplier();
     if ($this->getDomain()) {
         $this->view->domain = $this->getDomain();
         if ($form->getElement('domain')) {
             $form->getElement('domain')->setValue($this->getDomain()->getId());
         }
     }
     $this->notify('mailbox', 'add', 'addPrepare', $this);
     if ($this->getRequest()->isPost()) {
         $this->notify('mailbox', 'add', 'addPrevalidate', $this);
         if ($form->isValid($_POST)) {
             $this->notify('mailbox', 'add', 'addPostvalidate', $this);
             if (!$this->isEdit()) {
                 if (!$this->getDomain() || $this->getDomain()->getId() != $form->getElement('domain')->getValue()) {
                     $this->_domain = $this->loadDomain($form->getElement('domain')->getValue());
                 }
                 // do we have available mailboxes?
                 if (!$this->getAdmin()->isSuper() && $this->getDomain()->getMaxMailboxes() != 0 && $this->getDomain()->getMailboxCount() >= $this->getDomain()->getMaxMailboxes()) {
                     $this->addMessage(_('You have used all of your allocated mailboxes.'), OSS_Message::ERROR);
                     return;
                 }
                 // is the mailbox address valid?
                 $username = sprintf("%s@%s", $form->getValue('local_part'), $this->_domain->getDomain());
                 if (!Zend_Validate::is($username, 'EmailAddress', array(1, null))) {
                     $form->getElement('local_part')->addError('Invalid email address.');
                     return;
                 }
                 // does a mailbox of the same name exist?
                 if (!$this->getD2EM()->getRepository("\\Entities\\Mailbox")->isUnique($username)) {
                     $this->addMessage(_('Mailbox already exists for') . " {$username}", OSS_Message::ERROR);
                     return;
                 }
                 $this->getMailbox()->setUsername($username);
                 $form->assignFormToEntity($this->getMailbox(), $this, $this->isEdit());
                 $this->getMailbox()->setDomain($this->getDomain());
                 $this->getMailbox()->setHomedir($this->_options['defaults']['mailbox']['homedir']);
                 $this->getMailbox()->setUid($this->_options['defaults']['mailbox']['uid']);
                 $this->getMailbox()->setGid($this->_options['defaults']['mailbox']['gid']);
                 $this->getMailbox()->formatHomedir($this->_options['defaults']['mailbox']['homedir']);
                 $this->getMailbox()->formatMaildir($this->_options['defaults']['mailbox']['maildir']);
                 $this->getMailbox()->setActive(1);
                 $this->getMailbox()->setDeletePending(false);
                 $this->getMailbox()->setCreated(new \DateTime());
                 $password = $this->getMailbox()->getPassword();
                 $this->getMailbox()->setPassword(OSS_Auth_Password::hash($password, ['pwhash' => $this->_options['defaults']['mailbox']['password_scheme'], 'pwsalt' => isset($this->_options['defaults']['mailbox']['password_salt']) ? $this->_options['defaults']['mailbox']['password_salt'] : null, 'pwdovecot' => isset($this->_options['defaults']['mailbox']['dovecot_pw_binary']) ? $this->_options['defaults']['mailbox']['dovecot_pw_binary'] : null, 'username' => $username]));
                 if ($this->_options['mailboxAliases'] == 1) {
                     $alias = new \Entities\Alias();
                     $alias->setAddress($this->getMailbox()->getUsername());
                     $alias->setGoto($this->getMailbox()->getUsername());
                     $alias->setDomain($this->getDomain());
                     $alias->setActive(1);
                     $alias->setCreated(new \DateTime());
                     $this->getD2EM()->persist($alias);
                 }
                 $this->getDomain()->setMailboxCount($this->getDomain()->getMailboxCount() + 1);
             } else {
                 $form->removeElement("local_part");
                 $form->assignFormToEntity($this->getMailbox(), $this, $this->isEdit());
                 $this->getMailbox()->setModified(new \DateTime());
             }
             //check quota
             if ($this->getDomain()->getMaxQuota() != 0) {
                 if ($this->getMailbox()->getQuota() <= 0 || $this->getMailbox()->getQuota() > $this->getDomain()->getMaxQuota()) {
                     $this->getMailbox()->setQuota($this->getDomain()->getQuota());
                     $this->addMessage(_("Mailbox quota set to ") . $this->getDomain()->getQuota(), OSS_Message::ALERT);
                 }
             }
             $this->log($this->isEdit() ? \Entities\Log::ACTION_MAILBOX_EDIT : \Entities\Log::ACTION_MAILBOX_ADD, "{$this->getAdmin()->getFormattedName()} " . ($this->isEdit() ? ' edited' : ' added') . " mailbox {$this->getMailbox()->getUsername()}");
             $this->notify('mailbox', 'add', 'addPreflush', $this);
             $this->getD2EM()->flush();
             $this->notify('mailbox', 'add', 'addPostflush', $this, ['options' => $this->_options]);
             if ($form->getValue('welcome_email')) {
                 if (!$this->_sendSettingsEmail($form->getValue('cc_welcome_email') ? $form->getValue('cc_welcome_email') : false, $password, true)) {
                     $this->addMessage(_('Could not sent welcome email'), OSS_Message::ALERT);
                 }
             }
             if ($this->getParam("did", false)) {
                 $this->getSessionNamespace()->domain = $this->getDomain();
             }
             $this->notify('mailbox', 'add', 'addFinish', $this);
             $this->addMessage(_("You have successfully added/edited the mailbox record."), OSS_Message::SUCCESS);
             $this->redirect('mailbox/list');
         }
     }
 }
 /**
  * Unserialize archive data serialized structure.
  *
  * Function unserialize data array. And by create mailbox object form parameters.
  * Then it creates mailbox preferences. Create aliases and their preferences, iterates
  * through inAliases and if aliases exists append their got field by mailbox email.
  * Then it persists mailbox and aliases set their domains, increase domain mailbox / alias counters.
  * Persist all preferences.
  *
  * Returns restored mailbox and aliases array. Array format:
  *
  * $return = [ 'mailbox' => $mailbox
  *       'aliases' => [
  *           1 => $alias1,
  *           2 => $alias2,
  *           .....
  *       ]
  *  ]
  *
  * @param string $data Serialized mailbox structure from archive data field.
  * @return array;
  */
 private function _unserialzeMailbox($data)
 {
     $debug = $this->getParam('debug', false);
     $this->getD2EM()->flush();
     $data = unserialize($data);
     if ($debug) {
         echo "[DEBUG] Unserialising {$data['mailbox']['params']['username']}\n";
     }
     $params = $data['mailbox']['params'];
     $mailbox = new \Entities\Mailbox();
     $mailbox->setUsername($params['username']);
     $mailbox->setPassword($params['password']);
     $mailbox->setName($params['name']);
     $mailbox->setAltEmail($params['alt_email']);
     $mailbox->setQuota($params['quota']);
     $mailbox->setLocalPart($params['local_part']);
     $mailbox->setActive($params['active']);
     $mailbox->setAccessRestriction($params['access_restriction']);
     $mailbox->setHomeDir($params['homedir']);
     $mailbox->setMailDir($params['maildir']);
     $mailbox->setUid($params['uid']);
     $mailbox->setGid($params['gid']);
     $mailbox->setHomedirSize($params['homedir_size']);
     $mailbox->setMaildirSize($params['maildir_size']);
     $mailbox->setCreated(new \DateTime($params['created']['date']));
     $mailbox->setSizeAt(new \DateTime($params['size_at']['date']));
     $mailbox->setModified(new \DateTime());
     if (!($domain = $this->getD2EM()->getRepository("\\Entities\\Domain")->find($params['domain']['id']))) {
         $this->getLogger()->alert("ArchiveController::_unserialzeMailbox -> domain not found for {$data['mailbox']['params']['username']}");
         throw new ViMbAdmin_Exception("Domain was not found");
     }
     $mailbox->setDomain($domain);
     $this->getD2EM()->persist($mailbox);
     $this->getD2EM()->flush();
     if (isset($data['mailbox_prefrences'])) {
         if ($debug) {
             echo "[DEBUG] Unserialising preferences for {$data['mailbox']['params']['username']}\n";
         }
         foreach ($data['mailbox_prefrences'] as $mprefs) {
             $pr = $this->getD2EM()->getUnitOfWork()->createEntity($mprefs['className'], $mprefs['params']);
             $pr->setMailbox($mailbox);
             if ($debug) {
                 echo "[DEBUG]        {$pr->getAttribute()} {$pr->getOp()} {$pr->getValue()}\n";
             }
             $this->getD2EM()->persist($pr);
             $this->getD2EM()->flush();
         }
     }
     if (isset($this->_options['mailboxAliases']) && $this->_options['mailboxAliases']) {
         $alias = new \Entities\Alias();
         $alias->setAddress($mailbox->getUsername());
         $alias->setGoto($mailbox->getUsername());
         $alias->setActive(1);
         $alias->setCreated(new \Datetime());
         $alias->setDomain($domain);
         $this->getD2EM()->persist($alias);
         $this->getD2EM()->flush();
     }
     /*
     
         The code to archive aliases is buggy right now so we've disabled this.
     
     if( isset( $data["aliases"] ) )
     { 
         if( $debug ) echo "[DEBUG] Unserialising aliases for {$data['mailbox']['params']['username']}\n";
         foreach( $data["aliases"] as $idx => $dalias )
         {
             if( !isset( $dalias['params'] ) || !isset( $dalias['className'] ) )
                 continue;
             
             $uow->clear();
             $alias = $uow->createEntity( $dalias['className'], $dalias['params'] );
             $alias->setCreated( new \DateTime( $dalias['params']['created']['date'] ) );
             $alias->setModified( new \DateTime() );
             $domains[] = $dalias['params']['domain']['id'];
             $newEnts[] = $alias;
     
             if( $debug ) echo "[DEBUG]    {$alias->getAddress()} => {$alias->getGoto()}\n";
     
             if( isset( $data["alias_prefrences"][$idx] ) )
             {
                 foreach( $data["alias_prefrences"][$idx] as $ap )
                 {
                     if( !isset( $ap['params'] ) || !isset( $ap['className'] ) )
                         continue;
                     
                     $uow->clear();
                     $pr = $uow->createEntity( $ap['className'], $ap['params'] );
                     $pr->setAlias( $alias );
                     $newprefs[] = $pr;
                     if( $debug ) echo "[DEBUG]        {$pr->getAttribute()} {$pr->getOp()} {$pr->getValue()}\n";
                 }
             }
         }
     }
     
     if( isset( $data["inAliases"] ) )
     {
         if( $debug ) echo "[DEBUG] Unserialising 'in' aliases for {$data['mailbox']['params']['username']}\n";
     
         foreach( $data["inAliases"] as $idx => $dalias )
         {
             if( !isset( $dalias['params'] ) || !isset( $dalias['className'] ) )
                 continue;
     
             $params = $dalias['params'];
             $alias = $this->getD2EM()->getRepository( "\\Entities\\Alias" )->find( $params['id'] );
             
             //FIXME: Now we skipping if alias was removed.
             if( $alias )
             {
                 $alias->setGoto( $alias->getGoto() . "," . $mailbox->getUsername() );
                 if( $debug ) echo "[DEBUG]    {$alias->getAddress()} => {$alias->getGoto()}\n";
             }
         }
     }
     */
     if ($debug) {
         echo "\n";
     }
     return ['mailbox' => $mailbox, 'aliases' => []];
 }