public function saveRel(Mage_Admin_Model_Permissions_Rules $rule) { $this->_write->beginTransaction(); try { $roleId = $rule->getRoleId(); $this->_write->delete($this->_ruleTable, "role_id = {$roleId}"); $masterResources = Mage::getModel('admin/permissions_roles')->getResourcesList2D(); $masterAdmin = false; if ($postedResources = $rule->getResources()) { foreach ($masterResources as $index => $resName) { if (!$masterAdmin) { $permission = in_array($resName, $postedResources) ? 'allow' : 'deny'; $this->_write->insert($this->_ruleTable, array('role_type' => 'G', 'resource_id' => trim($resName, '/'), 'privileges' => '', 'assert_id' => 0, 'role_id' => $roleId, 'permission' => $permission)); } if ($resName == 'all' && $permission == 'allow') { $masterAdmin = true; } } } $this->_write->commit(); } catch (Mage_Core_Exception $e) { throw $e; } catch (Exception $e) { $this->_write->rollBack(); } }
/** * create new folder state * * @param Syncope_Model_IFolder $_folder * @return Syncope_Model_IFolder */ public function create(Syncope_Model_IFolder $_folder) { $id = sha1(mt_rand() . microtime()); $deviceId = $_folder->device_id instanceof Syncope_Model_IDevice ? $_folder->device_id->id : $_folder->device_id; $this->_db->insert($this->_tablePrefix . 'folder', array('id' => $id, 'device_id' => $deviceId, 'class' => $_folder->class, 'folderid' => $_folder->folderid instanceof Syncope_Model_IFolder ? $_folder->folderid->id : $_folder->folderid, 'parentid' => $_folder->parentid, 'displayname' => $_folder->displayname, 'type' => $_folder->type, 'creation_time' => $_folder->creation_time->format('Y-m-d H:i:s'), 'lastfiltertype' => $_folder->lastfiltertype)); return $this->get($id); }
/** * Trigger an import run * * @return int Last import run ID */ public function run() { if ($this->providesChanges() && !$this->rowsetExists()) { $this->storeRowset(); } $this->db->insert('import_run', array('source_id' => $this->source->id, 'rowset_checksum' => $this->rowsetChecksum(), 'start_time' => date('Y-m-d H:i:s'), 'succeeded' => 'y')); return $this->db->lastInsertId(); }
/** * create new content state * * @param Syncope_Model_IContent $_state * @return Syncope_Model_IContent */ public function create(Syncope_Model_IContent $_state) { $id = sha1(mt_rand() . microtime()); $deviceId = $_state->device_id instanceof Syncope_Model_IDevice ? $_state->device_id->id : $_state->device_id; $folderId = $_state->folder_id instanceof Syncope_Model_IFolder ? $_state->folder_id->id : $_state->folder_id; $this->_db->insert($this->_tablePrefix . 'content', array('id' => $id, 'device_id' => $deviceId, 'folder_id' => $folderId, 'contentid' => $_state->contentid, 'creation_time' => $_state->creation_time->format('Y-m-d H:i:s'), 'creation_synckey' => $_state->creation_synckey, 'is_deleted' => isset($_state->is_deleted) ? (int) (!!$_state->is_deleted) : 0)); return $this->get($id); }
/** * Fetch the schema version of the current database * * @return string */ public final function getSchemaVersion() { if (!in_array('schema_info', $this->dbAdapter->listTables())) { $this->createTable('schema_info', array('primary' => false), array(array('version', 'string'))); $this->dbAdapter->insert('schema_info', array('version' => '00000000000000')); return '00000000000000'; } return $this->dbAdapter->fetchOne($this->dbAdapter->select()->from('schema_info', 'version')->limit(1)); }
/** * @param $shadowPath * @param $newPath * @param $oldPath * @param $newShadowPath * @param $oldShadowPath */ public function copyTreeByShadowPath($shadowPath, $newPath, $oldPath, $newShadowPath, $oldShadowPath) { $select = $this->_db->select()->from($this->_tablePrefix . $this->_tableName, array('path' => new Zend_Db_Expr($this->_db->quoteInto($this->_db->quoteInto('REPLACE(path, ?', $oldPath) . ', ?)', $newPath)), 'shadow_path' => new Zend_Db_Expr($this->_db->quoteInto($this->_db->quoteInto('REPLACE(shadow_path, ?', $oldShadowPath) . ', ?)', $newShadowPath)), 'record_id' => 'record_id', 'creation_time' => new Zend_Db_Expr('NOW()')))->where($this->_db->quoteInto($this->_db->quoteIdentifier('shadow_path') . ' like ?', $shadowPath . '/%')); $stmt = $this->_db->query($select); $entries = $stmt->fetchAll(Zend_Db::FETCH_ASSOC); foreach ($entries as $entry) { $entry['id'] = Tinebase_Record_Abstract::generateUID(); $this->_db->insert($this->_tablePrefix . $this->_tableName, $entry); } }
/** * create new sync state * * @param Syncope_Model_ISyncState $_syncState * @return Syncope_Model_SyncState */ public function create(Syncope_Model_ISyncState $_syncState, $_keepPreviousSyncState = true) { $id = sha1(mt_rand() . microtime()); $deviceId = $_syncState->device_id instanceof Syncope_Model_IDevice ? $_syncState->device_id->id : $_syncState->device_id; $this->_db->insert($this->_tablePrefix . 'synckey', array('id' => $id, 'device_id' => $deviceId, 'type' => $_syncState->type instanceof Syncope_Model_IFolder ? $_syncState->type->id : $_syncState->type, 'counter' => $_syncState->counter, 'lastsync' => $_syncState->lastsync->format('Y-m-d H:i:s'), 'pendingdata' => isset($_syncState->pendingdata) && is_array($_syncState->pendingdata) ? Zend_Json::encode($_syncState->pendingdata) : null)); $state = $this->get($id); if ($_keepPreviousSyncState !== true) { // remove all other synckeys $this->_deleteOtherStates($state); } return $state; }
/** * (non-PHPdoc) * @see Log::log() */ public function log($message) { try { $result = $this->_db->insert($this->_table, array($this->_logFields['name'] => $this->_name, $this->_logFields['message'] => $message, $this->_logFields['date'] => date('Y-m-d H:i:s'))); if (!$result) { throw new Exception('cannot save log to db '); } return true; } catch (Exception $e) { $this->_lastError = $e->getMessage(); return false; } }
/** * Log the communication for the respondent. */ protected function logRespondentCommunication() { $currentUserId = $this->loader->getCurrentUser()->getUserId(); $changeDate = new \MUtil_Db_Expr_CurrentTimestamp(); $logData['grco_id_to'] = $this->respondent->getId(); if (!is_int($this->by)) { $this->by = 0; } $logData['grco_id_by'] = $this->by; $logData['grco_organization'] = $this->organizationId; $logData['grco_id_token'] = $this->token->getTokenId(); $logData['grco_method'] = 'email'; $logData['grco_topic'] = substr($this->applyFields($this->subject), 0, 120); $to = array(); foreach ($this->to as $name => $address) { $to[] = $name . '<' . $address . '>'; } $logData['grco_address'] = substr(join(',', $to), 0, 120); $logData['grco_sender'] = substr($this->from, 0, 120); $logData['grco_id_message'] = $this->templateId ? $this->templateId : null; $logData['grco_changed'] = $changeDate; $logData['grco_changed_by'] = $this->by; $logData['grco_created'] = $changeDate; $logData['grco_created_by'] = $this->by; $this->db->insert('gems__log_respondent_communications', $logData); }
/** * * @param string $action * @return array */ protected function getAction($action) { if (array_key_exists($action, $this->_actions)) { return $this->_actions[$action]; } // Check if a refresh from the db fixes the problem $this->_actions = $this->_getActionsDb(); if (array_key_exists($action, $this->_actions)) { return $this->_actions[$action]; } $values['gls_name'] = $action; $values['gls_when_no_user'] = 0; $values['gls_on_action'] = 0; $values['gls_on_post'] = 0; // preg_match('/(create|edit)/', $action); $values['gls_on_change'] = preg_match('/(create|edit|delete|deactivate|reactivate)/', $action); $values['gls_changed'] = $values['gls_created'] = new \MUtil_Db_Expr_CurrentTimestamp(); $values['gls_changed_by'] = $values['gls_created_by'] = \Gems_User_UserLoader::SYSTEM_USER_ID; try { $this->_db->insert('gems__log_setup', $values); $this->_actions = $this->_getActionsDb(); if (array_key_exists($action, $this->_actions)) { return $this->_actions[$action]; } } catch (\Exception $exc) { $this->_warn(); } return array('gls_id_action' => 0, 'gls_when_no_user' => 0, 'gls_on_action' => 0, 'gls_on_post' => 0, 'gls_on_change' => 0); }
/** * save data * @param string $key * @param int $language_id * @param string $val * @return boolean */ public function save($key, $language_id, $val, $section = "", $import = false, $newKey = "") { $data = array('key' => $newKey == "" ? $key : $newKey, 'language_id' => $language_id, 'value' => $val, 'section' => $section); $selectTranslate = $this->_dbTable->select()->where('`language_id` = ?', $language_id)->where('`key` = ?', $data['key']); if ($section != "" && !$import) { $data['section'] = $section; } if ($section != "" && $import) { $selectTranslate->where('`section` = ?', $section); } $rowTranslate = $selectTranslate->query()->fetchObject(); // ->toArray() if (is_object($rowTranslate)) { $res = $this->_dbTable->update($data, array('id = ?' => $rowTranslate->id)); if (!$import) { $this->cacheCleanTranslation(); } return $res == 1; } else { $res = $this->_dbTable->insert($data); if (!$import) { $this->cacheCleanTranslation(); } return $res > 0; } }
public function aggregate($object) { if (!$object->getEntityPkValue() && $object->getId()) { $object->load($object->getReviewId()); } $ratingModel = Mage::getModel('rating/rating'); $ratingSummaries = $ratingModel->getEntitySummary($object->getEntityPkValue(), false); $nonDelete = array(); foreach ($ratingSummaries as $ratingSummaryObject) { if ($ratingSummaryObject->getCount()) { $ratingSummary = round($ratingSummaryObject->getSum() / $ratingSummaryObject->getCount()); } else { $ratingSummary = $ratingSummaryObject->getSum(); } $reviewsCount = $this->getTotalReviews($object->getEntityPkValue(), true, $ratingSummaryObject->getStoreId()); $select = $this->_read->select(); $select->from($this->_aggregateTable)->where("{$this->_aggregateTable}.entity_pk_value = ?", $object->getEntityPkValue())->where("{$this->_aggregateTable}.entity_type = ?", $object->getEntityId())->where("{$this->_aggregateTable}.store_id = ?", $ratingSummaryObject->getStoreId()); $oldData = $this->_read->fetchRow($select); $data = new Varien_Object(); $data->setReviewsCount($reviewsCount)->setEntityPkValue($object->getEntityPkValue())->setEntityType($object->getEntityId())->setRatingSummary($ratingSummary > 0 ? $ratingSummary : 0)->setStoreId($ratingSummaryObject->getStoreId()); $this->_write->beginTransaction(); try { if ($oldData['primary_id'] > 0) { $condition = $this->_write->quoteInto("{$this->_aggregateTable}.primary_id = ?", $oldData['primary_id']); $this->_write->update($this->_aggregateTable, $data->getData(), $condition); } else { $this->_write->insert($this->_aggregateTable, $data->getData()); } $this->_write->commit(); } catch (Exception $e) { $this->_write->rollBack(); } } }
/** * 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 store() { $fileTable = IcingaConfigFile::$table; $fileKey = IcingaConfigFile::$keyName; $this->db->beginTransaction(); try { $existingQuery = $this->db->select()->from($fileTable, 'checksum')->where('checksum IN (?)', array_map(array($this, 'dbBin'), $this->getFilesChecksums())); $existing = $this->db->fetchCol($existingQuery); foreach ($existing as $key => $val) { if (is_resource($val)) { $existing[$key] = stream_get_contents($val); } } $missing = array_diff($this->getFilesChecksums(), $existing); /** @var IcingaConfigFile $file */ foreach ($this->files as $name => $file) { $checksum = $file->getChecksum(); if (!in_array($checksum, $missing)) { continue; } $this->db->insert($fileTable, array($fileKey => $this->dbBin($checksum), 'content' => $file->getContent())); } $this->db->insert(self::$table, array('duration' => $this->generationTime, 'last_activity_checksum' => $this->dbBin($this->getLastActivityChecksum()), 'checksum' => $this->dbBin($this->getChecksum()))); /** @var IcingaConfigFile $file */ foreach ($this->files as $name => $file) { $this->db->insert('director_generated_config_file', array('config_checksum' => $this->dbBin($this->getChecksum()), 'file_checksum' => $this->dbBin($file->getChecksum()), 'file_path' => $name)); } $this->db->commit(); } catch (Exception $e) { $this->db->rollBack(); throw $e; var_dump($e->getMessage()); } return $this; }
/** * adds a HTML page to lucene index and mysql table for search result sumaries * @param string $html * @param string $url * @param string $language * @return void */ protected function addHtmlToIndex($html, $url, $language, $encoding, $host) { //$this->checkAndPrepareIndex(); try { $content = $this->getPlainTextFromHtml($html); $this->db->insert("plugin_searchphp_contents_temp", array("id" => md5($url), "uri" => $url, "host" => $host, "content" => $content, "html" => $html)); $doc = Zend_Search_Lucene_Document_Html::loadHTML($html, false, "utf-8"); //add h1 to index $headlines = array(); preg_match_all('@(<h1[^>]*?>[ \\t\\n\\r\\f]*(.*?)[ \\t\\n\\r\\f]*' . '</h1>)@si', $html, $headlines); if (is_array($headlines[2])) { $h1 = ""; foreach ($headlines[2] as $headline) { $h1 .= $headline . " "; } //logger::log($h1); //logger::log($encoding); $h1 = strip_tags($h1); $field = Zend_Search_Lucene_Field::Text('h1', $h1, $encoding); $field->boost = 10; $doc->addField($field); } $doc->addField(Zend_Search_Lucene_Field::Keyword('charset', $encoding)); $doc->addField(Zend_Search_Lucene_Field::Keyword('lang', $language)); $doc->addField(Zend_Search_Lucene_Field::Keyword('url', $url)); $serialized = serialize($doc); $this->db->insert("plugin_searchphp_indexer_todo", array("content" => $serialized)); //$this->index->addDocument($doc); } catch (Exception $e) { logger::log($e->getMessage(), Zend_Log::ERR); } }
/** * Process everything after authentication. * * @param \Zend_Auth_Result $result */ protected function afterAuthorization(\Zend_Auth_Result $result, $lastAuthorizer = null) { try { $select = $this->db->select(); $select->from('gems__user_login_attempts', array('gula_failed_logins', 'gula_last_failed', 'gula_block_until', new \Zend_Db_Expr('UNIX_TIMESTAMP() - UNIX_TIMESTAMP(gula_last_failed) AS since_last')))->where('gula_login = ?', $this->getLoginName())->where('gula_id_organization = ?', $this->getCurrentOrganizationId())->limit(1); $values = $this->db->fetchRow($select); // The first login attempt if (!$values) { $values['gula_login'] = $this->getLoginName(); $values['gula_id_organization'] = $this->getCurrentOrganizationId(); $values['gula_failed_logins'] = 0; $values['gula_last_failed'] = null; $values['gula_block_until'] = null; $values['since_last'] = $this->failureIgnoreTime + 1; } if ($result->isValid()) { // Reset login failures $values['gula_failed_logins'] = 0; $values['gula_last_failed'] = null; $values['gula_block_until'] = null; } else { // Reset the counters when the last login was longer ago than the delay factor if ($values['since_last'] > $this->failureIgnoreTime) { $values['gula_failed_logins'] = 1; } elseif ($lastAuthorizer === 'pwd') { // Only increment failed login when password failed $values['gula_failed_logins'] += 1; } // If block is already set if ($values['gula_block_until']) { // Do not change it anymore unset($values['gula_block_until']); } else { // Only set the block when needed if ($this->failureBlockCount <= $values['gula_failed_logins']) { $values['gula_block_until'] = new \Zend_Db_Expr('DATE_ADD(CURRENT_TIMESTAMP, INTERVAL ' . $this->failureIgnoreTime . ' SECOND)'); } } // Always record the last fail $values['gula_last_failed'] = new \MUtil_Db_Expr_CurrentTimestamp(); $values['gula_failed_logins'] = max(1, $values['gula_failed_logins']); // Response gets slowly slower $sleepTime = min($values['gula_failed_logins'] - 1, 10) * 2; sleep($sleepTime); // \MUtil_Echo::track($sleepTime, $values, $result->getMessages()); } // Value not saveable unset($values['since_last']); if (isset($values['gula_login'])) { $this->db->insert('gems__user_login_attempts', $values); } else { $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 yet run // \MUtil_Echo::r($e); } }
/** * @param string|int $nodeId * @param array $data * @return false|string * @SuppressWarnings(PHPMD.ExitExpression) */ public function appendChild($nodeId, $data) { $info = $this->getNodeInfo($nodeId); if (!$info) { return false; } $data[$this->_left] = $info[$this->_right]; $data[$this->_right] = $info[$this->_right] + 1; $data[$this->_level] = $info[$this->_level] + 1; $data[$this->_pid] = $nodeId; // creating a place for the record being inserted if ($nodeId) { $this->_db->beginTransaction(); try { $sql = 'UPDATE ' . $this->_table . ' SET' . ' `' . $this->_left . '` = IF( `' . $this->_left . '` > :left,' . ' `' . $this->_left . '`+2, `' . $this->_left . '`),' . ' `' . $this->_right . '` = IF( `' . $this->_right . '`>= :right,' . ' `' . $this->_right . '`+2, `' . $this->_right . '`)' . ' WHERE `' . $this->_right . '` >= :right'; $this->_db->query($sql, ['left' => $info[$this->_left], 'right' => $info[$this->_right]]); $this->_db->insert($this->_table, $data); $this->_db->commit(); } catch (\PDOException $p) { $this->_db->rollBack(); echo $p->getMessage(); exit; } catch (\Exception $e) { $this->_db->rollBack(); echo $e->getMessage(); echo $sql; exit; } // TODO: change to ZEND LIBRARY $res = $this->_db->fetchOne('select last_insert_id()'); return $res; } return false; }
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; }
/** * Inserts a new row. * * @param array $data Column-value pairs. * @return mixed The primary key of the row inserted. */ public function insert(array $data) { /** * Zend_Db_Table assumes that if you have a compound primary key * and one of the columns in the key uses a sequence, * it's the _first_ column in the compound key. */ $primary = (array) $this->_primary; $pkIdentity = $primary[(int) $this->_identity]; /** * If this table uses a database sequence object and the data does not * specify a value, then get the next ID from the sequence and add it * to the row. We assume that only the first column in a compound * primary key takes a value from a sequence. */ if (is_string($this->_sequence) && !isset($data[$pkIdentity])) { $data[$pkIdentity] = $this->_db->nextSequenceId($this->_sequence); } /** * If the primary key can be generated automatically, and no value was * specified in the user-supplied data, then omit it from the tuple. */ if (array_key_exists($pkIdentity, $data) && $data[$pkIdentity] === null) { unset($data[$pkIdentity]); } /** * INSERT the new row. */ $tableSpec = ($this->_schema ? $this->_schema . '.' : '') . $this->_name; $this->_db->insert($tableSpec, $data); /** * Fetch the most recent ID generated by an auto-increment * or IDENTITY column, unless the user has specified a value, * overriding the auto-increment mechanism. */ if ($this->_sequence === true && !isset($data[$pkIdentity])) { $data[$pkIdentity] = $this->_db->lastInsertId(); } /** * Return the primary key value if the PK is a single column, * else return an associative array of the PK column/value pairs. */ $pkData = array_intersect_key($data, array_flip($primary)); if (count($primary) == 1) { return current($pkData); } else { return $pkData; } /** * The last case: the user did not specify a value for the primary * key, nor is this table class declared to use an auto-increment key. * Since the insert did not fail, we can assume this is one of the edge * cases, which may include: * - the table has no primary key defined; * - the database table uses a trigger to set a primary key value; * - the RDBMS permits primary keys to be NULL or have a value set * to the column's DEFAULT */ return null; }
public function save(Mage_Admin_Model_Permissions_Roles $role) { if ($role->getPid() > 0) { $row = $this->load($role->getPid()); } else { $row = array('tree_level' => 0); } if ($role->getId()) { $this->_write->update($this->_roleTable, array('parent_id' => $role->getPid(), 'tree_level' => $row['tree_level'] + 1, 'role_name' => $role->getName()), "role_id = {$role->getId()}"); } else { $this->_write->insert($this->_roleTable, array('parent_id' => $role->getPid(), 'tree_level' => $row['tree_level'] + 1, 'role_name' => $role->getName(), 'role_type' => $role->getRoleType())); $role->setId($this->_write->lastInsertId()); } $this->_updateRoleUsersAcl($role); return $role->getId(); }
/** * 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); } } }
/** * Inserts a new row. * * @param array $data Column-value pairs. * @return mixed The primary key of the row inserted. */ public function insert(array $data) { /** * Zend_Db_Table assumes that if you have a compound primary key * and one of the columns in the key uses a sequence, * it's the _first_ column in the compound key. */ $primary = (array) $this->_primary; $pkIdentity = $primary[(int) $this->_identity]; /** * If this table uses a database sequence object and the data does not * specify a value, then get the next ID from the sequence and add it * to the row. We assume that only the first column in a compound * primary key takes a value from a sequence. */ if (is_string($this->_sequence) && !isset($data[$pkIdentity])) { $data[$pkIdentity] = $this->_db->nextSequenceId($this->_sequence); } /** * If the primary key can be generated automatically, and no value was * specified in the user-supplied data, then omit it from the tuple. */ if (array_key_exists($pkIdentity, $data) && $data[$pkIdentity] === null) { unset($data[$pkIdentity]); } /** * Run pre-INSERT logic */ if ($this->notify('preInsert', $this, $data) === false) { return null; } /** * INSERT the new row. */ $tableSpec = ($this->_schema ? $this->_schema . '.' : '') . $this->_name; $this->_db->insert($tableSpec, $data); /** * Fetch the most recent ID generated by an auto-increment * or IDENTITY column, unless the user has specified a value, * overriding the auto-increment mechanism. */ if ($this->_sequence === true && !isset($data[$pkIdentity])) { $data[$pkIdentity] = $this->_db->lastInsertId(); } /** * Run post-INSERT logic */ $this->notify('postInsert', $this, $data); /** * Return the primary key value if the PK is a single column, * else return an associative array of the PK column/value pairs. */ $pkData = array_intersect_key($data, array_flip($primary)); if (count($primary) == 1) { reset($pkData); return current($pkData); } return $pkData; }
/** * Test the Adapter's insert() method. * This requires providing an associative array of column=>value pairs. * * @todo: test that require delimited identifiers. */ public function testInsert() { $table = $this->getIdentifier(self::TABLE_NAME); $row = array('title' => 'News Item 3', 'subtitle' => 'Sub title 3', 'body' => 'This is body 1', 'date_created' => '2006-05-03 13:13:13'); $rows_affected = $this->_db->insert($table, $row); $last_insert_id = $this->_db->lastInsertId(); $this->assertEquals(3, (string) $last_insert_id, 'Expected new id to be 3'); }
/** * Inserts a new row. * * @param array $data Column-value pairs. * @param string $where An SQL WHERE clause. * @return integer The last insert ID. */ public function insert(array $data) { $this->_db->insert($this->_name, $data); // @todo handle tables that have no auto-generated key. // @todo handle tables that use a named sequence instead // of an implict auto-generated key. return $this->_db->lastInsertId(); }
/** * Callback function on create new row. */ protected function _insert(Days_Db_Row $row) { $data = $row->toArray(); $this->_db->insert($this->_name, $data); $id = $this->_db->lastInsertId(); $row->id = $id; return $id; }
/** * Seta/Atualiza um valor do registro * * @param string $key chave do valor * @param mixed $value novo valor */ public function __set($key, $value) { if (isset($this->{$key})) { $this->db->update("registry", array("value" => $value), "context='{$this->getContext()}' AND `key`='{$key}'"); } else { $this->db->insert("registry", array("context" => $this->getContext(), "key" => $key, "value" => $value)); } $this->update(); }
/** * Inserts a new row. * * @param array $data Column-value pairs. * @return mixed The primary key of the row inserted. */ public function insert(array $data) { /** * Zend_Db_Table assumes that if you have a compound primary key * and one of the columns in the key uses a sequence, * it's the _first_ column in the compound key. */ $primary = (array) $this->_primary; $pkIdentity = $primary[(int) $this->_identity]; /** * If this table uses a database sequence object and the data does not * specify a value, then get the next ID from the sequence and add it * to the row. We assume that only the first column in a compound * primary key takes a value from a sequence. */ if (is_string($this->_sequence) && !isset($data[$pkIdentity])) { $data[$pkIdentity] = $this->_db->nextSequenceId($this->_sequence); } /** * INSERT the new row. */ $this->_db->insert($this->_name, $data); if (isset($data[$pkIdentity])) { /** * Return the primary key value or array of values(s) if the * primary key is compound. This handles the case of natural keys * and sequence-driven keys. This also covers the case of * auto-increment keys when the user specifies a value, thus * overriding the auto-increment logic. */ $pkData = array_intersect_key($data, array_flip($primary)); if (count($primary) == 1) { return current($pkData); } else { return $pkData; } } if ($this->_sequence === true) { /** * Return the most recent ID generated by an auto-increment * or IDENTITY column. */ return $this->_db->lastInsertId(); } /** * The last case: the user did not specify a value for the primary * key, nor is this table class declared to use an auto-increment key. * Since the insert did not fail, we can assume this is one of the edge * cases, which may include: * - the table has no primary key defined; * - the database table uses a trigger to set a primary key value; * - the RDBMS permits primary keys to be NULL or have a value set * to the column's DEFAULT */ return null; }
/** * @param $oo_id * @param bool $createMissingChildrenRows * @throws \Zend_Db_Adapter_Exception */ public function doUpdate($oo_id, $createMissingChildrenRows = false) { if (empty($this->fields) && empty($this->relations) && !$createMissingChildrenRows) { return; } $this->idTree = []; $fields = implode("`,`", $this->fields); if (!empty($fields)) { $fields = ", `" . $fields . "`"; } $result = $this->db->fetchRow("SELECT " . $this->idField . " AS id" . $fields . " FROM " . $this->storetable . " WHERE " . $this->idField . " = ?", $oo_id); $o = new \stdClass(); $o->id = $result['id']; $o->values = $result; $o->childs = $this->buildTree($result['id'], $fields); if (!empty($this->fields)) { foreach ($this->fields as $fieldname) { foreach ($o->childs as $c) { $this->getIdsToUpdateForValuefields($c, $fieldname); } $this->updateQueryTable($oo_id, $this->fieldIds[$fieldname], $fieldname); } } if (!empty($this->relations)) { foreach ($this->relations as $fieldname => $fields) { foreach ($o->childs as $c) { $this->getIdsToUpdateForRelationfields($c, $fieldname); } if (is_array($fields)) { foreach ($fields as $f) { $this->updateQueryTable($oo_id, $this->fieldIds[$fieldname], $f); } } else { $this->updateQueryTable($oo_id, $this->fieldIds[$fieldname], $fieldname); } } } // check for missing entries which can occur in object bricks and localized fields // this happens especially in the following case: // parent object has no brick, add child to parent, add brick to parent & click save // without this code there will not be an entry in the query table for the child object if ($createMissingChildrenRows) { $idsToUpdate = $this->extractObjectIdsFromTreeChildren($o->childs); if (!empty($idsToUpdate)) { $idsInTable = $this->db->fetchCol("SELECT " . $this->idField . " FROM " . $this->querytable . " WHERE " . $this->idField . " IN (" . implode(",", $idsToUpdate) . ")"); $diff = array_diff($idsToUpdate, $idsInTable); // create entries for children that don't have an entry yet $originalEntry = $this->db->fetchRow("SELECT * FROM " . $this->querytable . " WHERE " . $this->idField . " = ?", $oo_id); foreach ($diff as $id) { $originalEntry[$this->idField] = $id; $this->db->insert($this->querytable, $originalEntry); } } } }
/** * Update session * * @param string $sessId * @param string $sessData * @return boolean */ public function write($sessId, $sessData) { $data = array('session_id' => $this->_prepareValueForSave($sessId), 'session_expires' => time() + $this->getLifeTime(), 'session_data' => $this->_prepareValueForSave($sessData)); $exists = $this->_write->fetchOne("SELECT session_id FROM `" . $this->_sessionTable . "` WHERE session_id = '" . $sessId . "'"); if ($exists) { $this->_write->update($this->_sessionTable, $data, 'session_id'); } else { $this->_write->insert($this->_sessionTable, $data); } return true; }
public function updateOneshot($minutes = 60, $interval = 300) { $last_update = $this->_read->fetchOne("SELECT UNIX_TIMESTAMP(MAX(add_date)) FROM {$this->_summaryTable} WHERE type_id IS NULL"); $next_update = $last_update + $interval; if (time() >= $next_update) { $stats = $this->_read->fetchAssoc("SELECT\n u.visit_time,\n v.visitor_id,\n c.customer_id,\n ROUND( (UNIX_TIMESTAMP(u.visit_time) - UNIX_TIMESTAMP(" . now() . " - INTERVAL {$minutes} MINUTE )) / {$interval} ) as _diff,\n COUNT(DISTINCT(v.visitor_id)) as visitor_count,\n COUNT(DISTINCT(c.customer_id)) as customer_count\n FROM\n {$this->_urlTable} u\n LEFT JOIN {$this->_visitorTable} v ON(v.visitor_id = u.visitor_id)\n LEFT JOIN {$this->_customerTable} c on(c.visitor_id = v.visitor_id)\n WHERE\n UNIX_TIMESTAMP(u.visit_time) > {$next_update}\n group by _diff"); foreach ($stats as $stat) { $data = array('type_id' => new Zend_Db_Expr('NULL'), 'visitor_count' => $stat['visitor_count'], 'customer_count' => $stat['customer_count'], 'add_date' => $stat['visit_time']); $this->_write->insert($this->_summaryTable, $data); } } }