public function deleteOther(ActiveSync_Model_SyncState $_syncState) { // remove all other synckeys $where = array($this->_db->quoteInto('device_id = ?', $_syncState->device_id), $this->_db->quoteInto('type = ?', $_syncState->type), $this->_db->quoteInto('counter != ?', $_syncState->counter)); $this->_db->delete(SQL_TABLE_PREFIX . 'acsync_synckey', $where); return true; }
public function getTableDataDump($tableName, $step = 100) { $sql = ''; if ($this->_read) { $quotedTableName = $this->_read->quoteIdentifier($tableName); $colunms = $this->_read->fetchRow('SELECT * FROM ' . $quotedTableName . ' LIMIT 1'); if ($colunms) { $arrSql = array(); $colunms = array_keys($colunms); $quote = $this->_read->getQuoteIdentifierSymbol(); $sql = 'INSERT INTO ' . $quotedTableName . ' (' . $quote . implode($quote . ', ' . $quote, $colunms) . $quote . ')'; $sql .= ' VALUES '; $startRow = 0; $select = $this->_read->select(); $select->from($tableName)->limit($step, $startRow); while ($data = $this->_read->fetchAll($select)) { $dataSql = array(); foreach ($data as $row) { $dataSql[] = $this->_read->quoteInto('(?)', $row); } $arrSql[] = $sql . implode(', ', $dataSql) . ';'; $startRow += $step; $select->limit($step, $startRow); } $sql = implode("\n", $arrSql) . "\n"; } } return $sql; }
/** * Should handle execution of the task, taking as much (optional) parameters as needed * * The parameters should be optional and failing to provide them should be handled by * the task */ public function execute($sourceId = null, $userId = null) { $now = new \MUtil_Db_Expr_CurrentTimestamp(); $values = array('gso_last_synch' => $now, 'gso_changed' => $now, 'gso_changed_by' => $userId); $where = $this->db->quoteInto('gso_id_source = ?', $sourceId); $this->db->update('gems__sources', $values, $where); }
public function isValid($value, $context = null) { $result = true; $this->_value = $value; $where = array(); $where[] = $this->dbAdapter->quoteInto("(p.url_id = ? OR pt.url_id = ?)", $value); if (isset($this->_data['id'])) { $where[] = $this->dbAdapter->quoteInto("(p.id <> ?)", $this->_data['id']); } if (isset($this->_data['type_id'])) { $where[] = $this->dbAdapter->quoteInto("(p.type_id = ?)", $this->_data['type_id']); } $where = implode(' AND ', $where); $sql = "SELECT COUNT(p.id) AS doubles\n FROM cms_page AS p\n LEFT JOIN cms_page_tr AS pt ON (p.id = pt.translation_id AND pt.language = '" . $this->_lang . "')\n WHERE {$where}"; //echo "\n\n$sql\n\n"; die(); $resultSet = $this->dbAdapter->fetchAll($sql); if (0 == count($resultSet)) { return false; } $row = $resultSet[0]; $result = $row['doubles'] == 0; if (!$result) { $this->_error(self::URLID_EXISTS); } return $result; }
/** * Overrule to implement snippet specific filtering and sorting. * * @param \MUtil_Model_ModelAbstract $model */ protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model) { $filter[] = $this->db->quoteInto("gr2t_id_respondent_track IN (\n SELECT gr2t2a_id_respondent_track\n FROM gems__respondent2track2appointment\n WHERE gr2t2a_id_appointment = ?)", $this->request->getParam(\Gems_Model::APPOINTMENT_ID)); // \MUtil_Model::$verbose = true; $model->setFilter($filter); $this->processSortOnly($model); }
/** * Generates an array of SQL insert statements that * will save the current * * @param array $resources * @access public * @return string */ public function generateInserts(array $resources) { $quotedName = $this->_db->quoteIdentifier('name'); $quotedDescription = $this->_db->quoteIdentifier('description'); $quotedFlagsTable = $this->_db->quoteIdentifier('flags'); $insertResourceTemplate = sprintf('INSERT IGNORE INTO %s (%s, %s) VALUES (?, ?);', $quotedFlagsTable, $quotedName, $quotedDescription); $selectResourceTemplate = sprintf('SET @flag_id := (SELECT id FROM %s WHERE %s = ?);', $quotedFlagsTable, $quotedName); $insertPrivilegeTemplate = '(@flag_id, %s, %s)'; $inserts = array(); foreach ($resources as $resource) { // ready the insert resource query $insertResourceSql = $this->_db->quoteInto($insertResourceTemplate, $resource['name'], NULL, 1); $insertResourceSql = $this->_db->quoteInto($insertResourceSql, $resource['description'], NULL, 1); // ready the select resource query $selectResourceSql = $this->_db->quoteInto($selectResourceTemplate, $resource['name']); // ready the insert privilege query $insertPrivilegeSql = sprintf('INSERT IGNORE INTO %s (%s, %s, %s) VALUES ', $this->_db->quoteIdentifier('privileges'), $this->_db->quoteIdentifier('flag_id'), $quotedName, $quotedDescription); $insertPrivilegeSqlParts = array(); foreach ($resource['methods'] as $method) { $insertPrivilegeSqlParts[] = sprintf($insertPrivilegeTemplate, $this->_db->quote($method['name']), $this->_db->quote($method['description'])); } $inserts[] = $insertResourceSql . PHP_EOL . $selectResourceSql . PHP_EOL . $insertPrivilegeSql . PHP_EOL . "\t" . implode(',' . PHP_EOL . "\t", $insertPrivilegeSqlParts) . ';' . PHP_EOL; } return $inserts; }
/** * get switch case expression with multiple cases * * @param string $field * @param array $cases * * @return Zend_Db_Expr */ public function getSwitch($field, $cases) { $case = 'CASE ' . $this->_adapter->quoteIdentifier($field) . ' '; foreach ($cases as $when => $then) { $case .= $this->_adapter->quoteInto(' WHEN ' . $when . ' THEN ?', $then); } $case .= ' END'; return new Zend_Db_Expr($case); }
/** * Overrule to implement snippet specific filtering and sorting. * * @param \MUtil_Model_ModelAbstract $model */ protected function processFilterAndSort(\MUtil_Model_ModelAbstract $model) { parent::processFilterAndSort($model); $appId = $this->request->getParam(\Gems_Model::APPOINTMENT_ID); if ($appId) { $appKeyPrefix = $this->db->quote(FieldsDefinition::makeKey(FieldMaintenanceModel::APPOINTMENTS_NAME, '')); $appSource = $this->db->quote(\Gems_Tracker_Engine_StepEngineAbstract::APPOINTMENT_TABLE); $or[] = $this->db->quoteInto("gro_valid_after_source = {$appSource} AND\n (gto_id_respondent_track, gro_valid_after_field) IN\n (SELECT gr2t2a_id_respondent_track, CONCAT({$appKeyPrefix}, gr2t2a_id_app_field)\n FROM gems__respondent2track2appointment\n WHERE gr2t2a_id_appointment = ?)", $appId); $or[] = $this->db->quoteInto("gro_valid_for_source = {$appSource} AND\n (gto_id_respondent_track, gro_valid_for_field) IN\n (SELECT gr2t2a_id_respondent_track, CONCAT({$appKeyPrefix}, gr2t2a_id_app_field)\n FROM gems__respondent2track2appointment\n WHERE gr2t2a_id_appointment = ?)", $appId); } $model->addFilter(array('(' . implode(') OR (', $or) . ')')); }
/** * Should handle execution of the task, taking as much (optional) parameters as needed * * The parameters should be optional and failing to provide them should be handled by * the task */ public function execute($lineNr = null, $forRoundOrder = null, $usesRoundRound = null, $roundField = null) { $batch = $this->getBatch(); $import = $batch->getVariable('import'); if (!(isset($import['trackId']) && $import['trackId'])) { // Do nothing return; } if (isset($import['roundOrders'][$usesRoundRound]) && $import['roundOrders'][$usesRoundRound]) { $this->db->update('gems__rounds', array($roundField => $import['roundOrders'][$usesRoundRound]), $this->db->quoteInto("gro_id_order = ? AND ", $forRoundOrder) . $this->db->quoteInto("gro_id_track = ?", $import['trackId'])); } }
/** * Should handle execution of the task, taking as much (optional) parameters as needed * * The parameters should be optional and failing to provide them should be handled by * the task */ public function execute() { $role = \Gems_Roles::getInstance(); $parents = $this->db->fetchPairs("SELECT grl_id_role, grl_parents FROM gems__roles"); // \MUtil_Echo::track($parents); if ($parents) { foreach ($parents as $id => $priv) { $values['grl_parents'] = implode(',', $role->translateToRoleIds($priv)); $this->db->update('gems__roles', $values, $this->db->quoteInto('grl_id_role = ?', $id)); } } }
/** * Hook that loads the form data from $_POST or the model * * Or from whatever other source you specify here. */ protected function loadFormData() { parent::loadFormData(); if ($this->request->isPost()) { if (!$this->_saveButton || !$this->_saveButton->isChecked()) { if (isset($this->formData['grs_ssn']) && $this->formData['grs_ssn']) { $filter = array('grs_ssn' => $this->formData['grs_ssn'], 'gr2o_id_organization' => true); if ($this->formData['gr2o_id_organization']) { $orgId = $this->formData['gr2o_id_organization']; } else { $orgId = $this->model->get('gr2o_id_organization', 'default'); } $order = array($this->db->quoteInto("CASE WHEN gr2o_id_organization = ? THEN 1 ELSE 2 END", $orgId) => SORT_ASC); $data = $this->model->loadFirst($filter, $order); if ($data && !isset($this->formData[$this->saveButtonId])) { // \MUtil_Echo::track($this->formData); // \MUtil_Echo::track($data); // Do not use this value unset($data['grs_ssn']); if ($data['gr2o_id_organization'] == $orgId) { // gr2o_patient_nr // gr2o_id_organization $this->addMessage($this->_('Known respondent.')); //* foreach ($data as $name => $value) { if (substr($name, 0, 4) == 'grs_' || substr($name, 0, 5) == 'gr2o_') { if (array_key_exists($name, $this->formData)) { $this->formData[$name] = $value; } $cname = $this->model->getKeyCopyName($name); if (array_key_exists($cname, $this->formData)) { $this->formData[$cname] = $value; } } } // */ } else { $org = $this->loader->getOrganization($data['gr2o_id_organization']); $this->addMessage(sprintf($this->_('Respondent data retrieved from %s.'), $org->getName())); foreach ($data as $name => $value) { if (substr($name, 0, 4) == 'grs_' && array_key_exists($name, $this->formData)) { $this->formData[$name] = $value; } } } } } } } }
/** * Checks if the user is allowed to login or is blocked * * An adapter authorizes and if the end resultis boolean, string or array * it is converted into a \Zend_Auth_Result. * * @return mixed \Zend_Auth_Adapter_Interface|\Zend_Auth_Result|boolean|string|array */ protected function authorizeBlock() { try { $select = $this->db->select(); $select->from('gems__user_login_attempts', array('UNIX_TIMESTAMP(gula_block_until) - UNIX_TIMESTAMP() AS wait'))->where('gula_block_until is not null')->where('gula_login = ?', $this->getLoginName())->where('gula_id_organization = ?', $this->getCurrentOrganizationId())->limit(1); // Not the first login if ($block = $this->db->fetchOne($select)) { if ($block > 0) { $minutes = intval($block / 60) + 1; // Report all is not well return sprintf($this->plural('Your account is temporarily blocked, please wait a minute.', 'Your account is temporarily blocked, please wait %d minutes.', $minutes), $minutes); } else { // Clean the block once it's past $values['gula_failed_logins'] = 0; $values['gula_last_failed'] = null; $values['gula_block_until'] = null; $where = $this->db->quoteInto('gula_login = ? AND ', $this->getLoginName()); $where .= $this->db->quoteInto('gula_id_organization = ?', $this->getCurrentOrganizationId()); $this->db->update('gems__user_login_attempts', $values, $where); } } } catch (\Zend_Db_Exception $e) { // Fall through as this does not work if the database upgrade did not run // \MUtil_Echo::r($e); } return true; }
public function load($object, $customerId) { $select = $this->_read->select(); $select->from($this->_customerTable, array('login_at', 'logout_at'))->joinInner($this->_visitorTable, $this->_visitorTable . '.visitor_id=' . $this->_customerTable . '.visitor_id', array('last_visit_at'))->joinInner($this->_visitorInfoTable, $this->_visitorTable . '.visitor_id=' . $this->_visitorInfoTable . '.visitor_id', array('http_referer', 'remote_addr'))->joinInner($this->_urlInfoTable, $this->_urlInfoTable . '.url_id=' . $this->_visitorTable . '.last_url_id', array('url'))->where($this->_read->quoteInto($this->_customerTable . '.customer_id=?', $customerId))->order($this->_customerTable . '.login_at desc')->limit(1); $object->setData($this->_read->fetchRow($select)); return $object; }
/** * @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; }
/** * converts category to tag * * @param int $catId * @return string tagid */ public function getTag($catId) { if (!(isset($this->_tagMapCache[$catId]) || array_key_exists($catId, $this->_tagMapCache))) { $select = $this->_egwDb->select()->from(array('cats' => 'egw_categories'))->where($this->_egwDb->quoteInto($this->_egwDb->quoteIdentifier('cat_id') . ' = ?', $catId)); $cat = $this->_egwDb->fetchAll($select, NULL, Zend_Db::FETCH_ASSOC); $cat = count($cat) === 1 ? $cat[0] : NULL; if (!$cat) { $this->_log->DEBUG(__METHOD__ . '::' . __LINE__ . " category {$catId} not found in egw, skipping tag"); return $this->_tagMapCache[$catId] = NULL; } $tineDb = Tinebase_Core::getDb(); $select = $tineDb->select()->from(array('tags' => $tineDb->table_prefix . 'tags'))->where($tineDb->quoteInto($tineDb->quoteIdentifier('name') . ' LIKE ?', $cat['cat_name'])); $tag = $tineDb->fetchAll($select, NULL, Zend_Db::FETCH_ASSOC); $tag = count($tag) > 0 ? $tag[0] : NULL; if ($tag) { return $this->_tagMapCache[$catId] = $tag['id']; } // create tag $catData = unserialize($cat['cat_data']); $tagId = Tinebase_Record_Abstract::generateUID(); $tagType = $cat['cat_access'] == 'public' ? Tinebase_Model_Tag::TYPE_SHARED : Tinebase_Model_Tag::TYPE_PERSONAL; $tagOwner = $tagType == Tinebase_Model_Tag::TYPE_SHARED ? 0 : $this->mapAccountIdEgw2Tine($cat['cat_owner']); $this->_log->NOTICE(__METHOD__ . '::' . __LINE__ . " creating new {$tagType} tag '{$cat['cat_name']}'"); $tineDb->insert($tineDb->table_prefix . 'tags', array('id' => $tagId, 'type' => $tagType, 'owner' => $tagOwner, 'name' => $cat['cat_name'], 'description' => $cat['cat_description'], 'color' => $catData['color'], 'created_by' => $tagOwner ? $tagOwner : Tinebase_Core::getUser()->getId(), 'creation_time' => $cat['last_mod'] ? $this->convertDate($cat['last_mod']) : Tinebase_DateTime::now())); $right = new Tinebase_Model_TagRight(array('tag_id' => $tagId, 'account_type' => $tagType == Tinebase_Model_Tag::TYPE_SHARED ? Tinebase_Acl_Rights::ACCOUNT_TYPE_ANYONE : Tinebase_Acl_Rights::ACCOUNT_TYPE_USER, 'account_id' => $tagOwner, 'view_right' => true, 'use_right' => true)); Tinebase_Tags::getInstance()->setRights($right); Tinebase_Tags::getInstance()->setContexts(array(0), $tagId); $this->_tagMapCache[$catId] = $tagId; } return $this->_tagMapCache[$catId]; }
/** * reset list of stored id * * @param Syncope_Model_IDevice|string $_deviceId * @param Syncope_Model_IFolder|string $_folderId */ public function resetState($_deviceId, $_folderId) { $deviceId = $_deviceId instanceof Syncope_Model_IDevice ? $_deviceId->id : $_deviceId; $folderId = $_folderId instanceof Syncope_Model_IFolder ? $_folderId->id : $_folderId; $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('device_id') . ' = ?', $deviceId), $this->_db->quoteInto($this->_db->quoteIdentifier('folder_id') . ' = ?', $folderId)); $this->_db->delete($this->_tablePrefix . 'content', $where); }
/** * delete containers, configs and other data of an application * * NOTE: if a table with foreign key constraints to applications is added, we need to make sure that the data is deleted here * * @param Tinebase_Model_Application $_applicationName * @return void */ public function removeApplicationData(Tinebase_Model_Application $_application) { $dataToDelete = array('container' => array('tablename' => ''), 'config' => array('tablename' => ''), 'customfield' => array('tablename' => ''), 'rights' => array('tablename' => 'role_rights'), 'definitions' => array('tablename' => 'importexport_definition'), 'filter' => array('tablename' => 'filter')); $countMessage = ' Deleted'; $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('application_id') . '= ?', $_application->getId())); foreach ($dataToDelete as $dataType => $info) { switch ($dataType) { case 'container': $count = Tinebase_Container::getInstance()->deleteContainerByApplicationId($_application->getId()); break; case 'config': $count = Tinebase_Config::getInstance()->deleteConfigByApplicationId($_application->getId()); break; case 'customfield': $count = Tinebase_CustomField::getInstance()->deleteCustomFieldsForApplication($_application->getId()); break; default: if (array_key_exists('tablename', $info) && !empty($info['tablename'])) { $count = $this->_db->delete(SQL_TABLE_PREFIX . $info['tablename'], $where); } else { Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' No tablename defined for ' . $dataType); $count = 0; } } $countMessage .= ' ' . $count . ' ' . $dataType . '(s) /'; } $countMessage .= ' for application ' . $_application->name; Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . $countMessage); }
public function addConfigField($path, $label, array $data = array(), $default = null) { $data['level'] = sizeof(explode('/', $path)); $data['path'] = $path; $data['frontend_label'] = $label; if ($id = $this->getTableRow('core/config_field', 'path', $path, 'field_id')) { $this->updateTableRow('core/config_field', 'field_id', $id, $data); } else { if (empty($data['sort_order'])) { $sql = "select max(sort_order) cnt from " . $this->getTable('core/config_field') . " where level=" . ($data['level'] + 1); if ($data['level'] > 1) { $sql .= $this->_conn->quoteInto(" and path like ?", dirname($path) . '/%'); } $result = $this->_conn->raw_fetchRow($sql); $this->_conn->fetchAll($sql); #print_r($result); die; $data['sort_order'] = $result['cnt'] + 1; /* // Triggers "Command out of sync" mysql error for next statement!?!? $data['sort_order'] = $this->_conn->fetchOne("select max(sort_order) from ".$this->getTable('core/config_field')." where level=?".$parentWhere, $data['level'])+1; */ } #$this->_conn->raw_query("insert into ".$this->getTable('core/config_field')." (".join(',', array_keys($data)).") values ('".join("','", array_values($data))."')"); $this->_conn->insert($this->getTable('core/config_field'), $data); } if (!is_null($default)) { $this->setConfigData($path, $default); } return $this; }
/** * _authenticateCreateSelect() - This method creates a Zend_Db_Select object that * is completely configured to be queried against the database. * * @return Zend_Db_Select */ protected function _authenticateCreateSelect() { // build credential expression if (empty($this->_credentialTreatment) || (strpos($this->_credentialTreatment, '?') === false)) { $this->_credentialTreatment = '?'; } $credentialExpression = new Zend_Db_Expr( '(CASE WHEN ' . $this->_zendDb->quoteInto( $this->_zendDb->quoteIdentifier($this->_credentialColumn, true) . ' = ' . $this->_credentialTreatment, $this->_credential ) . ' THEN 1 ELSE 0 END) AS ' . $this->_zendDb->quoteIdentifier( $this->_zendDb->foldCase('zend_auth_credential_match') ) ); // get select $dbSelect = clone $this->getDbSelect(); $dbSelect->from($this->_tableName, array('*', $credentialExpression)) ->where($this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity); return $dbSelect; }
/** * delete groups in sql backend * * @param array $groupIds */ public function deleteGroupsInSqlBackend($groupIds) { $where = $this->_db->quoteInto($this->_db->quoteIdentifier('group_id') . ' IN (?)', (array) $groupIds); $this->groupMembersTable->delete($where); $where = $this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' IN (?)', (array) $groupIds); $this->groupsTable->delete($where); }
/** * 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; }
/** * Saves the properties to the database. * * This performs an intelligent insert/update, and reloads the * properties with fresh data from the table on success. * * @return integer 0 on failure, 1 on success. */ public function save() { // convenience var for the primary key name $primary = $this->_info['primary']; // check the primary key value for insert/update if (empty($this->_data[$primary])) { // no primary key value, must be an insert. // make sure it's null. $this->_data[$primary] = null; // attempt the insert. $result = $this->_table->insert($this->_data); if (is_numeric($result)) { // insert worked, refresh with data from the table $this->_data[$primary] = $result; $this->_refresh(); } } else { // has a primary key value, update only that key. $where = $this->_db->quoteInto("{$primary} = ?", $this->_data[$primary]); // return the result of the update attempt, // no need to update the row object. $result = $this->_table->update($this->_data, $where); if (is_int($result)) { // update worked, refresh with data from the table $this->_refresh(); } } // regardless of success return the result return $result; }
/** * Move tree node * * @param Varien_Data_Tree_Node $node * @param Varien_Data_Tree_Node $parentNode * @param Varien_Data_Tree_Node $prevNode */ public function move($category, $newParent, $prevNode = null) { $position = 1; $oldPath = $category->getData($this->_pathField); $newPath = $newParent->getData($this->_pathField); $newPath = $newPath . '/' . $category->getId(); $oldPathLength = strlen($oldPath); $data = array($this->_pathField => new Zend_Db_Expr("CONCAT('{$newPath}', RIGHT({$this->_pathField}, LENGTH({$this->_pathField}) - {$oldPathLength}))")); $condition = $this->_conn->quoteInto("{$this->_pathField} REGEXP ?", "^{$oldPath}(/|\$)"); $this->_conn->beginTransaction(); try { if ($prevNode && $prevNode->getId()) { $reorderData = array($this->_orderField => new Zend_Db_Expr("{$this->_orderField} + 1")); $reorderCondition = "{$this->_orderField} > {$prevNode->getData($this->_orderField)}"; $this->_conn->update($this->_table, $reorderData, $reorderCondition); $position = $prevNode->getData($this->_orderField) + 1; } $this->_conn->update($this->_table, $data, $condition); $this->_conn->update($this->_table, array($this->_orderField => $position), $this->_conn->quoteInto("{$this->_idField} = ?", $category->getId())); $this->_conn->commit(); } catch (Exception $e) { $this->_conn->rollBack(); throw new Exception("Can't move tree node due to error: " . $e->getMessage()); } }
/** * delete groups * * @param mixed $_groupId * @throws Tinebase_Exception_Backend */ public function deleteGroups($_groupId) { $groupIds = array(); if (is_array($_groupId) or $_groupId instanceof Tinebase_Record_RecordSet) { foreach ($_groupId as $groupId) { $groupIds[] = Tinebase_Model_Group::convertGroupIdToInt($groupId); } } else { $groupIds[] = Tinebase_Model_Group::convertGroupIdToInt($_groupId); } try { $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction(Tinebase_Core::getDb()); $where = $this->_db->quoteInto($this->_db->quoteIdentifier('group_id') . ' IN (?)', $groupIds); $this->groupMembersTable->delete($where); $where = $this->_db->quoteInto($this->_db->quoteIdentifier('id') . ' IN (?)', $groupIds); $this->groupsTable->delete($where); if ($this instanceof Tinebase_Group_Interface_SyncAble) { $this->deleteGroupsInSyncBackend($groupIds); } Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId); } catch (Exception $e) { Tinebase_TransactionManager::getInstance()->rollBack(); throw new Tinebase_Exception_Backend($e->getMessage()); } }
/** * Returns true if and only if $value meets the validation requirements * * If $value fails validation, then this method returns false, and * getMessages() will return an array of messages that explain why the * validation failed. * * @param mixed $value * @return boolean * @throws \Zend_Valid_Exception If validation of $value is impossible */ public function isValid($value) { if ($throttleSettings = $this->project->getAskThrottleSettings()) { // Prune the database for (very) old attempts $where = $this->db->quoteInto('gta_datetime < DATE_SUB(NOW(), INTERVAL ? second)', $throttleSettings['period'] * 20); $this->db->delete('gems__token_attempts', $where); // Retrieve the number of failed attempts that occurred within the specified window $select = $this->db->select(); $select->from('gems__token_attempts', array(new \Zend_Db_Expr('COUNT(*) AS attempts'), new \Zend_Db_Expr('UNIX_TIMESTAMP(MAX(gta_datetime)) - UNIX_TIMESTAMP() AS last')))->where('gta_datetime > DATE_SUB(NOW(), INTERVAL ? second)', $throttleSettings['period']); $attemptData = $this->db->fetchRow($select); $remainingDelay = $attemptData['last'] + $throttleSettings['delay']; // \MUtil_Echo::track($throttleSettings, $attemptData, $remainingDelay); if ($attemptData['attempts'] > $throttleSettings['threshold'] && $remainingDelay > 0) { $this->logger->log("Possible token brute force attack, throttling for {$remainingDelay} seconds", \Zend_Log::ERR); $this->_messages = $this->translate->_('The server is currently busy, please wait a while and try again.'); return false; } } // The pure token check if ($this->isValidToken($value)) { return true; } $max_length = $this->tracker->getTokenLibrary()->getLength(); $this->db->insert('gems__token_attempts', array('gta_id_token' => substr($value, 0, $max_length), 'gta_ip_address' => $this->getRequest()->getClientIp())); return false; }
protected function _addDeclarationDefaultValue(array $_buffer, Setup_Backend_Schema_Field_Abstract $_field) { if (isset($_field->default)) { $_buffer[] = $this->_db->quoteInto("DEFAULT ?", $_field->default); } return $_buffer; }
public function loadEnsuredNodes($category, $rootNode) { $pathIds = $category->getPathIds(); $rootNodeId = $rootNode->getId(); $rootNodePath = $rootNode->getData($this->_pathField); $select = clone $this->_select; $select->order($this->_table . '.' . $this->_orderField . ' ASC'); if ($pathIds) { $condition = $this->_conn->quoteInto("{$this->_table}.{$this->_idField} in (?)", $pathIds); $select->where($condition); } $arrNodes = $this->_conn->fetchAll($select); if ($arrNodes) { $childrenItems = array(); foreach ($arrNodes as $nodeInfo) { $nodeId = $nodeInfo[$this->_idField]; if ($nodeId <= $rootNodeId) { continue; } $pathToParent = explode('/', $nodeInfo[$this->_pathField]); array_pop($pathToParent); $pathToParent = implode('/', $pathToParent); $childrenItems[$pathToParent][] = $nodeInfo; } $this->_addChildNodes($childrenItems, $rootNodePath, $rootNode, true); } }
/** * sets etags, expects ids as keys and etags as value * * @param array $etags * * @todo maybe we should find a better place for the etag functions as this is currently only used in Calendar + Tasks */ public function setETags(array $etags) { foreach ($etags as $id => $etag) { $where = array($this->_db->quoteInto($this->_db->quoteIdentifier($this->_identifier) . ' = ?', $id)); $this->_db->update($this->_tablePrefix . $this->_tableName, array('etag' => $etag), $where); } }
/** * Render sql select conditions * * @return Varien_Data_Collection_Db */ protected function _renderFilters() { if ($this->_isFiltersRendered) { return $this; } $this->_renderFiltersBefore(); foreach ($this->_filters as $filter) { switch ($filter['type']) { case 'or': $condition = $this->_conn->quoteInto($filter['field'] . '=?', $filter['value']); $this->_select->orWhere($condition); break; case 'string': $this->_select->where($filter['value']); break; case 'public': $field = $this->_getMappedField($filter['field']); $condition = $filter['value']; $this->_select->where($this->_getConditionSql($field, $condition), null, Varien_Db_Select::TYPE_CONDITION); break; default: $condition = $this->_conn->quoteInto($filter['field'] . '=?', $filter['value']); $this->_select->where($condition); } } $this->_isFiltersRendered = true; return $this; }
public function loadEnsuredNodes($category, $rootNode) { $pathIds = $category->getPathIds(); $rootNodeId = $rootNode->getId(); $rootNodePath = $rootNode->getData($this->_pathField); $select = clone $this->_select; // $select->order($this->_table.'.'.$this->_orderField . ' ASC'); if ($pathIds) { $condition = $this->_conn->quoteInto("{$this->_table}.{$this->_idField} in (?)", $pathIds); $select->where($condition); } $select->joinLeft(array('t6' => 'catalog_category_entity_varchar'), '(catalog_category_entity.entity_id = t6.entity_id and t6.attribute_id = 111)', array('t6.value as name')); $select->order('' . $this->_orderField . ' ASC'); // print_r((string)$select);die; $arrNodes = $this->_conn->fetchAll($select); if ($arrNodes) { $childrenItems = array(); foreach ($arrNodes as $nodeInfo) { $nodeId = $nodeInfo[$this->_idField]; if ($nodeId <= $rootNodeId) { continue; } $pathToParent = explode('/', $nodeInfo[$this->_pathField]); array_pop($pathToParent); $pathToParent = implode('/', $pathToParent); $childrenItems[$pathToParent][] = $nodeInfo; } $this->_addChildNodes($childrenItems, $rootNodePath, $rootNode, true); } }