/**
  * Tears down the fixture, for example, closes a network connection.
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     $db = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'record_persistentobserver'));
     foreach ($this->persistentObserver as $persistentObserver) {
         $db->delete(array('identifier' => $persistentObserver->getId()));
     }
 }
예제 #2
0
 /**
  * Tears down the fixture, for example, closes a network connection.
  * This method is called after a test is executed.
  *
  * @access protected
  */
 protected function tearDown()
 {
     $db = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'relations'));
     foreach ($this->relations as $relation) {
         $db->delete(array($db->getAdapter()->quoteInto('rel_id = ?', $relation->getId())));
     }
 }
예제 #3
0
 public function testCreateMinimalTask()
 {
     $summary = 'minimal task by phpunit';
     $task = new Tasks_Model_Task(array('summary' => $summary, 'container_id' => $this->container_id));
     $persitantTask = $this->_backend->create($task);
     $pagination = new Tasks_Model_Pagination();
     $filter = new Tasks_Model_TaskFilter(array(array('field' => 'summary', 'operator' => 'contains', 'value' => $summary), array('field' => 'container_id', 'operator' => 'equals', 'value' => $task->container_id)));
     $tasks = $this->_backend->search($filter, $pagination);
     $this->assertEquals(1, count($tasks));
     $db = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'tasks'));
     $db->delete("summary LIKE '{$summary}'");
     Tinebase_Timemachine_ModificationLogTest::purgeLogs($persitantTask->getId());
 }
 /**
  * Saves a logbook record
  * 
  * @param Tinebase_Model_ModificationLog $modification
  * @return string id
  */
 public function setModification(Tinebase_Model_ModificationLog $modification)
 {
     $modification->isValid(TRUE);
     $id = $modification->generateUID();
     $modification->setId($id);
     $modification->convertDates = true;
     $modificationArray = $modification->toArray();
     if (is_array($modificationArray['new_value'])) {
         throw new Tinebase_Exception_Record_Validation("New value is an array! \n" . print_r($modificationArray['new_value'], true));
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . " Inserting modlog: " . print_r($modificationArray, TRUE));
     }
     try {
         $this->_table->insert($modificationArray);
     } catch (Zend_Db_Statement_Exception $zdse) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . $zdse->getMessage() . ' ' . print_r($modification->toArray(), TRUE));
         }
         // check if unique key constraint failed
         $filter = new Tinebase_Model_ModificationLogFilter(array(array('field' => 'seq', 'operator' => 'equals', 'value' => $modification->seq), array('field' => 'record_type', 'operator' => 'equals', 'value' => $modification->record_type), array('field' => 'record_id', 'operator' => 'equals', 'value' => $modification->record_id), array('field' => 'modified_attribute', 'operator' => 'equals', 'value' => $modification->modified_attribute)));
         $result = $this->_backend->search($filter);
         if (count($result) > 0) {
             throw new Tinebase_Timemachine_Exception_ConcurrencyConflict('Seq ' . $modification->seq . ' for record ' . $modification->record_id . ' already exists');
         } else {
             throw $zdse;
         }
     }
     return $id;
 }
예제 #5
0
 /**
  * returns all observers of a given observable and event
  * 
  * @param Tinebase_Record_Interface $_observable 
  * @param string _event 
  * @return Tinebase_Record_RecordSet
  */
 protected function getObserversByEvent($_observable, $_event)
 {
     if (!$_observer->getApplication() || !$_observer->getId()) {
         throw new Tinebase_Exception_Record_DefinitionFailure();
     }
     $where = array($this->_db->quoteIdentifier('observable_application') . ' =' . $_observable->getApplication(), $this->_db->quoteIdentifier('observable_identifier') . '  =' . $_observable->getId(), $this->_db->quoteIdentifier('observed_event') . '         =' . $this->_db->getAdapter()->quote($_event));
     return new Tinebase_Record_RecordSet('Tinebase_Model_PersistentObserver', $this->_db->fetchAll($where), true);
 }
예제 #6
0
 /**
  * add single role rights 
  *
  * @param   int $_roleId
  * @param   int $_applicationId
  * @param   string $_right
  */
 public function addSingleRight($_roleId, $_applicationId, $_right)
 {
     // check if already in
     $select = $this->_roleRightsTable->select();
     $select->where($this->_db->quoteInto($this->_db->quoteIdentifier('role_id') . ' = ?', $_roleId))->where($this->_db->quoteInto($this->_db->quoteIdentifier('right') . ' = ?', $_right))->where($this->_db->quoteInto($this->_db->quoteIdentifier('application_id') . ' = ?', $_applicationId));
     if (!($row = $this->_roleRightsTable->fetchRow($select))) {
         $data = array('role_id' => $_roleId, 'application_id' => $_applicationId, 'right' => $_right);
         $this->_roleRightsTable->insert($data);
     }
 }
예제 #7
0
 /**
  * check if relation already exists but is_deleted
  *
  * @param Tinebase_Model_Relation $_relation
  * @return string relation id
  */
 protected function _checkExistance($_relation)
 {
     $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('own_model') . ' = ?', $_relation->own_model), $this->_db->quoteInto($this->_db->quoteIdentifier('own_backend') . ' = ?', $_relation->own_backend), $this->_db->quoteInto($this->_db->quoteIdentifier('own_id') . ' = ?', $_relation->own_id), $this->_db->quoteInto($this->_db->quoteIdentifier('related_id') . ' = ?', $_relation->related_id), $this->_db->quoteIdentifier('is_deleted') . ' = 1');
     $relationRow = $this->_dbTable->fetchRow($where);
     if ($relationRow) {
         return $relationRow->rel_id;
     } else {
         return FALSE;
     }
 }
 /**
  * Get multiple groups
  *
  * @param string|array $_ids Ids
  * @return Tinebase_Record_RecordSet
  * 
  * @todo this should return the container_id, too
  */
 public function getMultiple($_ids)
 {
     $result = new Tinebase_Record_RecordSet('Tinebase_Model_Group');
     if (!empty($_ids)) {
         $select = $this->groupsTable->select();
         $select->where($this->_db->quoteIdentifier('id') . ' IN (?)', array_unique((array) $_ids));
         $rows = $this->groupsTable->fetchAll($select);
         foreach ($rows as $row) {
             $result->addRecord(new Tinebase_Model_Group($row->toArray(), TRUE));
         }
     }
     return $result;
 }
예제 #9
0
 /**
  * Saves a logbook record
  * 
  * @param   Tinebase_Model_ModificationLog _modification 
  * @return  string id;
  * @throws  Tinebase_Exception_Record_Validation
  */
 public function setModification(Tinebase_Model_ModificationLog $_modification)
 {
     if ($_modification->isValid()) {
         $id = $_modification->generateUID();
         $_modification->setId($id);
         $_modification->convertDates = true;
         $modificationArray = $_modification->toArray();
         if (is_array($modificationArray['new_value'])) {
             throw new Tinebase_Exception_Record_Validation("New value is an array! \n" . print_r($modificationArray['new_value'], true));
         }
         $this->_table->insert($modificationArray);
     } else {
         throw new Tinebase_Exception_Record_Validation("_modification data is not valid! \n" . print_r($_modification->getValidationErrors(), true));
     }
     return $id;
 }
 /**
  * the constructor
  *
  */
 public function __construct(array $_options = array())
 {
     $imapConfig = Tinebase_Config::getInstance()->get(Tinebase_Config::IMAP, new Tinebase_Config_Struct())->toArray();
     // merge _config and dbmail imap
     $this->_config = array_merge($imapConfig['dbmail'], $this->_config);
     // set domain from imap config
     $this->_config['domain'] = !empty($imapConfig['domain']) ? $imapConfig['domain'] : null;
     // _tablename = "dbmail_users"
     $this->_userTable = $this->_config['prefix'] . $this->_config['userTable'];
     // connect to DB
     $this->_getDb($this->_config);
     $columns = Tinebase_Db_Table::getTableDescriptionFromCache('dbmail_users', $this->_db);
     if ((isset($columns['tine20_userid']) || array_key_exists('tine20_userid', $columns)) && (isset($columns['tine20_clientid']) || array_key_exists('tine20_clientid', $columns))) {
         $this->_hasTine20Userid = true;
         $this->_propertyMapping['emailUserId'] = 'tine20_userid';
         $this->_propertyMapping['emailGID'] = 'tine20_clientid';
     }
     $this->_clientId = Tinebase_Application::getInstance()->getApplicationByName('Tinebase')->getId();
     $this->_config['emailGID'] = Tinebase_Application::getInstance()->getApplicationByName('Tinebase')->getId();
 }
예제 #11
0
 /**
  * add salutation image path
  */
 public function update_3()
 {
     $declaration = new Setup_Backend_Schema_Field_Xml('
         <field>
             <name>image_path</name>
             <type>text</type>
             <length>255</length>
         </field>');
     $this->_backend->addCol('addressbook_salutations', $declaration);
     $this->setTableVersion('addressbook_salutations', '2', TRUE);
     // update image paths
     $salutationTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'addressbook_salutations'));
     $where = $salutationTable->getAdapter()->quoteInto('gender = ?', 'male');
     $salutationTable->update(array('image_path' => 'images/empty_photo_male.png'), $where);
     $where = $salutationTable->getAdapter()->quoteInto('gender = ?', 'female');
     $salutationTable->update(array('image_path' => 'images/empty_photo_female.png'), $where);
     $where = $salutationTable->getAdapter()->quoteInto('gender = ?', 'other');
     $salutationTable->update(array('image_path' => 'images/empty_photo_company.png'), $where);
     $this->setApplicationVersion('Addressbook', '3.4');
 }
 /**
  * counts related records, gropued by Model, Type and Id but excludes relations which will be updated by $excludeCount
  *
  * @param string $ownModel
  * @param Tinebase_Record_RecordSet $relations
  * @return array
  */
 public function countRelatedConstraints($ownModel, $relations, $excludeCount)
 {
     if ($relations->count() == 0) {
         return array();
     }
     $adapter = $this->_dbTable->getAdapter();
     $tableName = SQL_TABLE_PREFIX . 'relations';
     $sql = 'SELECT ' . $this->_dbCommand->getConcat(array($this->_db->quoteIdentifier('related_model'), "'--'", $this->_db->quoteIdentifier('type'), "'--'", $this->_db->quoteIdentifier('own_id'))) . ' 
                 AS ' . $this->_db->quoteIdentifier('id') . ',
                 ' . $this->_db->quoteIdentifier('related_model') . ', ' . $this->_db->quoteIdentifier('type') . ',
                 ' . $this->_db->quoteIdentifier('own_model') . ', COUNT(*)
                 AS ' . $this->_db->quoteIdentifier('count') . '
             FROM ' . $this->_db->quoteIdentifier($tableName) . '
             WHERE ' . $this->_db->quoteInto($this->_db->quoteIdentifier('own_id') . ' IN (?) ', $relations->related_id) . '
                 AND ' . $this->_db->quoteInto($this->_db->quoteIdentifier('related_model') . ' = ? ', $ownModel) . '
                 AND ' . $this->_db->quoteIdentifier('is_deleted') . ' = 0 ';
     if (!empty($excludeCount)) {
         $sql .= ' AND ' . $this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' NOT IN (?) ', $excludeCount);
     }
     $sql .= 'GROUP BY ' . $this->_db->quoteIdentifier('own_id') . ',' . $this->_db->quoteIdentifier('related_model') . ', ' . $this->_db->quoteIdentifier('own_model') . ', ' . $this->_db->quoteIdentifier('type') . ', ' . $this->_db->quoteIdentifier('related_id');
     $result = $adapter->fetchAssoc($sql);
     return $result;
 }
 /**
  * update to 8.1
  * 
  * @see 0009152: saving of record fails because of too many relations
  */
 public function update_0()
 {
     $valueFields = array('old_value', 'new_value');
     foreach ($valueFields as $field) {
         // check schema, only change if type == text
         $typeMapping = $this->_backend->getTypeMapping('text');
         $schema = Tinebase_Db_Table::getTableDescriptionFromCache(SQL_TABLE_PREFIX . 'timemachine_modlog', $this->_backend->getDb());
         if ($schema[$field]['DATA_TYPE'] === $typeMapping['defaultType']) {
             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Old column type (' . $schema[$field]['DATA_TYPE'] . ') is going to be altered to clob');
             }
             $declaration = new Setup_Backend_Schema_Field_Xml('
                 <field>
                     <name>' . $field . '</name>
                     <type>clob</type>
                 </field>
             ');
             $this->_backend->alterCol('timemachine_modlog', $declaration);
         }
     }
     $this->setTableVersion('timemachine_modlog', '3');
     $this->setApplicationVersion('Tinebase', '8.1');
 }
 /**
  * @param $_oldTableName
  * @param $_newTableName
  * @return int
  */
 public function renameTableInAppTables($_oldTableName, $_newTableName)
 {
     $applicationsTables = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'application_tables'));
     $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('name') . ' = ?', $_oldTableName));
     $result = $applicationsTables->update(array('name' => $_newTableName), $where);
     return $result;
 }
 /**
  * delete note type
  *
  * @param integer $_noteTypeId
  */
 public function deleteNoteType($_noteTypeId)
 {
     $this->_noteTypesTable->delete($this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' = ?', $_noteTypeId));
 }
 /**
  * Public service for grouping treatment
  * 
  * @param Zend_Db_Select $select
  */
 public static function traitGroup(Zend_Db_Select $select)
 {
     // not needed for MySQL backends
     if ($select->getAdapter() instanceof Zend_Db_Adapter_Pdo_Mysql) {
         return;
     }
     $group = $select->getPart(Zend_Db_Select::GROUP);
     if (empty($group)) {
         return;
     }
     $columns = $select->getPart(Zend_Db_Select::COLUMNS);
     $updatedColumns = array();
     //$column is an array where 0 is table, 1 is field and 2 is alias
     foreach ($columns as $key => $column) {
         if ($column[1] instanceof Zend_Db_Expr) {
             if (preg_match('/^\\(.*\\)/', $column[1])) {
                 $updatedColumns[] = array($column[0], new Zend_Db_Expr("MIN(" . $column[1] . ")"), $column[2]);
             } else {
                 $updatedColumns[] = $column;
             }
             continue;
         }
         if (preg_match('/^\\(.*\\)/', $column[1])) {
             $updatedColumns[] = array($column[0], new Zend_Db_Expr("MIN(" . $column[1] . ")"), $column[2]);
             continue;
         }
         // resolve * to single columns
         if ($column[1] == '*') {
             $tableFields = Tinebase_Db_Table::getTableDescriptionFromCache(SQL_TABLE_PREFIX . $column[0], $select->getAdapter());
             foreach ($tableFields as $columnName => $schema) {
                 // adds columns into group by clause (table.field)
                 // checks if field has a function (that must be an aggregation)
                 $fieldName = "{$column[0]}.{$columnName}";
                 if (in_array($fieldName, $group)) {
                     $updatedColumns[] = array($column[0], $fieldName, $columnName);
                 } else {
                     // any selected field which is not in the group by clause must have an aggregate function
                     // we choose MIN() as default. In practice the affected columns will have only one value anyways.
                     $updatedColumns[] = array($column[0], new Zend_Db_Expr("MIN(" . $select->getAdapter()->quoteIdentifier($fieldName) . ")"), $columnName);
                 }
             }
             continue;
         }
         $fieldName = $column[0] . '.' . $column[1];
         if (in_array($fieldName, $group)) {
             $updatedColumns[] = $column;
         } else {
             // any selected field which is not in the group by clause must have an aggregate function
             // we choose MIN() as default. In practice the affected columns will have only one value anyways.
             $updatedColumns[] = array($column[0], new Zend_Db_Expr("MIN(" . $select->getAdapter()->quoteIdentifier($fieldName) . ")"), $column[2] ? $column[2] : $column[1]);
         }
     }
     $select->reset(Zend_Db_Select::COLUMNS);
     foreach ($updatedColumns as $column) {
         $select->columns(!empty($column[2]) ? array($column[2] => $column[1]) : $column[1], $column[0]);
     }
     // add order by columns to group by
     $order = $select->getPart(Zend_Db_Select::ORDER);
     foreach ($order as $column) {
         $field = $column[0];
         if (preg_match('/.*\\..*/', $field) && !in_array($field, $group)) {
             // adds column into group by clause (table.field)
             $group[] = $field;
         }
     }
     $select->reset(Zend_Db_Select::GROUP);
     $select->group($group);
 }
예제 #17
0
 /**
  * delete registration by username
  *
  * @param   string $_username
  * @return  int     number of rows affected
  */
 public function deleteRegistrationByLoginName($_username)
 {
     $where = $this->_db->quoteInto($this->_db->quoteIdentifier('login_name') . ' = ?', $_username);
     $result = $this->_registrationsTable->delete($where);
     return $result;
 }
 /**
  * update modlog seq
  * 
  * @param string $model
  * @param string $recordTable
  */
 public static function updateModlogSeq($model, $recordTable)
 {
     if (!class_exists($model)) {
         throw new Setup_Exception('Could not find model class');
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Fetching modlog records for ' . $model);
     }
     // check if modlog table already has seq col
     $db = Tinebase_Core::getDb();
     $modlogTable = SQL_TABLE_PREFIX . 'timemachine_modlog';
     $modlogTableColumns = Tinebase_Db_Table::getTableDescriptionFromCache($modlogTable, $db);
     if (!(isset($modlogTableColumns['seq']) || array_key_exists('seq', $modlogTableColumns))) {
         throw new Tinebase_Exception_SystemGeneric('You need to update Tinebase before updating any other application');
     }
     // fetch modlog records for model
     $sql = "SELECT DISTINCT record_id,modification_time,seq " . "FROM {$modlogTable} WHERE record_type ='{$model}' " . "ORDER BY modification_time ASC ";
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' SQL for fetching modlogs: ' . $sql);
     }
     $result = $db->fetchAll($sql);
     if (empty($result)) {
         if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
             Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' No modlog records found for ' . $model);
         }
         return;
     }
     $recordSeqs = array();
     $updateSeqs = array();
     // collect modlog data
     foreach ($result as $modification) {
         if ($modification['seq'] != 0) {
             $recordSeqs[$modification['record_id']] = $modification['seq'];
             continue;
         }
         if (!isset($recordSeqs[$modification['record_id']])) {
             $seq = $recordSeqs[$modification['record_id']] = 1;
         } else {
             $seq = ++$recordSeqs[$modification['record_id']];
         }
         if (!isset($updateSeqs[$seq])) {
             $updateSeqs[$seq] = array();
         }
         $updateSeqs[$seq][] = array('record_id' => $modification['record_id'], 'modification_time' => $modification['modification_time']);
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Found ' . count($recordSeqs) . ' (different seqs: ' . count($updateSeqs) . ') records for modlog sequence update.');
     }
     // update modlog
     foreach ($updateSeqs as $seq => $modsBySeq) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Updating ' . count($modsBySeq) . ' modification(s) to seq ' . $seq);
         }
         $updateData = array('seq' => $seq);
         $i = 0;
         while ($i < count($modsBySeq)) {
             $whereArray = array();
             // step by 1000
             for ($j = 0; $j < 1000 && $i + $j < count($modsBySeq); $j++) {
                 $whereArray[] = '(' . $db->quoteInto('record_id = ?', $modsBySeq[$i + $j]['record_id']) . ' AND ' . $db->quoteInto('modification_time = ?', $modsBySeq[$i + $j]['modification_time']) . ')';
             }
             if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                 Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Stepping from ' . $i . ' to ' . ($i + $j) . '(' . count($whereArray) . ' mods)');
             }
             if (count($whereArray) > 0) {
                 $where = implode(' OR ', $whereArray);
                 $db->update($modlogTable, $updateData, $where);
             }
             $i += $j;
         }
     }
     // update records
     $maxSeqs = array();
     foreach ($recordSeqs as $recordId => $maxSeq) {
         $maxSeqs[$maxSeq][] = (string) $recordId;
     }
     foreach ($maxSeqs as $maxSeq => $recordIds) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Setting max seq to ' . $maxSeq . ' for ' . count($recordIds) . ' record(s).');
         }
         $updateData = array('seq' => $maxSeq);
         $where = $db->quoteInto($db->quoteIdentifier('id') . ' IN (?)', (array) $recordIds);
         try {
             $db->update(SQL_TABLE_PREFIX . $recordTable, $updateData, $where);
         } catch (Zend_Db_Statement_Exception $zdse) {
             if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) {
                 Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Could not update record seq: ' . $zdse->getMessage());
             }
             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Data: ' . print_r($updateData, TRUE) . ' Where: ' . substr($where, 0, 256));
             }
         }
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Finished modlog sequence update for ' . $model);
     }
 }
예제 #19
0
 /**
  * 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);
     }
     $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'));
     $userRegistrationsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'registrations'));
     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);
         $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('login_name') . ' = ?', $user->accountLoginName));
         $userRegistrationsTable->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;
 }
 /**
  * get prefered extension of this account
  *
  * @param   int $_accountId the id of the account to get the prefered extension for
  * @return  array
  * @throws  Phone_Exception_NotFound
  */
 public function getPreferedExtension($_accountId)
 {
     $accountId = Tinebase_Model_User::convertUserIdToInt($_accountId);
     $extensionsTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'phone_extensions'));
     $select = $extensionsTable->select()->where($this->_db->quoteIdentifier('account_id') . ' = ?', $accountId);
     $row = $extensionsTable->fetchRow($select);
     if ($row === NULL) {
         throw new Phone_Exception_NotFound('No prefered extension found.');
     }
     return $row->toArray();
 }
 /**
  * testConcurrencyLinebreakMismatch
  * 
  * @see 0007140: normalize linebreaks in concurrency check
  */
 public function testConcurrencyLinebreakMismatch()
 {
     $utask = $this->_persistantTestTask1;
     $utask->description = 'description' . "\n";
     $utask = $this->_controller->update($utask);
     // change linebreak in db to \r\n
     $loggedMods = Tinebase_Timemachine_ModificationLog::getInstance()->getModifications('Tasks', $utask->getId(), 'Tasks_Model_Task', 'Sql', Tinebase_DateTime::now()->subMinute(5), $utask->last_modified_time);
     $this->assertEquals(1, count($loggedMods));
     $mod = $loggedMods[0]->toArray();
     $this->assertEquals('description', $mod['modified_attribute']);
     $mod['new_value'] = 'description' . "\r\n";
     $modlog = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'timemachine_modlog'));
     $modlog->update($mod, Tinebase_Core::getDb()->quoteInto('id = ?', $mod['id']));
     // this should still work as we normalize linebreaks in concurrency check
     $resolvableConcurrencyTask = clone $utask;
     $resolvableConcurrencyTask->last_modified_time = Tinebase_DateTime::now()->addHour(-1);
     $resolvableConcurrencyTask->description = 'description' . "\n";
     $task = $this->_controller->update($resolvableConcurrencyTask);
     $this->assertEquals('description' . "\n", $task->description);
 }
 /**
  * purge tables
  *
  * @param $orderedTables
  * @param $where
  */
 protected function _purgeTables($orderedTables, $where)
 {
     foreach ($orderedTables as $table) {
         try {
             $schema = Tinebase_Db_Table::getTableDescriptionFromCache(SQL_TABLE_PREFIX . $table);
         } catch (Zend_Db_Statement_Exception $zdse) {
             echo "\nCould not get schema (" . $zdse->getMessage() . "). Skipping table {$table}";
             continue;
         }
         if (!(isset($schema['is_deleted']) || array_key_exists('is_deleted', $schema)) || !(isset($schema['deleted_time']) || array_key_exists('deleted_time', $schema))) {
             continue;
         }
         $deleteCount = 0;
         try {
             $deleteCount = Tinebase_Core::getDb()->delete(SQL_TABLE_PREFIX . $table, $where);
         } catch (Zend_Db_Statement_Exception $zdse) {
             echo "\nFailed to purge deleted records for table {$table}. " . $zdse->getMessage();
         }
         if ($deleteCount > 0) {
             echo "\nCleared table {$table} (deleted {$deleteCount} records).";
         } else {
             echo "\nNothing to purge from {$table}";
         }
     }
 }
 /**
  * Returns Status identifier
  *
  * @param string $_egw14Status
  * @return id identifier
  */
 protected static function getStatus($_egw14Status)
 {
     static $stati;
     $oldstatus = strtoupper($_egw14Status);
     if (!isset($stati[$oldstatus])) {
         $statusTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'tasks_status'));
         $status = $statusTable->fetchRow($statusTable->getAdapter()->quoteInto('status LIKE ?', $oldstatus));
         if (!$status) {
             $identifier = $statusTable->insert(array('created_by' => Tinebase_Core::getUser()->getId(), 'creation_time' => Tinebase_DateTime::now()->get(Tinebase_Record_Abstract::ISO8601LONG), 'status' => $oldstatus));
             $stati[$oldstatus] = $identifier;
         } else {
             $stati[$oldstatus] = $status->identifier;
         }
     }
     return $stati[$oldstatus];
 }
 /**
  * checks if a given column {@param $_columnName} exists in table {@param $_tableName}.
  *
  * @param string $_columnName
  * @param string $_tableName
  * @return boolean
  */
 public function columnExists($_columnName, $_tableName)
 {
     $columns = Tinebase_Db_Table::getTableDescriptionFromCache(SQL_TABLE_PREFIX . $_tableName, $this->_db);
     return isset($columns[$_columnName]) || array_key_exists($_columnName, $columns);
 }
 /**
  * Inserts a table row with specified data.
  * Add support for CLOB/BLOB
  * Oracle does not support anonymous ('?') binds.
  *
  * @param mixed $table The table to insert data into.
  * @param array $bind Column-value pairs.
  * @return int The number of affected rows.
  */
 public function insert($table, array $bind)
 {
     // Get the table metadata
     $columns = Tinebase_Db_Table::getTableDescriptionFromCache($table);
     // Check the columns in the array against the database table
     // to identify BLOB (or CLOB) columns
     foreach (array_keys($bind) as $column) {
         if (in_array($columns[$column]['DATA_TYPE'], array('BLOB', 'CLOB'))) {
             $lobs[] = $column;
         }
     }
     // If there are no blob columns then use the normal insert procedure
     if (!isset($lobs)) {
         $i = 0;
         // extract and quote col names from the array keys
         $cols = array();
         $vals = array();
         foreach ($bind as $col => $val) {
             $cols[] = $this->quoteIdentifier($col, true);
             if ($val instanceof Zend_Db_Expr) {
                 $vals[] = $val->__toString();
                 unset($bind[$col]);
             } else {
                 // MOD: add to_date for date column
                 if ($val === date('Y-m-d H:i:s', strtotime($val))) {
                     $vals[] = "TO_DATE(" . ':' . $col . $i . ",'YYYY-MM-DD hh24:mi:ss')";
                 } else {
                     $vals[] = ':' . $col . $i;
                 }
                 unset($bind[$col]);
                 $bind[':' . $col . $i] = $val;
             }
             $i++;
         }
         // build the statement
         $sql = "INSERT INTO " . $this->quoteIdentifier($table, true) . ' (' . implode(', ', $cols) . ') ' . 'VALUES (' . implode(', ', $vals) . ')';
         // execute the statement and return the number of affected rows
         $stmt = $this->query($sql, $bind);
         $result = $stmt->rowCount();
     } else {
         // There are blobs in the $bind array so insert them separately
         $ociTypes = array('BLOB' => OCI_B_BLOB, 'CLOB' => OCI_B_CLOB);
         // Extract and quote col names from the array keys
         $i = 0;
         $cols = array();
         $vals = array();
         $lobData = array();
         $returning = array();
         foreach ($bind as $col => $val) {
             $cols[] = $this->quoteIdentifier($col, true);
             if (in_array($col, $lobs)) {
                 $lobs[array_search($col, $lobs)] = $this->quoteIdentifier($col, true);
                 $vals[] = 'EMPTY_' . $columns[$col]['DATA_TYPE'] . '()';
                 $lobData[':' . $col . $i] = array('ociType' => $ociTypes[$columns[$col]['DATA_TYPE']], 'data' => $val);
                 unset($bind[$col]);
                 $lobDescriptors[':' . $col . $i] = oci_new_descriptor($this->_connection, OCI_D_LOB);
                 $returning[] = ':' . $col . $i;
                 $bind[':' . $col . $i] = $lobDescriptors[':' . $col . $i];
             } elseif ($val instanceof Zend_Db_Expr) {
                 $vals[] = $val->__toString();
                 unset($bind[$col]);
             } else {
                 $vals[] = ':' . $col . $i;
                 unset($bind[$col]);
                 $bind[':' . $col . $i] = $val;
             }
             $i++;
         }
         // build the statement
         $sql = "INSERT INTO " . $this->quoteIdentifier($table, true) . ' (' . implode(', ', $cols) . ') ' . 'VALUES (' . implode(', ', $vals) . ') ' . 'RETURNING ' . implode(', ', $lobs) . ' ' . 'INTO ' . implode(', ', $returning);
         //Tinebase_Core::getLogger()->debug("SQL INSERT\n" . $sql);
         // Execute the statement
         $stmt = new Zend_Db_Statement_Oracle($this, $sql);
         foreach (array_keys($bind) as $name) {
             if (in_array($name, array_keys($lobData))) {
                 $stmt->bindParam($name, $bind[$name], $lobData[$name]['ociType'], -1);
             } else {
                 $stmt->bindParam($name, $bind[$name]);
             }
         }
         $this->_setExecuteMode(OCI_DEFAULT);
         //Execute without committing
         $stmt->execute();
         $this->_setExecuteMode(OCI_COMMIT_ON_SUCCESS);
         $result = $stmt->rowCount();
         // Write the LOB data & free the descriptor
         if (isset($lobDescriptors)) {
             foreach ($lobDescriptors as $name => $lobDescriptor) {
                 $lobDescriptor->write($lobData[$name]['data']);
                 $lobDescriptor->free();
             }
         }
     }
     return $result;
 }
 /**
  * purges mod log entries of given recordIds
  *
  * @param mixed [string|array|Tinebase_Record_RecordSet] $_recordIds
  * 
  * @todo should be removed when other tests do not need this anymore
  */
 public static function purgeLogs($_recordIds)
 {
     $table = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'timemachine_modlog'));
     foreach ((array) $_recordIds as $recordId) {
         $table->delete($table->getAdapter()->quoteInto('record_id = ?', $recordId));
     }
 }
예제 #27
0
 /**
  * get categories (-> tags)
  *
  * @param string $oldTableName [OPTIONAL]
  * @return  array  categories
  */
 private function getCategories($_oldTableName = NULL)
 {
     $cats = array();
     // get old table data
     $tableName = $_oldTableName != NULL ? $_oldTableName : $this->oldTablePrefix . 'categories';
     $table = new Tinebase_Db_Table(array('name' => $tableName));
     $rows = $table->fetchAll();
     // fill array
     $cats = array();
     foreach ($rows as $row) {
         $cats[$row->cat_id] = $row;
     }
     return $cats;
 }
 /**
  * checks if use table already has modlog fields
  *
  * @return bool
  */
 protected function _userTableHasModlogFields()
 {
     $schema = Tinebase_Db_Table::getTableDescriptionFromCache($this->_db->table_prefix . $this->_tableName, $this->_db);
     return isset($schema['creation_time']);
 }
 /**
  * update to 0.13
  * - rename Dialer app to 'Phone'
  */
 public function update_12()
 {
     // rename app in application table
     $appTable = new Tinebase_Db_Table(array('name' => SQL_TABLE_PREFIX . 'applications'));
     $appTable->update(array('name' => 'Phone'), "name = 'Dialer'");
     $this->setApplicationVersion('Tinebase', '0.13');
 }
 /**
  * rename or redefines column/field in database table
  * 
  * @param string tableName
  * @param Setup_Backend_Schema_Field declaration
  * @param string old column/field name 
  */
 public function alterCol($_tableName, Setup_Backend_Schema_Field_Abstract $_declaration, $_oldName = NULL)
 {
     $columns = Tinebase_Db_Table::getTableDescriptionFromCache(SQL_TABLE_PREFIX . $_tableName);
     $quotedName = $this->_db->quoteIdentifier($_declaration->name);
     foreach ($columns as $column) {
         // first we need to rename column because use some column name
         if ($column['COLUMN_NAME'] == $_declaration->name) {
             $tempName = $_declaration->name . Tinebase_Record_Abstract::generateUID(3);
             $this->_renameCol($_tableName, $_declaration->name, $tempName);
             // add new column
             $this->addCol($_tableName, $_declaration);
             $updatevalue = 'UPDATE ' . $this->_db->quoteIdentifier(SQL_TABLE_PREFIX . $_tableName) . ' SET ' . $quotedName . ' = ' . $this->_db->quoteIdentifier($tempName);
             $this->execQueryVoid($updatevalue);
             $this->dropCol($_tableName, $tempName);
             return;
         }
     }
     if (isset($_oldName) && $_oldName != $_declaration->name) {
         $this->_renameCol($_tableName, $_oldName, $_declaration->name);
     }
     $statement = "ALTER TABLE " . $this->_db->quoteIdentifier(SQL_TABLE_PREFIX . $_tableName) . " MODIFY ";
     $oldName = $_oldName;
     if ($_oldName == NULL) {
         $oldName = SQL_TABLE_PREFIX . $_declaration->name;
     }
     $statement .= $this->getFieldDeclarations($_declaration, $_tableName);
     $this->execQueryVoid($statement);
 }