/**
  * @return Tinebase_TransactionManager
  */
 public static function getInstance()
 {
     if (self::$_instance === NULL) {
         self::$_instance = new Tinebase_TransactionManager();
     }
     return self::$_instance;
 }
 /**
  * tear down tests
  */
 protected function tearDown()
 {
     Zend_Session::$_unitTestEnabled = false;
     if ($this->_transactionId) {
         Tinebase_TransactionManager::getInstance()->rollBack();
     }
 }
 /**
  * Tears down the fixture, for example, closes a network connection.
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     if ($this->_smtpConfigChanged) {
         Tinebase_Config::getInstance()->set(Tinebase_Config::SMTP, $this->_smtpConfig);
         Tinebase_Smtp::setDefaultTransport($this->_smtpTransport);
     }
     Tinebase_TransactionManager::getInstance()->rollBack();
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     if ($this->_transactionId) {
         Tinebase_TransactionManager::getInstance()->rollBack();
     }
     if ($this->_user) {
         Tinebase_Core::set(Tinebase_Core::USER, $this->_user);
     }
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     // this needs to be done because Tinebase_Auth & Tinebase_Config use caching mechanisms
     Tinebase_Auth::setBackendType($this->_originalBackendType);
     Tinebase_Auth::deleteBackendConfiguration();
     Tinebase_Auth::setBackendConfiguration($this->_originalBackendConfiguration);
     Tinebase_Auth::saveBackendConfiguration();
     Tinebase_Auth::getInstance()->setBackend();
     Tinebase_TransactionManager::getInstance()->rollBack();
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     Tinebase_TransactionManager::getInstance()->rollBack();
     Tinebase_Config::getInstance()->clearCache();
     // needs to be reverted because we use Tinebase_User as a singleton
     Tinebase_User::setBackendType($this->_originalBackendType);
     Tinebase_User::deleteBackendConfiguration();
     Tinebase_User::setBackendConfiguration($this->_originalBackendConfiguration);
     Tinebase_User::saveBackendConfiguration();
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
     foreach ($this->objects['nodes'] as $node) {
         $this->_treeNodeBackend->delete($node->getId());
     }
     foreach ($this->objects['objects'] as $object) {
         $this->_fileObjectBackend->delete($object->getId());
     }
     Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     foreach ($this->_foldersToDelete as $foldername) {
         try {
             Expressomail_Controller_Folder::getInstance()->delete($this->_account->getId(), $foldername);
         } catch (Expressomail_Exception_IMAP $fei) {
             // do nothing
         }
     }
     Tinebase_TransactionManager::getInstance()->rollBack();
 }
 public function testOneDbRollback()
 {
     $db = Zend_Registry::get('dbAdapter');
     $transactionId = $this->_instance->startTransaction($db);
     $this->_createDbTestTable($db);
     $db->insert($this->_testTableName, array('Column1' => $transactionId));
     $this->_instance->rollBack();
     $columns = $db->fetchAll("SELECT * FROM " . $this->_testTableName . " WHERE " . $db->quoteInto('Column1 = ?', $transactionId) . ";");
     foreach ($columns as $column) {
         $this->assertNotEquals($transactionId, $column['Column1'], 'RollBack failed, data was inserted anyway');
     }
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     foreach ($this->_foldersToDelete as $foldername) {
         try {
             Felamimail_Controller_Folder::getInstance()->delete($this->_account->getId(), $foldername);
         } catch (Felamimail_Exception_IMAP $fei) {
             // do nothing
         }
     }
     Tinebase_TransactionManager::getInstance()->rollBack();
     if ($this->_pwChanged) {
         $testConfig = Zend_Registry::get('testConfig');
         $this->_setCredentials($testConfig->username, $testConfig->password);
     }
 }
 /**
  * (non-PHPdoc)
  * @see ActiveSync/ActiveSync_TestCase::setUp()
  */
 protected function setUp()
 {
     parent::setUp();
     Syncroton_Registry::setDatabase(Tinebase_Core::getDb());
     Syncroton_Registry::setTransactionManager(Tinebase_TransactionManager::getInstance());
     Syncroton_Registry::set(Syncroton_Registry::DEVICEBACKEND, new Syncroton_Backend_Device(Tinebase_Core::getDb(), SQL_TABLE_PREFIX . 'acsync_'));
     Syncroton_Registry::set(Syncroton_Registry::FOLDERBACKEND, new Syncroton_Backend_Folder(Tinebase_Core::getDb(), SQL_TABLE_PREFIX . 'acsync_'));
     Syncroton_Registry::set(Syncroton_Registry::SYNCSTATEBACKEND, new Syncroton_Backend_SyncState(Tinebase_Core::getDb(), SQL_TABLE_PREFIX . 'acsync_'));
     Syncroton_Registry::set(Syncroton_Registry::CONTENTSTATEBACKEND, new Syncroton_Backend_Content(Tinebase_Core::getDb(), SQL_TABLE_PREFIX . 'acsync_'));
     Syncroton_Registry::set(Syncroton_Registry::POLICYBACKEND, new Syncroton_Backend_Policy(Tinebase_Core::getDb(), SQL_TABLE_PREFIX . 'acsync_'));
     Syncroton_Registry::set('loggerBackend', Tinebase_Core::getLogger());
     Syncroton_Registry::setContactsDataClass('Addressbook_Frontend_ActiveSync');
     Syncroton_Registry::setCalendarDataClass('Calendar_Frontend_ActiveSync');
     Syncroton_Registry::setEmailDataClass('Felamimail_Frontend_ActiveSync');
     Syncroton_Registry::setTasksDataClass('Tasks_Frontend_ActiveSync');
     $this->_device = Syncroton_Registry::getDeviceBackend()->create(ActiveSync_TestCase::getTestDevice());
 }
 /**
  * test add customfield to the same record by multiple update
  *
  * @see #7330: https://forge.tine20.org/mantisbt/view.php?id=7330
  * @see 0007350: multipleUpdate - record not found
  */
 public function testAddSelfCustomFieldByMultipleUpdate()
 {
     // test needs transaction because Controller does rollback when exception is thrown
     Tinebase_TransactionManager::getInstance()->commitTransaction($this->_transactionId);
     $this->_transactionId = NULL;
     $cf = self::getCustomField(array('application_id' => Tinebase_Application::getInstance()->getApplicationByName('Addressbook')->getId(), 'model' => 'Addressbook_Model_Contact', 'definition' => array('type' => 'record', "recordConfig" => array("value" => array("records" => "Tine.Addressbook.Model.Contact")))));
     $cf = $this->_instance->addCustomField($cf);
     $c = Addressbook_Controller_Contact::getInstance();
     $record1 = $c->create(new Addressbook_Model_Contact(array('n_family' => 'Friendly', 'n_given' => 'Rupert')), false);
     $record2 = $c->create(new Addressbook_Model_Contact(array('n_family' => 'Friendly', 'n_given' => 'Matt')), false);
     $contactIds = array($record1->getId(), $record2->getId());
     $filter = new Addressbook_Model_ContactFilter(array(array('field' => 'n_family', 'operator' => 'equals', 'value' => 'Friendly')), 'AND');
     $result = $c->updateMultiple($filter, array('#' . $cf->name => $contactIds[0]));
     $this->assertEquals(1, $result['totalcount']);
     $this->assertEquals(1, $result['failcount']);
     // cleanup required because we do not have the tearDown() rollback here
     $this->_instance->deleteCustomField($cf);
     Addressbook_Controller_Contact::getInstance()->delete($contactIds);
 }
Example #13
0
 /**
  * get value of next revision for given fileobject
  * 
  * @param Tinebase_Model_Tree_FileObject $_objectId
  */
 protected function _getNextRevision(Tinebase_Model_Tree_FileObject $_objectId)
 {
     $objectId = $_objectId instanceof Tinebase_Model_Tree_FileObject ? $_objectId->getId() : $_objectId;
     $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
     $select = $this->_db->select()->from($this->_tablePrefix . $this->_tableName)->where($this->_db->quoteIdentifier($this->_tablePrefix . $this->_tableName . '.id') . ' = ?', $objectId);
     // lock row
     $stmt = $this->_db->query($select);
     $queryResult = $stmt->fetchAll();
     // increase revision
     $where = $this->_db->quoteInto('id = ?', $objectId);
     $data = array('revision' => new Zend_Db_Expr($this->_db->quoteIdentifier('revision') . ' + 1'));
     $this->_db->update($this->_tablePrefix . $this->_tableName, $data, $where);
     // fetch updated revision
     $stmt = $this->_db->query($select);
     $queryResult = $stmt->fetchAll();
     $revision = $queryResult[0]['revision'];
     // store new revisionid and unlock row
     Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
     return $revision;
 }
    /**
     * @group ServerTests
     *
     * @see 0011440: rework login failure handling
     */
    public function testAccountBlocking()
    {
        // NOTE: end transaction here as NOW() returns the start of the current transaction in pgsql
        //  and is used in user status statement (think about using statement_timestamp() instead of NOW() with pgsql)
        Tinebase_TransactionManager::getInstance()->commitTransaction($this->_transactionId);
        $this->_transactionId = null;
        $request = \Zend\Http\PhpEnvironment\Request::fromString(<<<EOS
POST /index.php HTTP/1.1
Content-Type: application/json
Content-Length: 122
Host: 192.168.122.158
Connection: keep-alive
Origin: http://192.168.1.158
X-Tine20-Request-Type: JSON
X-Tine20-Jsonkey: undefined
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36
X-Tine20-Transactionid: 9c7129898e9f8ab7e4621fddf7077a1eaa425aac
X-Requested-With: XMLHttpRequest
Accept: */*
Referer: http://192.168.122.158/tine20dev/
Accept-Encoding: gzip,deflate
Accept-Language: de-DE,de;q=0.8,en-GB;q=0.6,en;q=0.4
EOS
);
        $credentials = $this->getTestCredentials();
        for ($i = 0; $i <= 3; $i++) {
            $result = Tinebase_Controller::getInstance()->login($credentials['username'], 'foobar', $request);
            $this->assertFalse($result);
        }
        $result = Tinebase_Controller::getInstance()->login($credentials['username'], $credentials['password'], $request);
        $this->assertFalse($result, 'account must be blocked now');
        // wait for some time (2^4 = 16 +1 seconds)
        $timeToWait = 17;
        if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
            Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Waiting for ' . $timeToWait . ' seconds...');
        }
        sleep($timeToWait);
        $result = Tinebase_Controller::getInstance()->login($credentials['username'], $credentials['password'], $request);
        $this->assertTrue($result, 'account should be unblocked now');
    }
Example #15
0
 /**
  * set value of http_client_info_sent
  *
  * @param string|array|Tinebase_Record_RecordSet $_id
  * @param boolean $_status
  * @throws  Voipmanager_Exception_Backend
  */
 public function setHttpClientInfoSent($_id, $_status)
 {
     foreach ((array) $_id as $id) {
         $phoneId = Voipmanager_Model_Snom_Phone::convertSnomPhoneIdToInt($id);
         $where[] = $this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' = ?', $phoneId);
     }
     try {
         $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($this->_db);
         // NOTE: cascading delete for lines and phone_settings
         // SECOND NOTE: using array for second argument won't work as delete function joins array items using "AND"
         #foreach($where AS $where_atom)
         #{
         #    $this->_db->delete($this->_tablePrefix . 'snom_phones', $where_atom);
         #}
         $phoneData = array('http_client_info_sent' => (bool) $_status);
         $this->_db->update($this->_tablePrefix . 'snom_phones', $phoneData, $where);
         Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
     } catch (Exception $e) {
         Tinebase_TransactionManager::getInstance()->rollBack();
         throw new Voipmanager_Exception_Backend($e->getMessage());
     }
 }
 /**
  * remove members from list
  * 
  * @param  mixed  $_listId
  * @param  mixed  $_membersToRemove
  * @return Addressbook_Model_List
  */
 public function removeListMember($_listId, $_membersToRemove)
 {
     /** @var Addressbook_Model_List $list */
     $list = $this->get($_listId);
     if (empty($_membersToRemove)) {
         return $list;
     }
     $removeMembers = Tinebase_Record_RecordSet::getIdsFromMixed($_membersToRemove);
     $idsToRemove = array_intersect($list->members, $removeMembers);
     $listId = Tinebase_Record_Abstract::convertId($_listId, $this->_modelName);
     $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
     if (!empty($idsToRemove)) {
         $where = '(' . $this->_db->quoteInto($this->_db->quoteIdentifier($this->_tablePrefix . $this->_foreignTables['members']['table'] . '.' . $this->_foreignTables['members']['joinOn']) . ' = ?', $listId) . ' AND ' . $this->_db->quoteInto($this->_db->quoteIdentifier($this->_tablePrefix . $this->_foreignTables['members']['table'] . '.' . $this->_foreignTables['members']['field']) . ' IN (?)', $idsToRemove) . ')';
         $this->_db->delete($this->_tablePrefix . $this->_foreignTables['members']['table'], $where);
     }
     Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
     return $this->get($_listId);
 }
Example #17
0
 /**
  * finish job
  *
  * @param Tinebase_Model_AsyncJob $_asyncJob
  * @param string $_status
  * @param string $_message
  * @return Tinebase_Model_AsyncJob
  */
 public function finishJob(Tinebase_Model_AsyncJob $_asyncJob, $_status = Tinebase_Model_AsyncJob::STATUS_SUCCESS, $_message = NULL)
 {
     try {
         $db = $this->_backend->getAdapter();
         $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
         $_asyncJob->end_time = Tinebase_DateTime::now();
         $_asyncJob->status = $_status;
         if ($_message !== NULL) {
             $_asyncJob->message = $_message;
         }
         $result = $this->_backend->update($_asyncJob);
         Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
     } catch (Exception $e) {
         Tinebase_TransactionManager::getInstance()->rollBack();
         throw $e;
     }
     return $result;
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Tearing down ...');
     }
     if (count($this->_createdFolders) > 0) {
         foreach ($this->_createdFolders as $folderName) {
             //echo "delete $folderName\n";
             try {
                 $this->_imap->removeFolder(Felamimail_Model_Folder::encodeFolderName($folderName));
             } catch (Zend_Mail_Storage_Exception $zmse) {
                 // already deleted
             }
         }
         Felamimail_Controller_Cache_Folder::getInstance()->clear($this->_account);
     }
     if (!empty($this->_foldersToClear)) {
         foreach ($this->_foldersToClear as $folderName) {
             // delete test messages from given folders on imap server (search by special header)
             $this->_imap->selectFolder($folderName);
             $result = $this->_imap->search(array('HEADER X-Tine20TestMessage jsontest'));
             //print_r($result);
             foreach ($result as $messageUid) {
                 $this->_imap->removeMessage($messageUid);
             }
             // clear message cache
             $folder = Felamimail_Controller_Folder::getInstance()->getByBackendAndGlobalName($this->_account->getId(), $folderName);
             Felamimail_Controller_Cache_Message::getInstance()->clear($folder);
         }
     }
     // sieve cleanup
     if ($this->_testSieveScriptName !== NULL) {
         Felamimail_Controller_Sieve::getInstance()->setScriptName($this->_testSieveScriptName);
         try {
             Felamimail_Controller_Sieve::getInstance()->deleteScript($this->_account->getId());
         } catch (Zend_Mail_Protocol_Exception $zmpe) {
             // do not delete script if active
         }
         Felamimail_Controller_Account::getInstance()->setVacationActive($this->_account, $this->_oldSieveVacationActiveState);
         if ($this->_oldSieveData !== NULL) {
             $this->_oldSieveData->save();
         }
     }
     if ($this->_oldActiveSieveScriptName !== NULL) {
         Felamimail_Controller_Sieve::getInstance()->setScriptName($this->_oldActiveSieveScriptName);
         Felamimail_Controller_Sieve::getInstance()->activateScript($this->_account->getId());
     }
     // vfs cleanup
     foreach ($this->_pathsToDelete as $path) {
         $webdavRoot = new DAV\ObjectTree(new Tinebase_WebDav_Root());
         //echo "delete $path";
         $webdavRoot->delete($path);
     }
     Tinebase_TransactionManager::getInstance()->rollBack();
 }
 /**
  * constructs this importer
  * 
  * @param Zend_Db_Adapter_Abstract  $_egwDb
  * @param Zend_Config               $_config
  * @param Zend_Log                  $_log
  */
 public function __construct($_config, $_log)
 {
     $this->_config = $_config;
     $this->_log = $_log;
     $this->_egwDb = Zend_Db::factory('PDO_MYSQL', $this->_config->egwDb);
     /* egw config is utf-8 but db needs utf8 as string -> leave as config atm.
        $select = $this->_egwDb->select()
            ->from(array('grants' => 'egw_config'))
            ->where($this->_egwDb->quoteInto($this->_egwDb->quoteIdentifier('config_name') . ' = (?)', 'system_charset'));
            
        $egwConfig = $this->_egwDb->fetchAll($select, NULL, Zend_Db::FETCH_ASSOC);
        $charset = $egwConfig[0]['config_value'];
        */
     $this->_log->INFO(__METHOD__ . '::' . __LINE__ . " setting egw charset to {$this->_config->egwDb->charset}");
     $this->_egwDb->query("SET NAMES {$this->_config->egwDb->charset}");
     if ($this->_config->dryRun) {
         Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
     }
     if ($this->_config->accountIdMap) {
         $this->_accountIdMapCache = (include $this->_config->accountIdMap);
     }
 }
 /**
  * increase access count
  *
  * @param Filemanager_Model_DownloadLink $download
  */
 public function increaseAccessCount(Filemanager_Model_DownloadLink $download)
 {
     $db = method_exists($this->_backend, 'getAdapter') ? $this->_backend->getAdapter() : Tinebase_Core::getDb();
     $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db);
     $currentRecord = $this->_backend->get($download->getId());
     $currentRecord->access_count++;
     // yes, no history etc.
     $this->_backend->update($currentRecord);
     Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     Tinebase_TransactionManager::getInstance()->rollBack();
     Tinebase_Config::getInstance()->set(Tinebase_Config::ANYONE_ACCOUNT_DISABLED, false);
 }
 /**
  * test needs transaction
  */
 protected function _testNeedsTransaction()
 {
     if ($this->_transactionId) {
         Tinebase_TransactionManager::getInstance()->commitTransaction($this->_transactionId);
         $this->_transactionId = null;
     }
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     Tinebase_TransactionManager::getInstance()->rollBack();
 }
 /**
  * tear down tests
  *
  */
 public function tearDown()
 {
     if ($this->_transactionId) {
         Tinebase_TransactionManager::getInstance()->rollBack();
     }
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     Addressbook_Controller_Contact::getInstance()->setGeoDataForContacts(TRUE);
     Tinebase_TransactionManager::getInstance()->rollBack();
 }
 public function checkForRecreation(array $ids, $contract)
 {
     //we should delete from recent to old
     //we should create from old to recent
     //then compare correctly...
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         $forTrace = $contract->id . ' ' . print_r($ids, true);
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' for: ' . $forTrace);
     }
     $this->_autoInvoiceIterationDetailResults = array();
     $this->_autoInvoiceIterationResults = array();
     $this->_autoInvoiceRecreationResults = array();
     $oldInvoices = array();
     $oldPositions = array();
     $somethingChanged = false;
     $failed = false;
     $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
     $invoicePositionController = Sales_Controller_InvoicePosition::getInstance();
     foreach ($ids as $id) {
         $invoice = $this->get($id);
         if (!$invoice) {
             Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' can not ::get invoice with id: ' . $id);
             continue;
         }
         $invoice->setTimezone(Tinebase_Core::getUserTimezone());
         $oldInvoices[] = $invoice;
         $filter = new Sales_Model_InvoicePositionFilter(array());
         $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'invoice_id', 'operator' => 'equals', 'value' => $invoice->getId())));
         $oldPositions[$invoice->getId()] = $invoicePositionController->search($filter);
         try {
             $this->delete(array($invoice));
         } catch (Sales_Exception_DeletePreviousInvoice $sedpi) {
             $failed = true;
             Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' could not delete invoice with id: ' . $id);
             break;
         }
         //is $invoice still valid?!?!?
     }
     if (true === $failed) {
         Tinebase_TransactionManager::getInstance()->rollBack();
         return;
     }
     // reload relations as they may have changed as we deleted the invoices above
     // TODO: could be made more efficient as we just need to reload releationsa actually and not the whole contract.
     $contract = Sales_Controller_Contract::getInstance()->get($contract->getId());
     $this->_currentBillingContract = $contract;
     $this->_currentBillingContract->setTimezone(Tinebase_Core::getUserTimezone());
     // the newest invoice!
     $date = clone $oldInvoices[0]->date;
     // date seems not to have a tz, so after the clone, the tz is UTC!! we need to reset it
     $date->setTimezone(Tinebase_Core::getUserTimezone());
     $this->_createAutoInvoicesForContract($this->_currentBillingContract, $date);
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' deleted ' . count($oldInvoices) . ' and recreated ' . count($this->_autoInvoiceIterationDetailResults) . ' invoices for: ' . $forTrace);
     }
     if (count($oldInvoices) !== count($this->_autoInvoiceIterationDetailResults)) {
         // something changed for sure. fine, commit => done
         $somethingChanged = true;
     } else {
         // WE NEED TO DIFF POSITIONS TOO! diff on invoice does not do a diff on the positions!
         // if diff on invoice is negative, then check the positions
         foreach ($this->_autoInvoiceIterationDetailResults as $newInvoice) {
             $diff = null;
             foreach ($oldInvoices as $oldInvoice) {
                 if ($newInvoice->date->equals($oldInvoice->date)) {
                     $diff = $newInvoice->diff($oldInvoice, array('description', 'id', 'relations', 'contract', 'customer', 'created_by', 'creation_time', 'last_modified_by', 'last_modified_time'));
                     //if nothing changed, check the invoice positions
                     if ($diff->isEmpty()) {
                         $filter = new Sales_Model_InvoicePositionFilter(array());
                         $filter->addFilter(new Tinebase_Model_Filter_Text(array('field' => 'invoice_id', 'operator' => 'equals', 'value' => $newInvoice->getId())));
                         $newPositions = $invoicePositionController->search($filter);
                         $i = 0;
                         foreach ($oldPositions[$invoice->getId()] as $oldPosition) {
                             if ($i + 1 > $newPositions->count()) {
                                 $diff = null;
                                 break;
                             }
                             $newPosition = $newPositions->getByIndex($i++);
                             $diff = $newPosition->diff($oldPosition, array('id', 'invoice_id'));
                             if (!$diff->isEmpty()) {
                                 break;
                             }
                         }
                     }
                     break;
                 }
             }
             // null === $diff means that we could not match the new Invoice to the old one, though the count of invoices seems not to have changed
             if (null === $diff || !$diff->isEmpty()) {
                 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                     Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' something changed with $diff = ' . (null === $diff ? 'null' : print_r($diff->toArray(), true)) . ' for: ' . $forTrace);
                 }
                 $somethingChanged = true;
                 break;
             }
         }
     }
     if (true === $somethingChanged) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' something changed for: ' . $forTrace);
         }
         Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
         //create mapping of old to new invoices
         foreach ($this->_autoInvoiceIterationDetailResults as $newInvoice) {
             foreach ($oldInvoices as $oldInvoice) {
                 if ($newInvoice->date->equals($oldInvoice->date)) {
                     $this->_autoInvoiceRecreationResults[$oldInvoice->getId()] = $newInvoice->getId();
                 }
             }
         }
     } else {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' nothing changed for: ' . $forTrace);
         }
         Tinebase_TransactionManager::getInstance()->rollBack();
     }
 }
 /**
  * Tears down the fixture
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     Tinebase_TransactionManager::getInstance()->rollBack();
     Tinebase_FileSystem::getInstance()->clearStatCache();
     Tinebase_FileSystem::getInstance()->clearDeletedFiles();
 }
Example #28
0
 private function runTransaction()
 {
     try {
         $config = \Tinebase_Config::getInstance()->getConfig('pdfserver', NULL, TRUE)->value;
         $storageConf = \Tinebase_Config::getInstance()->getConfig('printjobs', NULL, TRUE)->value;
         $this->tempFilePath = CSopen::instance()->getCustomerPath() . '/customize/data/documents/temp/';
         $this->templateController = DocManager_Controller_Template::getInstance();
         $db = Tinebase_Core::getDb();
         $tm = Tinebase_TransactionManager::getInstance();
         $this->pdfServer = org\sopen\app\api\pdf\server\PdfServer::getInstance($config)->setDocumentsTempPath(CSopen::instance()->getDocumentsTempPath());
         $this->printJobStorage = org\sopen\app\api\filesystem\storage\TempFileProcessStorage::createNew('printjobs', $storageConf['storagepath']);
         $this->printJobStorage->addProcessLines(array('in', 'convert', 'out'));
         $tId = $tm->startTransaction($db);
         $this->createResult();
         // make db changes final
         $tm->commitTransaction($tId);
         // output the result
         if ($this->count > 0) {
             $this->outputResult();
         } else {
             $this->outputNone();
         }
     } catch (Exception $e) {
         echo $e->__toString();
         $tm->rollback($tId);
     }
 }
 /**
  * set role rights 
  *
  * @param   int    $roleId
  * @param   array  $_roleRights  with role rights array(("application_id" => app id, "right" => the right to set), (...))
  * @throws  Tinebase_Exception_InvalidArgument
  */
 public function setRoleRights($roleId, array $roleRights)
 {
     if (!is_numeric($roleId) || ($roleId = (int) $roleId) === 0) {
         throw new Tinebase_Exception_InvalidArgument('$_roleId must be integer and greater than 0');
     }
     $currentRights = $this->getRoleRights($roleId);
     // change array key to string identifying right
     foreach ($currentRights as $id => $right) {
         $currentRights[$right['application_id'] . $right['right']] = $right;
         unset($currentRights[$id]);
     }
     // change array key to string identifying right
     foreach ($roleRights as $id => $right) {
         $roleRights[$right['application_id'] . $right['right']] = $right;
         unset($roleRights[$id]);
     }
     // compare array keys to calculate changes
     $rightsToBeDeleted = array_diff_key($currentRights, $roleRights);
     $rightsToBeAdded = array_diff_key($roleRights, $currentRights);
     $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($this->_db);
     foreach ($rightsToBeDeleted as $right) {
         $this->deleteRoleRight($roleId, $right['application_id'], $right['right']);
     }
     foreach ($rightsToBeAdded as $right) {
         $this->addRoleRight($roleId, $right['application_id'], $right['right']);
     }
     Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
     $this->_invalidateRightsCache($roleId, array_merge($rightsToBeDeleted, $rightsToBeAdded));
 }
 /**
  * update foreign key values
  * 
  * @param string $_mode create|update
  * @param Tinebase_Record_Interface $_record
  */
 protected function _updateForeignKeys($_mode, Tinebase_Record_Interface $_record)
 {
     if (!empty($this->_foreignTables)) {
         foreach ($this->_foreignTables as $modelName => $join) {
             if (!(isset($join['field']) || array_key_exists('field', $join))) {
                 continue;
             }
             $idsToAdd = array();
             $idsToRemove = array();
             if (!empty($_record->{$modelName})) {
                 $idsToAdd = Tinebase_Record_RecordSet::getIdsFromMixed($_record->{$modelName});
             }
             $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb());
             if ($_mode == 'update') {
                 $select = $this->_db->select();
                 $select->from(array($join['table'] => $this->_tablePrefix . $join['table']), array($join['field']))->where($this->_db->quoteIdentifier($join['table'] . '.' . $join['joinOn']) . ' = ?', $_record->getId());
                 Tinebase_Backend_Sql_Abstract::traitGroup($select);
                 $stmt = $this->_db->query($select);
                 $currentIds = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
                 $stmt->closeCursor();
                 $idsToRemove = array_diff($currentIds, $idsToAdd);
                 $idsToAdd = array_diff($idsToAdd, $currentIds);
             }
             if (!empty($idsToRemove)) {
                 $where = '(' . $this->_db->quoteInto($this->_db->quoteIdentifier($this->_tablePrefix . $join['table'] . '.' . $join['joinOn']) . ' = ?', $_record->getId()) . ' AND ' . $this->_db->quoteInto($this->_db->quoteIdentifier($this->_tablePrefix . $join['table'] . '.' . $join['field']) . ' IN (?)', $idsToRemove) . ')';
                 $this->_db->delete($this->_tablePrefix . $join['table'], $where);
             }
             foreach ($idsToAdd as $id) {
                 $recordArray = array($join['joinOn'] => $_record->getId(), $join['field'] => $id);
                 $this->_db->insert($this->_tablePrefix . $join['table'], $recordArray);
             }
             Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId);
         }
     }
 }