/** * Process the data and return the answers that should be changed. * * Storing the changed values is handled by the calling function. * * @param \Gems_Tracker_Token $token Gems token object * @return array Containing the changed values */ public function processTokenData(\Gems_Tracker_Token $token) { if (!$token->getReceptionCode()->isSuccess()) { return; } $answers = $token->getRawAnswers(); if (isset($answers['informedconsent'])) { $consent = $this->util->getConsent($answers['informedconsent']); if ($consent->exists) { // Is existing consent description as answer $consentCode = $consent->getDescription(); } else { if ($answers['informedconsent']) { // Uses start of consent description as answer (LS has only 5 chars for an answer option) $consentCode = $this->db->fetchOne("SELECT gco_description FROM gems__consents WHERE gco_description LIKE ? ORDER BY gco_order", $answers['informedconsent'] . '%'); } else { $consentCode = false; } if (!$consentCode) { if ($answers['informedconsent']) { // Code not found, use first positive consent $consentCode = $this->db->fetchOne("SELECT gco_description FROM gems__consents WHERE gco_code != ? ORDER BY gco_order", $this->util->getConsentRejected()); } else { // Code not found, use first negative consent $consentCode = $this->db->fetchOne("SELECT gco_description FROM gems__consents WHERE gco_code = ? ORDER BY gco_order", $this->util->getConsentRejected()); } } } $respondent = $token->getRespondent(); $values = array('gr2o_patient_nr' => $respondent->getPatientNumber(), 'gr2o_id_organization' => $respondent->getOrganizationId(), 'gr2o_consent' => $consentCode); $respondent->getRespondentModel()->save($values); } return false; }
/** * 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, $organizationData = null) { $batch = $this->getBatch(); $import = $batch->getVariable('import'); if (isset($organizationData['gor_id_organization']) && $organizationData['gor_id_organization']) { $oldId = $organizationData['gor_id_organization']; } else { $oldId = false; $batch->addToCounter('import_errors'); $batch->addMessage(sprintf($this->_('No gor_id_organization not specified for organization at line %d.'), $lineNr)); } if (isset($organizationData['gor_name']) && $organizationData['gor_name']) { if ($oldId) { $orgId = $this->db->fetchOne("SELECT gor_id_organization FROM gems__organizations WHERE gor_name = ?", $organizationData['gor_name']); if ($orgId) { $import['organizationIds'][$oldId] = $orgId; $import['formDefaults']['gtr_organizations'][] = $orgId; } else { $import['organizationIds'][$oldId] = false; } } } else { $orgId = false; $batch->addToCounter('import_errors'); $batch->addMessage(sprintf($this->_('No gor_name not specified for organization at line %d.'), $lineNr)); } }
/** * 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 * * @param array $row Row to save */ public function execute($row = null) { if ($row) { if (!isset($row['grs_id_user']) && isset($row['grs_ssn']) && $this->targetModel instanceof \Gems_Model_RespondentModel && $this->targetModel->hashSsn !== \Gems_Model_RespondentModel::SSN_HIDE) { if (\Gems_Model_RespondentModel::SSN_HASH === $this->targetModel->hashSsn) { $search = $this->targetModel->saveSSN($row['grs_ssn']); } else { $search = $row['grs_ssn']; } $sql = 'SELECT grs_id_user FROM gems__respondents WHERE grs_ssn = ?'; $id = $this->db->fetchOne($sql, $search); // Check for change in patient ID if ($id) { if (isset($row['gr2o_id_organization']) && $this->targetModel instanceof \MUtil_Model_DatabaseModelAbstract) { $sql = 'SELECT gr2o_patient_nr FROM gems__respondent2org WHERE gr2o_id_user = ? AND gr2o_id_organization = ?'; $patientId = $this->db->fetchOne($sql, array($id, $row['gr2o_id_organization'])); if ($patientId) { // Change the patient number $copyId = $this->targetModel->getKeyCopyName('gr2o_patient_nr'); $row[$copyId] = $patientId; } } $row['grs_id_user'] = $id; $row['gr2o_id_user'] = $id; } } parent::execute($row); } }
public function getCurrentSchemaVersion() { if (empty($this->_module)) { throw new FFR_Exception('Module was empty. A module must be set.'); } $cache = Zend_Controller_Action_HelperBroker::getStaticHelper('Cache')->getManager()->getCache('database'); if (!($version = $cache->load($this->_module . 'Version'))) { // Ensure we have valid connection to the database if (!$this->_db->isConnected()) { $this->_db->getServerVersion(); } $sql = 'SELECT schema_version FROM ' . $this->_schemaVersionTable . ' WHERE schema_module = "' . $this->_module . '"'; $version = null; try { $version = $this->_db->fetchOne($sql); } catch (Zend_Db_Exception $e) { // exception means that the schema version table doesn't exist, so create it $createSql = "CREATE TABLE {$this->_schemaVersionTable} (\n schema_id INT NOT NULL AUTO_INCREMENT,\n schema_version INT NOT NULL,\n schema_module VARCHAR(50),\n PRIMARY KEY (schema_id)\n )"; $this->_db->query($createSql); } // There isn't a version record so lets make one if ($version === null || $version === false) { $insertSql = "INSERT {$this->_schemaVersionTable} SET schema_version = 0," . ' schema_module = "' . $this->_module . '"'; $this->_db->query($insertSql); $version = $this->_db->fetchOne($sql); } $cache->save($version, $this->_module . 'Version', array('schemaVersion')); } return $version; }
/** * Fetches a single order by its unique Id. * * @param int $id * @return Order */ public function getById($id) { try { $result = $this->_database->fetchOne( 'SELECT o.*,c.* FROM order o INNER JOIN customer c ON o.customer_id = c.id WHERE o.id = ?', array($id)); if ($result == null) throw new \Exception("Could not find order with id " . $id); $customer = new Customer(); $customer->setName($result['name']); $customer->setAddress1($result['address_1']); $customer->setAddress2($result['address_2']); $customer->setCity($result['city']); $customer->setState($result['state']); $customer->setPostalCode($result['postal_code']); $customer->setCellphone($result['cell_phone']); $customer->setEmail($result['email']); $customer->setCallbackUrl($result['callback_url']); $order = new Order(); $order->setId($id); $order->setCustomer($customer); return $order; } catch (\Exception $e) { throw $e; } }
public function configure(XenForo_ControllerAdmin_Abstract $controller, array &$config) { if ($config) { $errors = $this->validateConfiguration($config, $validatedDirectories); if ($errors) { return $controller->responseError($errors); } else { if (!isset($config['attachmentPaths'])) { $attachPaths = $this->_sourceDb->fetchOne(' SELECT value FROM ' . $this->_prefix . 'settings WHERE variable = \'attachmentUploadDir\' '); $path = @unserialize($attachPaths); if (!$path) { if ($attachPaths) { $path = array($attachPaths); } else { $path = array(''); } } $viewParams = array('attachPaths' => $path ? $path : array(), 'config' => $config); return $controller->responseView('XenForo_ViewAdmin_Import_SMF_Config_Attachments', 'import_smf_config_attachments', $viewParams); } } if ($validatedDirectories) { return true; } } else { $viewParams = array(); } return $controller->responseView('XenForo_ViewAdmin_Import_SMF_Config', 'import_smf_config', $viewParams); }
/** * Get the total paid amount by this customer. * Replaces: calc_customer_paid() * Enter description here ... */ public function getPaidAmount() { $tbl_prefix = SimpleInvoices_Db_Table_Abstract::getTablePrefix(); $select = new Zend_Db_Select($this->_db); $select->from($tbl_prefix . "payment", array('amount' => new Zend_Db_Expr("COALESCE(SUM(" . $tbl_prefix . "payment.ac_amount), 0)"))); $select->joinInner($tbl_prefix . "invoices", $tbl_prefix . "payment.ac_inv_id=" . $tbl_prefix . "invoices.id", NULL); $select->where($tbl_prefix . "invoices.customer_id=?", $this->_id); return $this->_db->fetchOne($select); }
/** * 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 $oo_id * @param $ids * @param $fieldname * @throws \Zend_Db_Adapter_Exception */ protected function updateQueryTable($oo_id, $ids, $fieldname) { if (!empty($ids)) { $value = $this->db->fetchOne("SELECT `{$fieldname}` FROM " . $this->querytable . " WHERE " . $this->idField . " = ?", $oo_id); $this->db->update($this->querytable, [$fieldname => $value], $this->idField . " IN (" . implode(",", $ids) . ")"); } }
/** * Возвращает массив опций для построения постраничной навигации * Необходимо дергать сразу после выполнения SQL-запроса с SQL_CAL_FOUND_ROWS * * @param array $options - Массив опций * * @return object */ function getPaginator($options = array()) { $Paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($this->_db->fetchOne('SELECT FOUND_ROWS()'))); $Paginator->setItemCountPerPage(isset($options['perpage']) ? $options['perpage'] : $this->getPerPage()); if (isset($options['widgetid'])) { $Paginator->setCurrentPageNumber($this->getCurrentPage($options['widgetid'])); } else { $Paginator->setCurrentPageNumber($this->getCurrentPage()); } $out = $Paginator->getPages(); $pageidentity = $this->getPageIdentity(); // Кроме стандартных параметров Zend_Paginator::getPages() возвращаем доп. параметры // Полный путь без GET-запроса $UrlInfo = parse_url($this->_request->getRequestUri()); $out->ClearUrl = $UrlInfo['path']; // Обрабатываем GET-запрос $query = $this->_request->getQuery(); if (isset($query[$pageidentity])) { unset($query[$pageidentity]); } if (isset($query['widget'])) { unset($query['widget']); } // Строим строку выражения if (!empty($query)) { $out->Query = http_build_query($query); } // Фактически, ссылку на первую страницу (без page и widget) $out->FullUrl = isset($out->Query) ? $out->ClearUrl . '?' . $out->Query : $out->ClearUrl; // Добавляем к выражению Id виджета $widget = isset($options['widgetid']) ? 'widget=' . (int) $options['widgetid'] . '&' : ''; // Полную ссылку к которой в конце надо только добавить номер страницы $out->PageUrl = isset($out->Query) ? $out->FullUrl . '&' . $widget . $pageidentity . '=' : $out->FullUrl . '?' . $widget . $pageidentity . '='; return $out; }
/** * Test the Adapter's fetchOne() method. */ public function testAdapterFetchOne() { $table = $this->getIdentifier(self::TABLE_NAME); $title = 'News Item 1'; $result = $this->_db->fetchOne('SELECT title FROM ' . $this->_db->quoteIdentifier($table) . ' WHERE date_created > ? ORDER BY id', array('2006-01-01')); $this->assertEquals($title, $result); }
/** * Execute a single mail job */ public function executeAction() { $jobId = $this->getParam(\MUtil_Model::REQUEST_ID); $batch = $this->loader->getTaskRunnerBatch('commjob-execute-' . $jobId); $batch->minimalStepDurationMs = 3000; // 3 seconds max before sending feedback if (!$batch->isLoaded() && !is_null($jobId)) { // Check for unprocessed tokens $tracker = $this->loader->getTracker(); $tracker->processCompletedTokens(null, $this->currentUser->getUserId()); // We could skip this, but a check before starting the batch is better $sql = $this->db->select()->from('gems__comm_jobs', array('gcj_id_job'))->where('gcj_active = 1')->where('gcj_id_job = ?', $jobId); $job = $this->db->fetchOne($sql); if (!empty($job)) { $batch->addTask('Mail\\ExecuteMailJobTask', $job); } } if ($batch->isFinished()) { // Add the messages to the view and forward $messages = $batch->getMessages(true); foreach ($messages as $message) { $this->addMessage($message); } $this->_reroute(array('action' => 'show')); } $this->_helper->BatchRunner($batch, $this->_('Execute single mail job'), $this->accesslog); }
/** * * @param array $inserts */ protected function _insertFields(array $inserts) { foreach ($inserts as $insert) { if (isset($insert['table_name'], $insert['data_writer'])) { $dw = XenForo_DataWriter::create($insert['data_writer']); if (isset($insert['primary_fields'])) { $sql = "SELECT count(*) FROM `" . $insert['table_name'] . "` "; $whereClauses = array(); foreach ($insert['primary_fields'] as $fieldName => $fieldValue) { $whereClauses[] = "`" . $fieldName . "` = '" . $fieldValue . "'"; } if (!empty($whereClauses)) { $sql .= "WHERE " . implode(" AND ", $whereClauses) . " "; } if ($this->_db->fetchOne($sql)) { $dw->setExistingData($insert['primary_fields']); } } $dw->bulkSet($insert['primary_fields']); if (isset($insert['fields'])) { $dw->bulkSet($insert['fields']); } $dw->save(); } } }
public function getCount($condition, $orderBy = null, $limit = null, $offset = null) { if ($condition) { $condition = "WHERE " . $condition; } if ($orderBy) { $orderBy = " ORDER BY " . $orderBy; } if ($limit) { if ($offset) { $limit = "LIMIT " . $offset . ", " . $limit; } else { $limit = "LIMIT " . $limit; } } if ($this->model->getVariantMode() == OnlineShop_Framework_IProductList::VARIANT_MODE_INCLUDE_PARENT_OBJECT) { $query = "SELECT count(DISTINCT o_virtualProductId) FROM " . $this->model->getCurrentTenantConfig()->getTablename() . " a " . $this->model->getCurrentTenantConfig()->getJoins() . $condition . $orderBy . " " . $limit; } else { $query = "SELECT count(*) FROM " . $this->model->getCurrentTenantConfig()->getTablename() . " a " . $this->model->getCurrentTenantConfig()->getJoins() . $condition . $orderBy . " " . $limit; } OnlineShop_Plugin::getSQLLogger()->log("Query: " . $query, Zend_Log::INFO); $result = $this->db->fetchOne($query); OnlineShop_Plugin::getSQLLogger()->log("Query done.", Zend_Log::INFO); return $result; }
/** * Move tree node * * @todo Use adapter for generate conditions * @param Varien_Data_Tree_Node $node * @param Varien_Data_Tree_Node $newParent * @param Varien_Data_Tree_Node $prevNode */ public function move($node, $newParent, $prevNode = null) { $position = 1; $oldPath = $node->getData($this->_pathField); $newPath = $newParent->getData($this->_pathField); $newPath = $newPath . '/' . $node->getId(); $oldPathLength = strlen($oldPath); $newLevel = $newParent->getLevel() + 1; $levelDisposition = $newLevel - $node->getLevel(); $data = array($this->_levelField => new Zend_Db_Expr("{$this->_levelField} + '{$levelDisposition}'"), $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(); $reorderData = array($this->_orderField => new Zend_Db_Expr("{$this->_orderField} + 1")); try { if ($prevNode && $prevNode->getId()) { $reorderCondition = "{$this->_orderField} > {$prevNode->getData($this->_orderField)}"; $position = $prevNode->getData($this->_orderField) + 1; } else { $reorderCondition = $this->_conn->quoteInto("{$this->_pathField} REGEXP ?", "^{$newParent->getData($this->_pathField)}/[0-9]+\$"); $select = $this->_conn->select()->from($this->_table, new Zend_Db_Expr("MIN({$this->_orderField})"))->where($reorderCondition); $position = (int) $this->_conn->fetchOne($select); } $this->_conn->update($this->_table, $reorderData, $reorderCondition); $this->_conn->update($this->_table, $data, $condition); $this->_conn->update($this->_table, array($this->_orderField => $position, $this->_levelField => $newLevel), $this->_conn->quoteInto("{$this->_idField} = ?", $node->getId())); $this->_conn->commit(); } catch (Exception $e) { $this->_conn->rollBack(); throw new Exception("Can't move tree node due to error: " . $e->getMessage()); } }
/** * Creates a model for getModel(). Called only for each new $action. * * The parameters allow you to easily adapt the model to the current action. The $detailed * parameter was added, because the most common use of action is a split between detailed * and summarized actions. * * @param boolean $detailed True when the current action is not in $summarizedActions. * @param string $action The current action. * @return \MUtil_Model_ModelAbstract */ protected function createModel($detailed, $action) { // Load organizationId and respondentId $this->loadParams(); $model = $this->loader->getModels()->createAppointmentModel(); if ($detailed) { if ('edit' === $action || 'create' === $action) { $model->applyEditSettings($this->organizationId); if ($action == 'create') { // Set default date to tomoorow. $now = new \MUtil_Date(); $now->addDay(1); $loid = $this->db->fetchOne("SELECT gap_id_location\n FROM gems__appointments\n WHERE gap_id_user = ? AND gap_id_organization = ?\n ORDER BY gap_admission_time DESC", array($this->respondentId, $this->organizationId)); if ($loid !== false) { $model->set('gap_id_location', 'default', $loid); } $model->set('gap_id_user', 'default', $this->respondentId); $model->set('gap_manual_edit', 'default', 1); $model->set('gap_admission_time', 'default', $now); } else { // When there is something saved, then set manual edit to 1 $model->setSaveOnChange('gap_manual_edit'); $model->setOnSave('gap_manual_edit', 1); } } else { $model->applyDetailSettings(); } } else { $model->applyBrowseSettings(); $model->addFilter(array('gap_id_user' => $this->respondentId, 'gap_id_organization' => $this->organizationId)); } return $model; }
/** * @param string|int $eId * @param string|int $pId * @param string|int $aId * @return void * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.UnusedLocalVariable) * @SuppressWarnings(PHPMD.ExitExpression) */ public function moveNodes($eId, $pId, $aId = 0) { $eInfo = $this->getNodeInfo($eId); if ($pId != 0) { $pInfo = $this->getNodeInfo($pId); } if ($aId != 0) { $aInfo = $this->getNodeInfo($aId); } $level = $eInfo[$this->_level]; $leftKey = $eInfo[$this->_left]; $rightKey = $eInfo[$this->_right]; if ($pId == 0) { $levelUp = 0; } else { $levelUp = $pInfo[$this->_level]; } $rightKeyNear = 0; $leftKeyNear = 0; if ($pId == 0) { //move to root $rightKeyNear = $this->_db->fetchOne('SELECT MAX(' . $this->_right . ') FROM ' . $this->_table); } elseif ($aId != 0 && $pId == $eInfo[$this->_pid]) { // if we have after ID $rightKeyNear = $aInfo[$this->_right]; $leftKeyNear = $aInfo[$this->_left]; } elseif ($aId == 0 && $pId == $eInfo[$this->_pid]) { // if we do not have after ID $rightKeyNear = $pInfo[$this->_left]; } elseif ($pId != $eInfo[$this->_pid]) { $rightKeyNear = $pInfo[$this->_right] - 1; } $skewLevel = $pInfo[$this->_level] - $eInfo[$this->_level] + 1; $skewTree = $eInfo[$this->_right] - $eInfo[$this->_left] + 1; echo "alert('" . $rightKeyNear . "');"; if ($rightKeyNear > $rightKey) { // up echo "alert('move up');"; $skewEdit = $rightKeyNear - $leftKey + 1; $sql = 'UPDATE ' . $this->_table . ' SET ' . $this->_right . ' = IF(' . $this->_left . ' >= ' . $eInfo[$this->_left] . ', ' . $this->_right . ' + ' . $skewEdit . ', IF(' . $this->_right . ' < ' . $eInfo[$this->_left] . ', ' . $this->_right . ' + ' . $skewTree . ', ' . $this->_right . ')), ' . $this->_level . ' = IF(' . $this->_left . ' >= ' . $eInfo[$this->_left] . ', ' . $this->_level . ' + ' . $skewLevel . ', ' . $this->_level . '), ' . $this->_left . ' = IF(' . $this->_left . ' >= ' . $eInfo[$this->_left] . ', ' . $this->_left . ' + ' . $skewEdit . ', IF(' . $this->_left . ' > ' . $rightKeyNear . ', ' . $this->_left . ' + ' . $skewTree . ', ' . $this->_left . '))' . ' WHERE ' . $this->_right . ' > ' . $rightKeyNear . ' AND ' . $this->_left . ' < ' . $eInfo[$this->_right]; } elseif ($rightKeyNear < $rightKey) { // down echo "alert('move down');"; $skewEdit = $rightKeyNear - $leftKey + 1 - $skewTree; $sql = 'UPDATE ' . $this->_table . ' SET ' . $this->_left . ' = IF(' . $this->_right . ' <= ' . $rightKey . ', ' . $this->_left . ' + ' . $skewEdit . ', IF(' . $this->_left . ' > ' . $rightKey . ', ' . $this->_left . ' - ' . $skewTree . ', ' . $this->_left . ')), ' . $this->_level . ' = IF(' . $this->_right . ' <= ' . $rightKey . ', ' . $this->_level . ' + ' . $skewLevel . ', ' . $this->_level . '), ' . $this->_right . ' = IF(' . $this->_right . ' <= ' . $rightKey . ', ' . $this->_right . ' + ' . $skewEdit . ', IF(' . $this->_right . ' <= ' . $rightKeyNear . ', ' . $this->_right . ' - ' . $skewTree . ', ' . $this->_right . '))' . ' WHERE ' . $this->_right . ' > ' . $leftKey . ' AND ' . $this->_left . ' <= ' . $rightKeyNear; } $this->_db->beginTransaction(); try { $this->_db->query($sql); $this->_db->commit(); } catch (\Exception $e) { $this->_db->rollBack(); echo $e->getMessage(); echo "<br>\r\n"; echo $sql; echo "<br>\r\n"; exit; } echo "alert('node added')"; }
/** * 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; }
protected function _bootstrap(array $config) { if ($this->_sourceDb) { // already run return; } @set_time_limit(0); $this->_config = $config; $this->_sourceDb = Zend_Db::factory('mysqli', array('host' => $config['db']['host'], 'port' => $config['db']['port'], 'username' => $config['db']['username'], 'password' => $config['db']['password'], 'dbname' => $config['db']['dbname'], 'charset' => 'utf8')); $this->_prefix = preg_replace('/[^a-z0-9_]/i', '', $config['db']['prefix']); $this->_defaultLang = $this->_sourceDb->fetchOne("\n\t\t\tSELECT config_value\n\t\t\tFROM " . $this->_prefix . "config\n\t\t\tWHERE config_name = 'default_lang'\n\t\t"); $this->_defaultLangId = $this->_sourceDb->fetchOne(' SELECT lang_id FROM ' . $this->_prefix . 'lang WHERE lang_iso = ' . $this->_sourceDb->quote($this->_defaultLang)); }
/** * Set the footer of the browse table. * * Overrule this function to set the header differently, without * having to recode the core table building code. * * @param \MUtil_Model_Bridge_VerticalTableBridge $bridge * @param \MUtil_Model_ModelAbstract $model * @return void */ protected function setShowTableFooter(\MUtil_Model_Bridge_VerticalTableBridge $bridge, \MUtil_Model_ModelAbstract $model) { $fparams = array('class' => 'centerAlign'); $row = $bridge->getRow(); if (isset($row[$this->filterWhen]) && $row[$this->filterWhen]) { $count = $this->db->fetchOne("SELECT COUNT(*) FROM gems__appointments WHERE " . $this->getWhere()); if ($count) { $footer = $bridge->tfrow($fparams); $footer[] = sprintf($this->plural('This will delete %d appointment. Are you sure?', 'This will delete %d appointments. Are you sure?', $count), $count); $footer[] = ' '; $footer->actionLink(array($this->confirmParameter => 1), $this->_('Yes')); $footer[] = ' '; $footer->actionLink(array($this->request->getActionKey() => $this->abortAction), $this->_('No')); } else { $this->addMessage($this->_('Clean up not needed!')); $bridge->tfrow($this->_('No clean up needed, no appointments exist.'), $fparams); } } else { $this->addMessage($this->_('Clean up filter disabled!')); $bridge->tfrow($this->_('No clean up possible.'), array('class' => 'centerAlign')); } if ($this->displayMenu) { if (!$this->menuList) { $this->menuList = $this->menu->getCurrentMenuList($this->request, $this->_('Cancel')); $this->menuList->addCurrentSiblings(); } if ($this->menuList instanceof \Gems_Menu_MenuList) { $this->menuList->addParameterSources($bridge); } $bridge->tfrow($this->menuList, $fparams); } }
/** * Load tree * * @param int|Varien_Data_Tree_Node $parentNode * @return Varien_Data_Tree_Dbp */ public function load($parentNode = null) { $parentPath = ''; if ($parentNode instanceof Varien_Data_Tree_Node) { $parentPath = $parentNode->getData($this->_pathField); } elseif (is_numeric($parentNode)) { $parentNode = null; $select = $this->_conn->select(); $select->from($this->_table, $this->_pathField)->where("{$this->_idField} = ?", $parentNode); $parentPath = $this->_conn->fetchOne($select); } elseif (is_string($parentNode)) { $parentNode = null; $parentPath = $parentNode; } $select = clone $this->_select; $select->order($this->_table . '.' . $this->_orderField . ' ASC'); if ($parentPath) { $condition = $this->_conn->quoteInto("{$this->_table}.{$this->_pathField} like ?", "{$parentPath}/%"); $select->where($condition); } $arrNodes = $this->_conn->fetchAll($select); $childrenItems = array(); foreach ($arrNodes as $nodeInfo) { $pathToParent = explode('/', $nodeInfo[$this->_pathField]); array_pop($pathToParent); $pathToParent = implode('/', $pathToParent); $childrenItems[$pathToParent][] = $nodeInfo; } $this->addChildNodes($childrenItems, $parentPath, $parentNode); return $this; }
protected function _getGalleryAttrId() { if (!$this->_galleryAttrId) { $this->_galleryAttrId = $this->_write->fetchOne("select attribute_id from {$this->_t('eav/attribute')} where attribute_code='media_gallery' and frontend_input='gallery'"); } return $this->_galleryAttrId; }
/** * Can this round be deleted as is? * * @param int $roundId * @return boolean */ public function isDeleteable($roundId) { if (!$roundId) { return true; } $sql = "SELECT gto_id_token FROM gems__tokens WHERE gto_id_round = ? AND gto_start_time IS NOT NULL"; return (bool) (!$this->db->fetchOne($sql, $roundId)); }
/** * New installations should not be trequired to run patches. This esthablishes that level. * * @return int The lowest level of patch stored in the database. */ protected function getMinimumPatchLevel() { static $level; if (!$level) { $level = intval($this->db->fetchOne("SELECT COALESCE(MIN(gpl_level), 1) FROM gems__patch_levels")); } return $level; }
/** * Check should a patient be imported * * @param string $patientNr * @param int $orgId * @return boolean */ protected function checkPatient($patientNr, $orgId) { if (!($patientNr && $orgId)) { return false; } $select = $this->db->select(); $select->from('gems__respondent2org', array('gr2o_id_user'))->where('gr2o_patient_nr = ?', $patientNr)->where('gr2o_id_organization = ?', $orgId); return $this->db->fetchOne($select); }
/** * Works with a tree of node data to recursively import nodes * * @param integer $parentId * @param array $nodeTree * @param array $nodePermissions * @param array $nodeIdMap * * @return number */ protected function _importNodeTree($parentId, array $nodeTree, array $nodePermissions = array(), array $nodeIdMap = array()) { if (!isset($nodeTree[$parentId])) { return 0; } XenForo_Db::beginTransaction(); $total = 0; foreach ($nodeTree[$parentId] as $node) { $import = $this->_quickAssembleData($node, array('title', 'description', 'node_type_id', 'display_order', 'display_in_list', 'parent_node_id' => $this->_mapLookUp($nodeIdMap, $node['parent_node_id'], 0))); // don't even set node_name if it's not specified in the source record if ($node['node_name']) { $import['node_name'] = $node['node_name']; } switch ($node['node_type_id']) { case 'Forum': $import = $this->_quickAssembleData($node, array('discussion_count', 'message_count', 'allow_posting', 'count_messages', 'find_new', 'default_sort_order', 'default_sort_direction', 'require_prefix', 'allowed_watch_notifications', 'allow_poll', 'list_date_limit_days'), $import); if (isset($node['moderate_messages'])) { $import['moderate_threads'] = $import['moderate_replies'] = $node['moderate_messages']; } else { if (isset($node['moderate_replies'])) { $import['moderate_threads'] = $node['moderate_threads']; $import['moderate_replies'] = $node['moderate_replies']; } } $nodeId = $this->_importModel->importForum($node['node_id'], $import); break; case 'LinkForum': $import = $this->_quickAssembleData($node, array('link_url', 'redirect_count'), $import); $nodeId = $this->_importModel->importLinkForum($node['node_id'], $import); break; case 'Page': $import = $this->_quickAssembleData($node, array('publish_date', 'modified_date', 'view_count', 'list_siblings', 'list_children', 'log_visits', 'callback_class', 'callback_method'), $import); /* @var $pageModel XenForo_Model_Page */ $pageModel = XenForo_Model::create('XenForo_Model_Page'); $template = $this->_sourceDb->fetchOne(' SELECT template FROM xf_template WHERE style_id = 0 AND title = ?', $pageModel->getTemplateTitle($node)); $nodeId = $this->_importModel->importPage($node['node_id'], $import, $template); break; default: // no additional data to import, so just grab the node info $nodeId = $this->_importModel->importCategory($node['node_id'], $import); } if ($nodeId) { if (!empty($nodePermissions[$node['node_id']])) { $this->_importNodePermissions($nodeId, $nodePermissions[$node['node_id']]); } $nodeIdMap[$node['node_id']] = $nodeId; $total++; $total += $this->_importNodeTree($node['node_id'], $nodeTree, $nodePermissions, $nodeIdMap); } } XenForo_Db::commit(); return $total; }
/** * Check the tokens for a single survey */ public function checkAction() { $surveyId = $this->getSurveyId(); $where = $this->db->quoteInto('gto_id_survey = ?', $surveyId); $batch = $this->loader->getTracker()->recalculateTokens('surveyCheck' . $surveyId, $this->currentUser->getUserId(), $where); $title = sprintf($this->_('Checking for the %s survey for answers .'), $this->db->fetchOne("SELECT gsu_survey_name FROM gems__surveys WHERE gsu_id_survey = ?", $surveyId)); $this->_helper->BatchRunner($batch, $title, $this->accesslog); $this->addSnippet('Survey\\CheckAnswersInformation', 'itemDescription', $this->_('This task checks all tokens using this survey for answers.')); }
/** * 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; }
function getCurrentSchemaVersion() { // Ensure we have valid connection to the database if (!$this->_db->isConnected()) { $this->_db->getServerVersion(); } $schemaVersionTableName = $this->getPrefixedSchemaVersionTableName(); $sql = "SELECT version FROM " . $schemaVersionTableName; try { $version = $this->_db->fetchOne($sql); } catch (Exception $e) { // exception means that the schema version table doesn't exist, so create it $createSql = "CREATE TABLE {$schemaVersionTableName} ( \n version bigint NOT NULL,\n PRIMARY KEY (version)\n )"; $this->_db->query($createSql); $insertSql = "INSERT INTO {$schemaVersionTableName} (version) VALUES (0)"; $this->_db->query($insertSql); $version = $this->_db->fetchOne($sql); } return $version; }
/** * fetch creation time of the first/oldest user * * @return Tinebase_DateTime */ public function getFirstUserCreationTime() { if (!$this->_userTableHasModlogFields()) { $fallback = new Tinebase_DateTime('2014-12-01'); return $fallback; } $select = $select = $this->_db->select()->from(SQL_TABLE_PREFIX . 'accounts', 'creation_time')->where($this->_db->quoteIdentifier('login_name') . " not in ('cronuser', 'calendarscheduling')")->where($this->_db->quoteIdentifier('creation_time') . " is not null")->order('creation_time ASC')->limit(1); $creationTime = $this->_db->fetchOne($select); $result = !empty($creationTime) ? new Tinebase_DateTime($creationTime) : $fallback; return $result; }