Exemplo n.º 1
0
 /**
  * import single record (create password if in data)
  *
  * @param Tinebase_Record_Abstract $_record
  * @param string $_resolveStrategy
  * @param array $_recordData
  * @return Tinebase_Record_Interface
  * @throws Tinebase_Exception_Record_Validation
  */
 protected function _importRecord($_record, $_resolveStrategy = NULL, $_recordData = array())
 {
     if ($_record instanceof Tinebase_Model_FullUser && $this->_controller instanceof Admin_Controller_User) {
         $record = $_record;
         // create valid login name
         if (!isset($record->accountLoginName)) {
             $record->accountLoginName = Tinebase_User::getInstance()->generateUserName($record, $this->_options['userNameSchema']);
         }
         // add prefix to login name if given
         if (!empty($this->_options['accountLoginNamePrefix'])) {
             $record->accountLoginName = $this->_options['accountLoginNamePrefix'] . $record->accountLoginName;
         }
         // add home dir if empty and prefix is given (append login name)
         if (empty($record->accountHomeDirectory) && !empty($this->_options['accountHomeDirectoryPrefix'])) {
             $record->accountHomeDirectory = $this->_options['accountHomeDirectoryPrefix'] . $record->accountLoginName;
         }
         // create email address if accountEmailDomain if given
         if (empty($record->accountEmailAddress) && !empty($this->_options['accountEmailDomain'])) {
             $record->accountEmailAddress = $record->accountLoginName . '@' . $this->_options['accountEmailDomain'];
         }
         if (!empty($this->_options['samba'])) {
             $this->_addSambaSettings($record);
         }
         Tinebase_Event::fireEvent(new Admin_Event_BeforeImportUser($record, $this->_options));
         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($record->toArray(), true));
         }
         // generate passwd (use accountLoginName or password from options or password from csv in this order)
         $password = $record->accountLoginName;
         if (!empty($this->_options['password'])) {
             $password = $this->_options['password'];
         }
         if (isset($_recordData['password']) && !empty($_recordData['password'])) {
             $password = $_recordData['password'];
         }
         $this->_addEmailUser($record, $password);
         //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Adding record: ' . print_r($record->toArray(), TRUE));
         // try to create record with password
         if ($record->isValid()) {
             if (!$this->_options['dryrun']) {
                 $record = $this->_controller->create($record, $password, $password);
             } else {
                 $this->_importResult['results']->addRecord($record);
             }
             $this->_importResult['totalcount']++;
         } else {
             Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Record invalid: ' . print_r($record->getValidationErrors(), TRUE));
             throw new Tinebase_Exception_Record_Validation('Imported record is invalid.');
         }
     } else {
         $record = parent::_importRecord($_record, $_resolveStrategy, $_recordData);
     }
     return $record;
 }
Exemplo n.º 2
0
 public function pay($payment)
 {
     $totalBrutto = $this->__get('open_sum');
     if ($payment->__get('amount') == $totalBrutto) {
         $this->__set('payment_state', 'PAYED');
         $this->__set('open_sum', 0);
         $this->__set('payed_sum', $totalBrutto);
     } elseif ($payment->__get('amount') == 0) {
         $this->__set('payment_state', 'TOBEPAYED');
     } elseif ($payment->__get('amount') < $totalBrutto) {
         $this->__set('payment_state', 'PARTLYPAYED');
         $this->__set('open_sum', $totalBrutto - $payment->__get('amount'));
         $this->__set('payed_sum', $payment->__get('amount'));
     }
     Billing_Controller_OpenItem::getInstance()->update($this);
     Tinebase_Event::fireEvent(new Billing_Events_OpenItemPayed($payment, $this));
 }
 /**
  * import single record (create password if in data)
  *
  * @param Tinebase_Record_Abstract $_record
  * @param string $_resolveStrategy
  * @param array $_recordData
  * @return Tinebase_Record_Interface
  * @throws Tinebase_Exception_Record_Validation
  */
 protected function _importRecord($_record, $_resolveStrategy = NULL, $_recordData = array())
 {
     if ($_record instanceof Tinebase_Model_FullUser && $this->_controller instanceof Admin_Controller_User) {
         $record = $_record;
         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' record Data' . print_r($_recordData, true));
         }
         if (isset($_recordData['smtpUser'])) {
             $record->smtpUser = new Tinebase_Model_EmailUser($_recordData['smtpUser']);
         }
         if (isset($_recordData['imapUser'])) {
             $record->imapUser = new Tinebase_Model_EmailUser($_recordData['imapUser']);
         }
         if (isset($_recordData['samba']) && (!isset($this->_options['samba']) || empty($this->_options['samba']))) {
             $this->_options['samba'] = $_recordData['samba'];
         }
         if (isset($_recordData['accountHomeDirectoryPrefix'])) {
             $this->_options['accountHomeDirectoryPrefix'] = $_recordData['accountHomeDirectoryPrefix'];
         }
         $password = $record->applyOptionsAndGeneratePassword($this->_options, isset($_recordData['password']) ? $_recordData['password'] : NULL);
         Tinebase_Event::fireEvent(new Admin_Event_BeforeImportUser($record, $this->_options));
         // try to create record with password
         if ($record->isValid()) {
             if (!$this->_options['dryrun']) {
                 $record = $this->_controller->create($record, $password, $password);
             } else {
                 $this->_importResult['results']->addRecord($record);
             }
             $this->_importResult['totalcount']++;
         } else {
             Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Record invalid: ' . print_r($record->getValidationErrors(), TRUE));
             throw new Tinebase_Exception_Record_Validation('Imported record is invalid.');
         }
     } else {
         $record = parent::_importRecord($_record, $_resolveStrategy, $_recordData);
     }
     return $record;
 }
 /**
  * fire event to allow other applications do some work before billing
  */
 protected function _firePrebillEvent()
 {
     $event = new Sales_Event_BeforeBillContract();
     $event->contract = $this->_currentBillingContract;
     $event->date = $this->_currentBillingDate;
     Tinebase_Event::fireEvent($event);
 }
 /**
  * set all groups an user is member of
  *
  * @param  mixed  $_usertId   the account as integer or Tinebase_Model_User
  * @param  mixed  $_groupIds
  * @return array
  */
 public function setGroupMembershipsInSqlBackend($_userId, $_groupIds)
 {
     if ($_groupIds instanceof Tinebase_Record_RecordSet) {
         $_groupIds = $_groupIds->getArrayOfIds();
     }
     if (count($_groupIds) === 0) {
         throw new Tinebase_Exception_InvalidArgument('user must belong to at least one group');
     }
     $userId = Tinebase_Model_user::convertUserIdToInt($_userId);
     $groupMemberships = $this->getGroupMemberships($userId);
     $removeGroupMemberships = array_diff($groupMemberships, $_groupIds);
     $addGroupMemberships = array_diff($_groupIds, $groupMemberships);
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' current groupmemberships: ' . print_r($groupMemberships, true));
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' new groupmemberships: ' . print_r($_groupIds, true));
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' added groupmemberships: ' . print_r($addGroupMemberships, true));
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' removed groupmemberships: ' . print_r($removeGroupMemberships, true));
     }
     foreach ($addGroupMemberships as $groupId) {
         $this->addGroupMemberInSqlBackend($groupId, $userId);
     }
     foreach ($removeGroupMemberships as $groupId) {
         $this->removeGroupMemberFromSqlBackend($groupId, $userId);
     }
     $event = new Tinebase_Group_Event_SetGroupMemberships(array('user' => $_userId, 'addedMemberships' => $addGroupMemberships, 'removedMemberships' => $removeGroupMemberships));
     Tinebase_Event::fireEvent($event);
     return $this->getGroupMemberships($userId);
 }
 /**
  * create user
  *
  * @param  Tinebase_Model_FullUser  $_account           the account
  * @param  string                     $_password           the new password
  * @param  string                     $_passwordRepeat  the new password again
  * @return Tinebase_Model_FullUser
  */
 public function create(Tinebase_Model_FullUser $_user, $_password, $_passwordRepeat)
 {
     $this->checkRight('MANAGE_ACCOUNTS');
     // avoid forging accountId, gets created in backend
     unset($_user->accountId);
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Create new user ' . $_user->accountLoginName);
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_user->toArray(), TRUE));
     }
     $this->_checkLoginNameExistance($_user);
     $this->_checkLoginNameLength($_user);
     $this->_checkPrimaryGroupExistance($_user);
     if ($_password != $_passwordRepeat) {
         throw new Admin_Exception("Passwords don't match.");
     } else {
         if (empty($_password)) {
             $_password = '';
             $_passwordRepeat = '';
         }
     }
     Tinebase_User::getInstance()->checkPasswordPolicy($_password, $_user);
     try {
         $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
         if (Tinebase_Application::getInstance()->isInstalled('Addressbook') === true) {
             $contact = $this->createOrUpdateContact($_user);
             $_user->contact_id = $contact->getId();
         }
         Tinebase_Timemachine_ModificationLog::setRecordMetaData($_user, 'create');
         $user = $this->_userBackend->addUser($_user);
         // make sure primary groups is in the list of groupmemberships
         $groups = array_unique(array_merge(array($user->accountPrimaryGroup), (array) $_user->groups));
         Admin_Controller_Group::getInstance()->setGroupMemberships($user, $groups);
         Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
     } catch (Exception $e) {
         Tinebase_TransactionManager::getInstance()->rollBack();
         Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' ' . $e->getMessage());
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $e->getTraceAsString());
         }
         throw $e;
     }
     $event = new Admin_Event_AddAccount(array('account' => $user));
     Tinebase_Event::fireEvent($event);
     $this->setAccountPassword($user, $_password, $_passwordRepeat);
     return $user;
 }
 /**
  * delete a user
  *
  * @param  mixed  $_userId
  * @return Tinebase_Model_FullUser  the delete user
  */
 public function deleteUserInSqlBackend($_userId)
 {
     if ($_userId instanceof Tinebase_Model_FullUser) {
         $user = $_userId;
     } else {
         $user = $this->getFullUserById($_userId);
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Deleting user' . $user->accountLoginName);
     }
     $event = new Tinebase_Event_User_DeleteAccount(Tinebase_Config::getInstance()->get(Tinebase_Config::ACCOUNT_DELETION_EVENTCONFIGURATION, new Tinebase_Config_Struct())->toArray());
     $event->account = $user;
     Tinebase_Event::fireEvent($event);
     $accountsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'accounts'));
     $groupMembersTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'group_members'));
     $roleMembersTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'role_accounts'));
     try {
         $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($this->_db);
         $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('account_id') . ' = ?', $user->getId()));
         $groupMembersTable->delete($where);
         $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('account_id') . ' = ?', $user->getId()), $this->_db->quoteInto($this->_db->quoteIdentifier('account_type') . ' = ?', Tinebase_Acl_Rights::ACCOUNT_TYPE_USER));
         $roleMembersTable->delete($where);
         $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' = ?', $user->getId()));
         $accountsTable->delete($where);
         Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
     } catch (Exception $e) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' error while deleting account ' . $e->__toString());
         }
         Tinebase_TransactionManager::getInstance()->rollBack();
         throw $e;
     }
     return $user;
 }
Exemplo n.º 8
0
 public function onPaymentCreated($payment)
 {
     if (!$payment->isBookingAllowed()) {
         return;
     }
     $cKto = $payment->getForeignId('account_system_id_haben');
     $dKto = $payment->getForeignId('account_system_id');
     // multi create bookings
     if ($dKto && $cKto) {
         $booking = new Billing_Model_Booking(null, true);
         $booking->__set('booking_date', new Zend_Date($payment->__get('payment_date')));
         $booking->__set('booking_text', $payment->__get('usage'));
         $booking->__set('erp_context_id', $payment->__get('erp_context_id'));
         $booking->__set('receipt_unique_nr', ' ');
         $booking->__set('receipt_id', $payment->getForeignId('receipt_id'));
         $booking->__set('donation_id', $payment->getForeignId('donation_id'));
         $booking->__set('is_cancelled', $payment->__get('is_cancelled'));
         $booking->__set('is_cancellation', $payment->__get('is_cancellation'));
         $value = abs($payment->__get('amount'));
         $creditValue = $value;
         $debitValue = $value;
         $credits = array(array('kto' => $cKto, 'value' => $value, 'debitor' => $payment->getForeignIdBreakNull('debitor_id')));
         if ($payment->__get('is_return_debit')) {
             $debitReturnFee = abs($payment->__get('return_inquiry_fee'));
             $debitReturnFeeAccount = Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::FIBU_KTO_DTA_RETURN_FEE);
             $debitValue -= $debitReturnFee;
             $debits = array(array('kto' => $dKto, 'value' => $debitValue, 'debitor' => $payment->getForeignIdBreakNull('debitor_id')));
             $debits[] = array('kto' => $debitReturnFeeAccount, 'value' => $debitReturnFee, 'debitor' => $payment->getForeignIdBreakNull('debitor_id'));
         } else {
             $debits = array(array('kto' => $dKto, 'value' => $value, 'debitor' => $payment->getForeignIdBreakNull('debitor_id')));
         }
         $data = array('credits' => $credits, 'debits' => $debits);
         $booking = Billing_Controller_Booking::getInstance()->create($booking);
         Billing_Controller_AccountBooking::getInstance()->multiCreateAccountBookings($booking->getId(), $data);
         Tinebase_Event::fireEvent(new Billing_Events_PaymentBooked($payment, $booking));
     }
 }
Exemplo n.º 9
0
 /**
  * 
  * Completely reverse an invoice by creating a credit receipt
  * @param string $receiptId
  */
 public function reverseInvoice($receiptId, $orderPositionData)
 {
     \org\sopen\dev\DebugLogger::openLogFileOverwrite(CSopen::instance()->getCustomerPath() . '/conf/logs/revinvoice.log');
     if (!is_array($orderPositionData)) {
         $orderPositionData = Zend_Json::decode($orderPositionData);
     }
     $rController = Billing_Controller_Receipt::getInstance();
     $receipt = $rController->get($receiptId);
     if ($receipt->__get('receipt_state') !== 'VALID') {
         throw new Billing_Exception_Receipt('Receipt cannot be reverted twice');
     }
     $order = $receipt->getForeignRecord('order_id', $this);
     $rpController = Billing_Controller_ReceiptPosition::getInstance();
     $opController = Billing_Controller_OrderPosition::getInstance();
     $receiptPositions = $rpController->getByReceiptId($receiptId);
     $creditReceipt = Billing_Model_Receipt::createCredit();
     $creditReceipt->__set('order_id', $order->getId());
     $creditReceipt->__set('invoice_nr', $receipt->__get('invoice_nr'));
     $creditReceipt->__set('credit_date', $receipt->__get('invoice_date'));
     $creditReceipt->__set('invoice_date', $receipt->__get('invoice_date'));
     // take same payment method for credit receipt
     $creditReceipt->__set('payment_method_id', $receipt->getForeignId('payment_method_id'));
     $creditReceipt->__set('is_cancellation', true);
     $receipt->__set('is_cancelled', true);
     \org\sopen\dev\DebugLogger::log('RECHNUNG ' . print_r($receipt, true));
     $creditReceipt = $rController->create($creditReceipt);
     $creditReceipt = $rController->get($creditReceipt->getId());
     $countPos = count($receiptPositions);
     $creditPositions = array();
     $opCount = count($orderPositionData);
     $aOrderPosData = null;
     if (is_array($orderPositionData)) {
         $aOrderPosData = org\sopen\app\util\arrays\ArrayHelper::getIndexedWithPropertyFromList($orderPositionData, 'id');
     }
     $partReverse = false;
     foreach ($receiptPositions as $invoicePosition) {
         //print_r($invoicePosition);
         if (is_array($aOrderPosData) && $opCount > 0 && (!array_key_exists($invoicePosition->getId(), $aOrderPosData) || !$aOrderPosData[$invoicePosition->getId()]['invert_amount'])) {
             $partReverse = true;
             continue;
         }
         $creditPosition = clone $invoicePosition;
         $creditPosition->__set('id', null);
         $creditPosition->__set('position_nr', ++$countPos);
         $creditPosition->__set('name', $creditPosition->__get('name') . ' -STORNO');
         if (is_array($aOrderPosData) && array_key_exists($invoicePosition->getId(), $aOrderPosData) && $aOrderPosData[$invoicePosition->getId()]['invert_amount']) {
             $creditPosition->__set('amount', $aOrderPosData[$invoicePosition->getId()]['invert_amount']);
         }
         $opController->invert($creditPosition);
         $creditPosition->flatten();
         $creditPositions[] = $opController->create($creditPosition);
     }
     $rpController->addOrderPositions($creditReceipt, $creditPositions);
     $creditReceipt = Billing_Controller_Receipt::getInstance()->get($creditReceipt->getId());
     /*
     		 
     		<value>REVERTED</value>
     		<value>PARTLYREVERTED</value>
     		<value>ISREVERSION</value>
     		<value>ISPARTREVERSION</value>
     */
     $receipt->__set('receipt_state', 'REVERTED');
     $creditReceipt->__set('receipt_state', 'ISREVERSION');
     $receipt->__set('revision_receipt_id', $creditReceipt->getId());
     $creditReceipt->__set('revision_receipt_id', $receipt->getId());
     //$creditReceipt->__set('payment_state', 'PAYED');
     $creditReceipt->__set('open_sum', -1 * (double) $receipt->__get('open_sum'));
     //$creditReceipt->__set('payed_sum',$creditReceipt->__get('total_brutto'));
     $creditReceipt->payTotal();
     if ($partReverse) {
         $receipt->__set('payment_state', 'PARTLYPAYED');
         $receipt->__set('receipt_state', 'PARTLYREVERTED');
         $creditReceipt->__set('receipt_state', 'ISPARTREVERSION');
         $receipt->payValue($creditReceipt->__get('total_brutto'));
     } else {
         try {
             $receipt->payTotal();
         } catch (Exception $e) {
             // @todo: silent failure: check OK
         }
     }
     $creditReceipt->__set('donation_id', $receipt->getForeignId('donation_id'));
     $creditReceipt->__set('reversion_record_id', $receipt->getId());
     $creditReceipt->__set('revision_receipt_id', $receipt->getId());
     $receipt->__set('reversion_record_id', $creditReceipt->getId());
     $receipt->__set('revision_receipt_id', $creditReceipt->getId());
     $receipt = $rController->update($receipt);
     $tags = $receipt->__get('tags');
     if ($tags) {
         $creditReceipt->__set('tags', $tags->toArray());
     }
     $creditReceipt = $rController->update($creditReceipt);
     \org\sopen\dev\DebugLogger::log('RECHNUNG_update ' . print_r($receipt, true));
     \org\sopen\dev\DebugLogger::log('GUTSCHRIFT ' . print_r($creditReceipt, true));
     Tinebase_Event::fireEvent(new Billing_Events_BillableReceiptCreated($creditReceipt));
     Tinebase_Event::fireEvent(new Billing_Events_BillableReceiptReverted($receipt, $creditReceipt));
     \org\sopen\dev\DebugLogger::close();
     return $creditReceipt;
 }
 /**
  * set new password & credentials
  * 
  * @param string $_username
  * @param string $_password
  */
 protected function _setCredentials($_username, $_password)
 {
     Tinebase_User::getInstance()->setPassword(Tinebase_Core::getUser(), $_password, true, false);
     $oldCredentialCache = Tinebase_Core::getUserCredentialCache();
     // update credential cache
     $credentialCache = Tinebase_Auth_CredentialCache::getInstance()->cacheCredentials($_username, $_password);
     Tinebase_Core::set(Tinebase_Core::USERCREDENTIALCACHE, $credentialCache);
     $event = new Tinebase_Event_User_ChangeCredentialCache($oldCredentialCache);
     Tinebase_Event::fireEvent($event);
     $this->_pwChanged = true;
 }
 /**
  * creates a new container
  *
  * @param   Tinebase_Model_Container $_container the new container
  * @param   Tinebase_Record_RecordSet $_grants the grants for the new folder 
  * @param   bool  $_ignoreAcl
  * @return  Tinebase_Model_Container the newly created container
  * @throws  Tinebase_Exception_Record_Validation
  * @throws  Tinebase_Exception_AccessDenied
  */
 public function addContainer(Tinebase_Model_Container $_container, $_grants = NULL, $_ignoreAcl = FALSE)
 {
     $_container->isValid(TRUE);
     if ($_ignoreAcl !== TRUE) {
         switch ($_container->type) {
             case Tinebase_Model_Container::TYPE_PERSONAL:
                 // is the user allowed to create personal container?
                 break;
             case Tinebase_Model_Container::TYPE_SHARED:
                 $application = Tinebase_Application::getInstance()->getApplicationById($_container->application_id);
                 $appName = (string) $application;
                 $manageRight = FALSE;
                 // check for MANAGE_SHARED_FOLDERS right
                 $appAclClassName = $appName . '_Acl_Rights';
                 if (@class_exists($appAclClassName)) {
                     $appAclObj = call_user_func(array($appAclClassName, 'getInstance'));
                     $allRights = $appAclObj->getAllApplicationRights();
                     if (in_array(Tinebase_Acl_Rights::MANAGE_SHARED_FOLDERS, $allRights)) {
                         $manageRight = Tinebase_Core::getUser()->hasRight($appName, Tinebase_Acl_Rights::MANAGE_SHARED_FOLDERS);
                     }
                 }
                 if (!$manageRight && !Tinebase_Core::getUser()->hasRight($appName, Tinebase_Acl_Rights::ADMIN)) {
                     throw new Tinebase_Exception_AccessDenied('Permission to add shared container denied.');
                 }
                 break;
             default:
                 throw new Tinebase_Exception_InvalidArgument('Can add personal or shared folders only when ignoring ACL.');
                 break;
         }
     }
     if (!empty($_container->owner_id)) {
         $accountId = $_container->owner_id instanceof Tinebase_Model_User ? $_container->owner_id->getId() : $_container->owner_id;
     } else {
         $accountId = is_object(Tinebase_Core::getUser()) ? Tinebase_Core::getUser()->getId() : NULL;
     }
     if ($_grants === NULL || count($_grants) == 0) {
         $creatorGrants = array('account_id' => $accountId, 'account_type' => Tinebase_Acl_Rights::ACCOUNT_TYPE_USER, Tinebase_Model_Grants::GRANT_READ => true, Tinebase_Model_Grants::GRANT_ADD => true, Tinebase_Model_Grants::GRANT_EDIT => true, Tinebase_Model_Grants::GRANT_DELETE => true, Tinebase_Model_Grants::GRANT_EXPORT => true, Tinebase_Model_Grants::GRANT_SYNC => true, Tinebase_Model_Grants::GRANT_ADMIN => true);
         if ($_container->type === Tinebase_Model_Container::TYPE_SHARED && !Tinebase_Config::getInstance()->get(Tinebase_Config::ANYONE_ACCOUNT_DISABLED)) {
             // add all grants to creator and
             // add read grants to any other user
             $grants = new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array($creatorGrants, array('account_id' => '0', 'account_type' => Tinebase_Acl_Rights::ACCOUNT_TYPE_ANYONE, Tinebase_Model_Grants::GRANT_READ => true, Tinebase_Model_Grants::GRANT_EXPORT => true, Tinebase_Model_Grants::GRANT_SYNC => true)), TRUE);
         } else {
             // add all grants to creator only
             $grants = new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array($creatorGrants), TRUE);
         }
     } else {
         $grants = $_grants;
     }
     $event = new Tinebase_Event_Container_BeforeCreate();
     $event->accountId = $accountId;
     $event->container = $_container;
     $event->grants = $grants;
     Tinebase_Event::fireEvent($event);
     Tinebase_Timemachine_ModificationLog::setRecordMetaData($_container, 'create');
     $container = $this->create($_container);
     $this->setGrants($container->getId(), $grants, TRUE, FALSE);
     return $container;
 }
Exemplo n.º 12
0
 /**
  * delete multiple groups
  *
  * @param   array $_groupIds
  * @return  void
  */
 public function delete($_groupIds)
 {
     $this->checkRight('MANAGE_ACCOUNTS');
     // check default user group / can't delete this group
     $defaultUserGroup = Tinebase_Group::getInstance()->getDefaultGroup();
     if (in_array($defaultUserGroup->getId(), $_groupIds)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Can\'t delete default group: ' . $defaultUserGroup->name);
         foreach ($_groupIds as $key => $value) {
             if ($value == $defaultUserGroup->getId()) {
                 unset($_groupIds[$key]);
             }
         }
     }
     if (empty($_groupIds)) {
         return;
     }
     $eventBefore = new Admin_Event_BeforeDeleteGroup();
     $eventBefore->groupIds = $_groupIds;
     Tinebase_Event::fireEvent($eventBefore);
     if (Tinebase_Application::getInstance()->isInstalled('Addressbook') === true) {
         $listIds = array();
         foreach ($_groupIds as $groupId) {
             $group = $this->get($groupId);
             if (!empty($group->list_id)) {
                 $listIds[] = $group->list_id;
             }
         }
         if (!empty($listIds)) {
             $listBackend = new Addressbook_Backend_List();
             $listBackend->delete($listIds);
         }
     }
     Tinebase_Group::getInstance()->deleteGroups($_groupIds);
     $event = new Admin_Event_DeleteGroup();
     $event->groupIds = $_groupIds;
     Tinebase_Event::fireEvent($event);
 }
Exemplo n.º 13
0
 /**
  * create user
  *
  * @param  Tinebase_Model_FullUser  $_account 		  the account
  * @param  string 					$_password 		  the new password
  * @param  string 					$_passwordRepeat  the new password again
  * @return Tinebase_Model_FullUser
  */
 public function create(Tinebase_Model_FullUser $_user, $_password, $_passwordRepeat)
 {
     $this->checkRight('MANAGE_ACCOUNTS');
     // avoid forging accountId, get's created in backend
     unset($_user->accountId);
     try {
         $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
         if (Tinebase_Application::getInstance()->isInstalled('Addressbook') === true) {
             $contact = $this->createOrUpdateContact($_user);
             $_user->contact_id = $contact->getId();
         }
         $user = $this->_userBackend->addUser($_user);
         // make sure primary groups is in the list of groupmemberships
         $groups = array_unique(array_merge(array($user->accountPrimaryGroup), (array) $_user->groups));
         Admin_Controller_Group::getInstance()->setGroupMemberships($user, $groups);
         Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
     } catch (Exception $e) {
         Tinebase_TransactionManager::getInstance()->rollBack();
         Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' ' . $e->getMessage());
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $e->getTraceAsString());
         }
         throw $e;
     }
     $event = new Admin_Event_AddAccount(array('account' => $user));
     Tinebase_Event::fireEvent($event);
     if (!empty($_password) && !empty($_passwordRepeat)) {
         $this->setAccountPassword($user, $_password, $_passwordRepeat);
     }
     return $user;
 }
Exemplo n.º 14
0
 public function payOpenItem($openItemId, $payment, $amount = 0)
 {
     $openItem = $this->get($openItemId);
     $receipt = $openItem->getForeignRecord('receipt_id', Billing_Controller_Receipt::getInstance());
     $pAmount = abs((double) $payment->__get('amount'));
     if ($amount == 0) {
         $amount = $pAmount;
     }
     $payedSum = abs((double) $openItem->__get('payed_sum'));
     $openSum = abs((double) $openItem->__get('open_sum'));
     if ($amount < $openSum) {
         $openItem->__set('state', 'PARTLYOPEN');
         $receipt->__set('payment_state', 'PARTLYPAYED');
     } else {
         $openItem->__set('state', 'DONE');
         $receipt->__set('payment_state', 'PAYED');
     }
     $openSum -= min($amount, $openSum);
     $payedSum += min($amount, $openSum);
     $openItem->__set('open_sum', $openSum);
     $openItem->__set('payed_sum', $payedSum);
     $receipt->__set('open_sum', $openSum);
     $receipt->__set('payed_sum', $payedSum);
     // payment is optional: as open item can be nulled with contra receipt (bill <-->credit)
     if ($payment) {
         $paymentId = $payment->getId();
         $openItem->__set('payment_id', $paymentId);
     } else {
         $payment = Billing_Controller_Payment::getInstance()->getEmptyPayment();
     }
     $receipt = Billing_Controller_Receipt::getInstance()->update($receipt);
     $this->update($openItem);
     Tinebase_Event::fireEvent(new Billing_Events_OpenItemPayed($payment, $openItem));
 }
Exemplo n.º 15
0
 /**
  * event handler function
  *
  * all events get routed through this function
  *
  * @param Tinebase_Event_Abstract $_eventObject the eventObject
  *
  * @todo    write test
  */
 public function handleEvents(Tinebase_Event_Abstract $_eventObject)
 {
     try {
         if ($_eventObject instanceof Billing_Events_BillableReceiptCreated) {
             // create open item out of invoice or credit
             $db = Tinebase_Core::getDb();
             $tm = Tinebase_TransactionManager::getInstance();
             $tId = $tm->startTransaction($db);
             try {
                 $receipt = Billing_Controller_Receipt::getInstance()->get($_eventObject->receipt->getId());
                 // set payed and open sum
                 Billing_Controller_Receipt::getInstance()->onBillableReceiptCreated($receipt);
                 // create according open item
                 Billing_Controller_OpenItem::getInstance()->onBillableReceiptCreated($receipt);
                 if (Tinebase_Core::getPreference('Billing')->getValue(Billing_Preference::FIBU_INSTANT_BOOK_BILLABLE)) {
                     // do fibu booking -> fire event: BillableReceiptBooked
                     Billing_Controller_Booking::getInstance()->onBillableReceiptCreated($receipt);
                 }
                 $tm->commitTransaction($tId);
             } catch (Exception $e) {
                 $tm->rollback($tId);
                 throw $e;
             }
         }
         if ($_eventObject instanceof Billing_Events_PaymentReverted) {
             // TODO: NRW
             //Billing_Controller_OpenItem::getInstance()->onOpenItemPayed($_eventObject->payment);
         }
         if ($_eventObject instanceof Billing_Events_PaymentCreated) {
             // TODO: NRW
             try {
                 $payment = $_eventObject->payment;
                 Billing_Controller_Booking::getInstance()->onPaymentCreated($payment);
                 if ($payment->__get('receipt_id')) {
                     $receipt = $payment->getForeignRecord('receipt_id', Billing_Controller_Receipt::getInstance());
                     $openItem = Billing_Controller_OpenItem::getInstance()->getByReceiptId($receipt->getId());
                     Billing_Controller_OpenItem::getInstance()->payOpenItem($openItem->getId(), $payment);
                 }
                 if ($payment->isReturnDebit()) {
                     Tinebase_Event::fireEvent(new Billing_Events_PaymentDebitReturnCreated($payment));
                 }
             } catch (Exception $e) {
                 echo $e->__toString();
             }
             //Billing_Controller_OpenItem::getInstance()->onOpenItemPayed($_eventObject->payment);
         }
         if ($_eventObject instanceof Billing_Events_PaymentDebitReturnCreated) {
             // TODO: NRW
             try {
                 $payment = $_eventObject->payment;
                 Billing_Controller_OpenItem::getInstance()->onPaymentDebitReturnCreated($payment);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
             //Billing_Controller_OpenItem::getInstance()->onOpenItemPayed($_eventObject->payment);
         }
         if ($_eventObject instanceof Billing_Events_PaymentBooked) {
             // TODO: NRW
             try {
                 $payment = $_eventObject->payment;
                 $booking = $_eventObject->booking;
                 Billing_Controller_DebitorAccount::getInstance()->onPaymentBooked($payment, $booking);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
         }
         if ($_eventObject instanceof Billing_Events_PaymentDonationDetected) {
             // TODO: NRW
             try {
                 $payment = $_eventObject->payment;
                 Billing_Controller_DebitorAccount::getInstance()->onPaymentDonationDetected($payment);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
         }
         if ($_eventObject instanceof Billing_Events_BillableReceiptBooked) {
             try {
                 // TODO: NRW
                 $receipt = Billing_Controller_Receipt::getInstance()->get($_eventObject->receipt->getId());
                 $openItem = $_eventObject->openItem;
                 $booking = $_eventObject->booking;
                 // after booking -> debitor account gets  created
                 Billing_Controller_DebitorAccount::getInstance()->onBillableReceiptBooked($receipt, $openItem, $booking);
                 $receipt->__set('booking_id', $booking->getId());
                 $openItem->__set('booking_id', $booking->getId());
                 Billing_Controller_Receipt::getInstance()->update($receipt);
                 Billing_Controller_OpenItem::getInstance()->update($openItem);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
         }
         if ($_eventObject instanceof Billing_Events_BillableReceiptReverted) {
             try {
                 // TODO: NRW
                 $receipt = $_eventObject->revertedReceipt;
                 $reversionReceipt = $_eventObject->reversionReceipt;
                 // after booking -> debitor account gets  created
                 Billing_Controller_DebitorAccount::getInstance()->onBillableReceiptReverted($receipt, $reversionReceipt);
             } catch (Exception $e) {
                 echo $e->__toString();
             }
         }
     } catch (Exception $e) {
         Tinebase_Core::getLogger()->warn($e->__toString());
         echo $e->__toString();
     }
 }
 /**
  * inspects delete action
  *
  * @param array $_ids
  * @return array of ids to actually delete
  */
 protected function _inspectDelete(array $_ids)
 {
     $lists = $this->getMultiple($_ids);
     foreach ($lists as $list) {
         $event = new Addressbook_Event_DeleteList();
         $event->list = $list;
         Tinebase_Event::fireEvent($event);
     }
     return $_ids;
 }
Exemplo n.º 17
0
 /**
  * update user credential cache
  *
  * - fires Tinebase_Event_User_ChangeCredentialCache
  *
  * @param string $password
  * @return array
  */
 public function updateCredentialCache($password)
 {
     $oldCredentialCache = Tinebase_Core::get(Tinebase_Core::USERCREDENTIALCACHE);
     $credentialCache = Tinebase_Auth_CredentialCache::getInstance()->cacheCredentials(Tinebase_Core::getUser()->accountLoginName, $password);
     Tinebase_Core::set(Tinebase_Core::USERCREDENTIALCACHE, $credentialCache);
     $success = $this->_setCredentialCacheCookie();
     if ($success) {
         // close session to allow other requests
         Zend_Session::writeClose(true);
         $event = new Tinebase_Event_User_ChangeCredentialCache($oldCredentialCache);
         Tinebase_Event::fireEvent($event);
     }
     return array('success' => $success);
 }
Exemplo n.º 18
0
 /**
  * 
  * Reverse a payment
  * @event Billing_Events_PaymentReverted
  * @param integer $paymentId
  */
 public function reversePayment($paymentId)
 {
     $currentPayment = $this->get($paymentId);
     $currentPayment->__set('is_cancelled', true);
     $payment = clone $currentPayment;
     $payment->__set('id', null);
     $payment->__set('is_cancellation', true);
     $payment->swapAccounts();
     switch ($payment->__get('type')) {
         case 'CREDIT':
             $payment->__set('type', 'DEBIT');
             break;
         case 'DEBIT':
             $payment->__set('type', 'CREDIT');
             break;
     }
     $payment->__set('payment_date', $currentPayment->__get('payment_date'));
     $payment->__set('usage', 'STORNO #' . $currentPayment->__get('id') . ' ' . $currentPayment->__get('usage'));
     $payment->__set('reversion_record_id', $currentPayment->getId());
     $currentPayment->__set('reversion_record_id', $payment->getId());
     $payment = $this->create($payment);
     $currentPayment = $this->update($currentPayment);
     Tinebase_Event::fireEvent(new Billing_Events_PaymentReverted($currentPayment, $payment));
     return $payment;
     //$debitorAccount = Billing_Controller_DebitorAccount::getInstance()->getByPaymentId($paymentId);
 }