From a452cf022ff9a9bc747b2d1584bb3e59dd9b5bbc Mon Sep 17 00:00:00 2001 From: Carsten Schmitz Date: Sun, 14 Jan 2018 16:18:02 +0100 Subject: [PATCH] Dev Removing dbExecuteAssoc --- application/controllers/admin/dataentry.php | 146 +++++++----------- application/controllers/admin/surveyadmin.php | 11 +- application/helpers/admin/activate_helper.php | 7 +- application/helpers/database_helper.php | 33 +--- .../helpers/expressions/em_manager_helper.php | 64 ++++---- application/helpers/frontend_helper.php | 32 ++-- application/helpers/qanda_helper.php | 9 +- 7 files changed, 113 insertions(+), 189 deletions(-) diff --git a/application/controllers/admin/dataentry.php b/application/controllers/admin/dataentry.php index 3c529700c80..e3bc5e65166 100644 --- a/application/controllers/admin/dataentry.php +++ b/application/controllers/admin/dataentry.php @@ -434,15 +434,12 @@ protected function isCompatible(CDbTableSchema $base, CDbTableSchema $old, $chec public function editdata($subaction, $id, $surveyid) { - $surveyid = sanitize_int($surveyid); + $surveyid = (int) $surveyid; $oSurvey = Survey::model()->findByPk($surveyid); - $id = sanitize_int($id); + $id = (int) $id; $aViewUrls = array(); - $survey = Survey::model()->findByPk($surveyid); - $sDataEntryLanguage = $survey->language; - if (Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) { - $surveytable = $survey->responsesTableName; + $sDataEntryLanguage = $oSurvey->language; $aData = []; $aData['display']['menu_bars']['browse'] = gT("Data entry"); @@ -453,7 +450,7 @@ public function editdata($subaction, $id, $surveyid) $fnames = []; $fnames['completed'] = array('fieldname'=>"completed", 'question'=>gT("Completed"), 'type'=>'completed'); - $fnames = array_merge($fnames, createFieldMap($survey, 'full', false, false, $sDataEntryLanguage)); + $fnames = array_merge($fnames, createFieldMap($oSurvey, 'full', false, false, $sDataEntryLanguage)); // Fix private if disallowed to view token if (!Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'read')) { unset($fnames['token']); @@ -463,9 +460,8 @@ public function editdata($subaction, $id, $surveyid) //SHOW INDIVIDUAL RECORD $results = array(); if ($subaction == "edit" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) { - $idquery = "SELECT * FROM $surveytable WHERE id=$id"; - $idresult = dbExecuteAssoc($idquery) or safeDie("Couldn't get individual record
$idquery
"); - foreach ($idresult->readAll() as $idrow) { + $idresult = Response::model($surveyid)->findByPk($id); + foreach ($idresult as $idrow) { $results[] = $idrow; } } elseif ($subaction == "editsaved" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) { @@ -495,7 +491,7 @@ public function editdata($subaction, $id, $surveyid) $responses[$svrow['fieldname']] = $svrow['value']; } // while - $fieldmap = createFieldMap($survey, 'full', false, false, $survey->language); + $fieldmap = createFieldMap($oSurvey, 'full', false, false, $oSurvey->language); $results1 = array(); foreach ($fieldmap as $fm) { if (isset($responses[$fm['fieldname']])) { @@ -559,7 +555,7 @@ public function editdata($subaction, $id, $surveyid) switch ($fname['type']) { case "completed": // First compute the submitdate - if ($survey->anonymized == "Y") { + if ($oSurvey->anonymized == "Y") { // In case of anonymized responses survey with no datestamp // then the the answer submitdate gets a conventional timestamp // 1st Jan 1980 @@ -1235,7 +1231,6 @@ public function delete() $surveytable = $survey->responsesTableName; $aData['thissurvey'] = getSurveyInfo($surveyid); - $delquery = "DELETE FROM $surveytable WHERE id=$id"; Yii::app()->loadHelper('database'); $beforeDataEntryDelete = new PluginEvent('beforeDataEntryDelete'); @@ -1243,7 +1238,7 @@ public function delete() $beforeDataEntryDelete->set('iResponseID', $id); App()->getPluginManager()->dispatchEvent($beforeDataEntryDelete); - dbExecuteAssoc($delquery) or safeDie("Couldn't delete record $id
\n"); + Response::model($surveyid)->findByPk($id)->delete(true); $aData['sidemenu']['state'] = false; $aData['menu']['edition'] = true; @@ -1290,7 +1285,7 @@ public function update() $thissurvey = getSurveyInfo($surveyid); $updateqr = "UPDATE $surveytable SET \n"; - + $aFieldAttributes=[]; foreach ($fieldmap as $irow) { $fieldname = $irow['fieldname']; if ($fieldname == 'id') { @@ -1305,7 +1300,7 @@ public function update() $thisvalue = 0; } elseif ($irow['type'] == Question::QT_D_DATE) { if ($thisvalue == "") { - $updateqr .= App()->db->quoteColumnName($fieldname)." = NULL, \n"; + $aFieldAttributes[$fieldname] = NULL; } else { $qidattributes = QuestionAttribute::model()->getQuestionAttributes($irow['qid']); $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey); @@ -1318,33 +1313,33 @@ public function update() } //need to check if library get initialized with new value of constructor or not. - $updateqr .= App()->db->quoteColumnName($fieldname)." = '{$dateoutput}', \n"; + $aFieldAttributes[$fieldname] = $dateoutput; } } elseif (($irow['type'] == Question::QT_N_NUMERICAL || $irow['type'] == Question::QT_K_MULTIPLE_NUMERICAL_QUESTION) && $thisvalue == "") { - $updateqr .= App()->db->quoteColumnName($fieldname)." = NULL, \n"; + $aFieldAttributes[$fieldname] = NULL; } elseif ($irow['type'] == Question::QT_VERTICAL_FILE_UPLOAD && strpos($irow['fieldname'], '_filecount') && $thisvalue == "") { - $updateqr .= App()->db->quoteColumnName($fieldname)." = NULL, \n"; + $aFieldAttributes[$fieldname] = NULL; } elseif ($irow['type'] == 'submitdate') { if (isset($_POST['completed']) && ($_POST['completed'] == "N")) { - $updateqr .= App()->db->quoteColumnName($fieldname)." = NULL, \n"; + $aFieldAttributes[$fieldname] = NULL; } elseif (isset($_POST['completed']) && $thisvalue == "") { - $updateqr .= App()->db->quoteColumnName($fieldname)." = ".App()->db->quoteValue($_POST['completed']).", \n"; + $aFieldAttributes[$fieldname] = $_POST['completed']; } else { - $updateqr .= App()->db->quoteColumnName($fieldname)." = ".App()->db->quoteValue($thisvalue).", \n"; + $aFieldAttributes[$fieldname] = $thisvalue; } } else { - $updateqr .= App()->db->quoteColumnName($fieldname)." = ".App()->db->quoteValue($thisvalue).", \n"; + $aFieldAttributes[$fieldname] = $thisvalue; } } - $updateqr = substr($updateqr, 0, -3); - $updateqr .= " WHERE id=$id"; $beforeDataEntryUpdate = new PluginEvent('beforeDataEntryUpdate'); $beforeDataEntryUpdate->set('iSurveyID', $surveyid); $beforeDataEntryUpdate->set('iResponseID', $id); App()->getPluginManager()->dispatchEvent($beforeDataEntryUpdate); - dbExecuteAssoc($updateqr) or safeDie("Update failed:
\n
$updateqr"); + $arResponse=Response::model($surveyid)->findByPk($id); + $arResponse->setAttributes($aFieldAttributes,false); + $arResponse->save(); Yii::app()->setFlashMessage(sprintf(gT("The response record %s was updated."), $id)); if (Yii::app()->request->getPost('close-after-save') == 'true') { @@ -1386,30 +1381,21 @@ public function insert() $lastanswfortoken = ''; // check if a previous answer has been submitted or saved if (Yii::app()->request->getPost('token') && Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'update')) { - $tokencompleted = ""; - $tcquery = "SELECT completed from {{tokens_{$surveyid}}} WHERE token=".App()->db->quoteValue($_POST['token']); - $tcresult = dbExecuteAssoc($tcquery); - $tcresult = $tcresult->readAll(); - $tccount = count($tcresult); - foreach ($tcresult as $tcrow) { - $tokencompleted = $tcrow['completed']; - } - - if ($tccount < 1) { -// token doesn't exist in survey participants table + $aToken = Token::model($surveyid)->findByAttributes(['token'=>$_POST['token']]); + if (empty($aToken)) { + // token doesn't exist in survey participants table $lastanswfortoken = 'UnknownToken'; } elseif ($survey->isAnonymized) { -// token exist but survey is anonymous, check completed state + // token exist but survey is anonymous, check completed state // token is completed - if ($tokencompleted != "" && $tokencompleted != "N") { + if ($aToken->completed != "" && $aToken->completed != "N") { $lastanswfortoken = 'PrivacyProtected'; } } else { -// token is valid, survey not anonymous, try to get last recorded response id - $aquery = "SELECT id,startlanguage FROM $surveytable WHERE token=".App()->db->quoteValue($_POST['token']); - $aresult = dbExecuteAssoc($aquery); - foreach ($aresult->readAll() as $arow) { - if ($tokencompleted != "N") { $lastanswfortoken = $arow['id']; } + // token is valid, survey not anonymous, try to get last recorded response id + $aresult = Response::model($surveyid)->findAllByAttributes(['token'=>$_POST['token']]); + foreach ($aresult as $arow) { + if ($aToken->completed != "N") { $lastanswfortoken = $arow['id']; } $rlanguage = $arow['startlanguage']; } } @@ -1547,41 +1533,36 @@ public function insert() $new_response->save(); $last_db_id = $new_response->getPrimaryKey(); if (isset($_POST['closerecord']) && isset($_POST['token']) && $_POST['token'] != '') { -// submittoken + // submittoken // get submit date if (isset($_POST['closedate'])) { $submitdate = $_POST['closedate']; } else { $submitdate = date("Y-m-d H:i:s"); } - - // check how many uses the token has left - $usesquery = "SELECT usesleft FROM {{tokens_}}$surveyid WHERE token=".App()->db->quoteValue($_POST['token']); - $usesresult = dbExecuteAssoc($usesquery); - $usesrow = $usesresult->readAll(); //$usesresult->row_array() - if (isset($usesrow)) { $usesleft = $usesrow[0]['usesleft']; } - - // query for updating tokens - $utquery = "UPDATE {{tokens_$surveyid}}\n"; + // query for updating tokens uses left + $aToken=Token::model($surveyid)->findByAttributes(['token'=>$_POST['token']]); if (isTokenCompletedDatestamped($thissurvey)) { - if (isset($usesleft) && $usesleft <= 1) { - $utquery .= "SET usesleft=usesleft-1, completed=".App()->db->quoteValue($submitdate); + if ($aToken->usesleft <= 1) { + $aToken->usesleft=((int)$aToken->usesleft)-1; + $aToken->completed=$submitdate; } else { - $utquery .= "SET usesleft=usesleft-1\n"; + $aToken->usesleft=((int)$aToken->usesleft)-1; } } else { - if (isset($usesleft) && $usesleft <= 1) { - $utquery .= "SET usesleft=usesleft-1, completed='Y'\n"; + if ($aToken->usesleft <= 1) { + $aToken->usesleft=((int)$aToken->usesleft)-1; + $aToken->completed='Y'; } else { - $utquery .= "SET usesleft=usesleft-1\n"; + $aToken->usesleft=((int)$aToken->usesleft)-1; } } - $utquery .= "WHERE token=".App()->db->quoteValue($_POST['token']); - dbExecuteAssoc($utquery); //Yii::app()->db->Execute($utquery) or safeDie ("Couldn't update tokens table!
\n$utquery
\n".Yii::app()->db->ErrorMsg()); - + $aToken->save(); + // save submitdate into survey table - $sdquery = "UPDATE {{survey_$surveyid}} SET submitdate='".$submitdate."' WHERE id={$last_db_id}\n"; - dbExecuteAssoc($sdquery) or safeDie("Couldn't set submitdate response in survey table!
\n$sdquery
\n"); + $aResponse=Response::model($surveyid)->findByPk($last_db_id); + $aResponse->submitdate=$submitdate; + $aResponse->save(); } if (isset($_POST['save']) && $_POST['save'] == "on") { $srid = $last_db_id; @@ -1604,30 +1585,19 @@ public function insert() $aDataentrymsgs[] = CHtml::tag('font', array('class'=>'successtitle'), gT("Your survey responses have been saved successfully. You will be sent a confirmation e-mail. Please make sure to save your password, since we will not be able to retrieve it for you.")); $tokens_table = "{{tokens_$surveyid}}"; if (tableExists($tokens_table)) { - //If the query fails, assume no tokens table exists - $tkquery = "SELECT * FROM {$tokens_table}"; - dbExecuteAssoc($tkquery); - /*$tokendata = array ( - "firstname"=> $saver['identifier'], - "lastname"=> $saver['identifier'], - "email"=>$saver['email'], - "token"=>randomChars(15), - "language"=>$saver['language'], - "sent"=>dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i", $timeadjust), - "completed"=>"N");*/ - - $columns = array("firstname", "lastname", "email", "token", - "language", "sent", "completed"); - $values = array("'".$saver['identifier']."'", "'".$saver['identifier']."'", "'".$saver['email']."'", "'".$password."'", - "'".randomChars(15)."'", "'".$saver['language']."'", "'"."N"."'"); - - $SQL = "INSERT INTO {$tokens_table} - (".implode(',', $columns).") - VALUES - (".implode(',', $values).")"; - dbExecuteAssoc($SQL); + $tokendata = array ( + "firstname"=> $saver['identifier'], + "lastname"=> $saver['identifier'], + "email"=>$saver['email'], + "token"=>$password, + "language"=>$saver['language'], + "sent"=>date("Y-m-d H:i:s"), + "completed"=>"N"); + + $aToken=new Token($surveyid); + $aToken->setAttributes($tokendata, false); + $aToken->save(); $aDataentrymsgs[] = CHtml::tag('font', array('class'=>'successtitle'), gT("A survey participant entry for the saved survey has been created too.")); - //$aDataentryoutput .= "
\n"; } if ($saver['email']) { //Send email diff --git a/application/controllers/admin/surveyadmin.php b/application/controllers/admin/surveyadmin.php index 7f909ca4d28..3b193c5d3d9 100644 --- a/application/controllers/admin/surveyadmin.php +++ b/application/controllers/admin/surveyadmin.php @@ -1812,7 +1812,7 @@ private function _createSampleGroup($iSurveyID) $oGroup->group_order = 1; $oGroup->grelevance = '1'; $oGroup->save(); - $oGroupL10ns = new QuestionGroupL10ns(); + $oGroupL10ns = new QuestionGroupL10n(); $oGroupL10ns->gid = $oGroup->gid; $oGroupL10ns->group_name = gt('My first question group', 'html', $sLanguage); $oGroupL10ns->language = $sLanguage; @@ -1835,13 +1835,16 @@ private function _createSampleQuestion($iSurveyID, $iGroupID) $oQuestion->gid = $iGroupID; $oQuestion->type = Question::QT_T_LONG_FREE_TEXT; $oQuestion->title = 'Q00'; - $oQuestion->question = gt('A first example question. Please answer this question:', 'html', $sLanguage); - $oQuestion->help = gt('This is a question help text.', 'html', $sLanguage); $oQuestion->mandatory = 'N'; $oQuestion->relevance = '1'; $oQuestion->question_order = 1; - $oQuestion->language = $sLanguage; $oQuestion->save(); + $oQuestionLS = new QuestionL10n(); + $oQuestionLS->question = gt('A first example question. Please answer this question:', 'html', $sLanguage); + $oQuestionLS->help = gt('This is a question help text.', 'html', $sLanguage); + $oQuestionLS->language = $sLanguage; + $oQuestionLS->qid=$oQuestion->qid; + $oQuestionLS->save(); return $oQuestion->qid; } diff --git a/application/helpers/admin/activate_helper.php b/application/helpers/admin/activate_helper.php index 6695fbc9a24..0e6822b6dfa 100644 --- a/application/helpers/admin/activate_helper.php +++ b/application/helpers/admin/activate_helper.php @@ -512,9 +512,10 @@ function mssql_drop_constraint($fieldname, $tablename) sys.sysobjects AS t_obj ON c_obj.parent_obj = t_obj.id INNER JOIN sys.sysconstraints AS con ON c_obj.id = con.constid INNER JOIN sys.syscolumns AS col ON t_obj.id = col.id AND con.colid = col.colid - WHERE (c_obj.xtype = 'D') AND (col.name = '$fieldname') AND (t_obj.name='{{{$tablename}}}')"; - $result = dbExecuteAssoc($dfquery)->read(); - $defaultname = $result['CONTRAINT_NAME']; + WHERE (c_obj.xtype = 'D') AND (col.name = '{$fieldname}') AND (t_obj.name='{{{$tablename}}}')"; + $result = Yii::app()->db->createCommand($dfquery)->query(); + $result = $result->read(); + $defaultname = $result['CONSTRAINT_NAME']; if ($defaultname != false) { modifyDatabase("", "ALTER TABLE {{{$tablename}}} DROP CONSTRAINT {$defaultname[0]}"); echo $modifyoutput; flush(); } diff --git a/application/helpers/database_helper.php b/application/helpers/database_helper.php index ef2efd4ca77..a16f158d713 100644 --- a/application/helpers/database_helper.php +++ b/application/helpers/database_helper.php @@ -16,38 +16,7 @@ */ /** - * - * @param string $sql - * @param array|bool $inputarr - * @param boolean $silent - * @return bool|CDbDataReader - * @throws Exception - * @deprecated Do not use anymore. If you see this replace it with a proper ActiveRecord Model query - */ -function dbExecuteAssoc($sql, $inputarr = false, $silent = true) -{ - $error = ''; - try { - if ($inputarr) { - $dataset = Yii::app()->db->createCommand($sql)->bindValues($inputarr)->query(); //Checked - } else { - $dataset = Yii::app()->db->createCommand($sql)->query(); - - } - } catch (CDbException $e) { - $error = $e->getMessage(); - $dataset = false; - } - - if (!$dataset && (Yii::app()->getConfig('debug') > 0 || !$silent)) { - // Exception is better than safeDie, because you can see the backtrace. - throw new \Exception('Error executing query in dbExecuteAssoc:'.$error); - } - return $dataset; -} - -/** - * Return the random function to use in ORDER BY sql statements + * Return the database-specific random function to use in ORDER BY sql statements * * @return string */ diff --git a/application/helpers/expressions/em_manager_helper.php b/application/helpers/expressions/em_manager_helper.php index 318f7e81d82..ec56f885a12 100644 --- a/application/helpers/expressions/em_manager_helper.php +++ b/application/helpers/expressions/em_manager_helper.php @@ -5426,9 +5426,8 @@ private function _UpdateValuesInDatabase($finished=false) } } if (count($updatedValues) > 0 || $finished) - { - $query = 'UPDATE ' . $this->surveyOptions['tablename'] . ' SET '; - $setter = array(); + { + $aResponseAttributes = array(); switch ($this->surveyMode) { case 'question': @@ -5445,14 +5444,14 @@ private function _UpdateValuesInDatabase($finished=false) $thisstep = 0; break; } - $setter[] = App()->db->quoteColumnName('lastpage') . "=" . App()->db->quoteValue($thisstep); + $aResponseAttributes['lastpage'] = $thisstep; if ($this->surveyOptions['datestamp'] && isset($_SESSION[$this->sessid]['datestamp'])) { $_SESSION[$this->sessid]['datestamp']=dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']); - $setter[] = App()->db->quoteColumnName('datestamp') . "=" . App()->db->quoteValue(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust'])); + $aResponseAttributes['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']); } if ($this->surveyOptions['ipaddr']) { - $setter[] = App()->db->quoteColumnName('ipaddr') . "=" . App()->db->quoteValue(getIPAddress()); + $aResponseAttributes['ipaddr'] = getIPAddress(); } foreach ($updatedValues as $key=>$value) @@ -5485,29 +5484,24 @@ private function _UpdateValuesInDatabase($finished=false) // @todo : control length of DB string, if answers in single choice is valid too (for example) ? break; } - if (is_null($val)) - { - $setter[] = App()->db->quoteColumnName($key) . "=NULL"; - } - else - { - $setter[] = App()->db->quoteColumnName($key) . "=" . App()->db->quoteValue(stripCtrlChars($val)); + if (is_null($val)) { + $aResponseAttributes[$key] = NULL; + } else { + $aResponseAttributes[$key] = stripCtrlChars($val); } } - $query .= implode(', ', $setter); - $query .= " WHERE ID="; if (isset($_SESSION[$this->sessid]['srid']) && $this->surveyOptions['active']) { - $query .= $_SESSION[$this->sessid]['srid']; - - if (!dbExecuteAssoc($query)) + $response = Response::model($this->sid)->findByPk($_SESSION[$this->sessid]['srid']); + $response->setAttributes($aResponseAttributes, false); + if (!$response->save()) { - // TODO: This kills the session if adminemail is defined, so the queries below won't work. - $message = submitfailed('', $query); // TODO - report SQL error? + // @todo This kills the session if adminemail is defined, so the queries below won't work. + $message = submitfailed('', join("\n",$response->getErorrs())); // TODO - report SQL error? if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) { - $message .= $this->gT('Error in SQL update'); // TODO - add SQL error? + $message .= $this->gT('Error on response update'); // @todo Add SQL error? } LimeExpressionManager::addFrontendFlashMessage('error', $message, $this->sid); @@ -5550,18 +5544,16 @@ private function _UpdateValuesInDatabase($finished=false) else { if ($finished) { - $sQuery = 'UPDATE '.$this->surveyOptions['tablename'] . " SET "; if($this->surveyOptions['datestamp']) { // Replace with date("Y-m-d H:i:s") ? See timeadjust - $sQuery .= App()->db->quoteColumnName('submitdate') . "=" . App()->db->quoteValue(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust'])); - } - else - { - $sQuery .= App()->db->quoteColumnName('submitdate') . "=" . App()->db->quoteValue(date("Y-m-d H:i:s",mktime(0,0,0,1,1,1980))); + $submitdate = date("Y-m-d H:i:s"); + } else { + $submitdate = date("Y-m-d H:i:s",mktime(0,0,0,1,1,1980)); } - $sQuery .= " WHERE ID=".$_SESSION[$this->sessid]['srid']; - dbExecuteAssoc($sQuery); // Checked + $aResponse = Response::model($this->sid)->findByPk($_SESSION[$this->sessid]['srid']); + $aResponse->submitdate = $submitdate; + $aResponse->save(); } } @@ -8558,14 +8550,14 @@ public function getAnswerSetsForEM($surveyid=NULL,$lang=NULL) $where .= " and a.language='".$lang."'" ; } - $query = "SELECT a.qid, a.code, l.answer, a.scale_id, a.assessment_value" + $sQuery = "SELECT a.qid, a.code, l.answer, a.scale_id, a.assessment_value" ." FROM {{answers}} AS a" ." JOIN {{questions}} q on a.qid=q.qid" ." JOIN {{answer_l10ns}} l on l.aid=a.aid" ." WHERE ".$where ." ORDER BY a.qid, a.scale_id, a.sortorder"; - $data = dbExecuteAssoc($query); + $data = Yii::app()->db->createCommand($sQuery)->query(); $qans = array(); @@ -9860,9 +9852,8 @@ static public function &TSVSurveyExport($sid) $otherlangs=''; // Export survey-level information - $query = "select * from {{surveys}} where sid = " . $sid; - $data = dbExecuteAssoc($query); - foreach ($data->readAll() as $r) + $arSurveyData = Survey::model()->findByPk($sid); + foreach ($arSurveyData as $r) { foreach ($r as $key=>$value) { @@ -9888,9 +9879,8 @@ static public function &TSVSurveyExport($sid) $langs = array_unique($langs); // Export survey language settings - $query = "select * from {{surveys_languagesettings}} where surveyls_survey_id = " . $sid; - $data = dbExecuteAssoc($query); - foreach ($data->readAll() as $r) + $arSurveyLanguageData = SurveyLanguageSetting::findAll("surveyls_survey_id = " . $sid); + foreach ($arSurveyLanguageData as $r) { $_lang = $r['surveyls_language']; foreach ($r as $key=>$value) diff --git a/application/helpers/frontend_helper.php b/application/helpers/frontend_helper.php index c4c9c7f583b..9fc8651c57b 100644 --- a/application/helpers/frontend_helper.php +++ b/application/helpers/frontend_helper.php @@ -1061,16 +1061,14 @@ function randomizationQuestion($surveyid, array $fieldmap, $preview) $randomGroups = array(); // Find all defined randomization groups through question attribute values - // TODO: move the sql queries to a model if (in_array(Yii::app()->db->getDriverName(), array('mssql', 'sqlsrv', 'dblib'))) { - $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid=$surveyid GROUP BY attr.qid, CAST(value as varchar(255))"; + //Previous query: $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) as value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and CAST(value as varchar(255)) <> '' and sid=$surveyid GROUP BY attr.qid, CAST(value as varchar(255))"; + $rgresult=Question::model()->with('questionAttributes')->together()->findAll("attribute='random_group' and CAST(value as varchar(255)) <>'' and sid={$surveyid}"); } else { - $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid=$surveyid GROUP BY attr.qid, value"; + //Previous query: $rgquery = "SELECT attr.qid, value FROM {{question_attributes}} as attr right join {{questions}} as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid=$surveyid GROUP BY attr.qid, value"; + $rgresult=Question::model()->with('questionAttributes')->together()->findAll("attribute='random_group' and value <>'' and sid={$surveyid}"); } - - $rgresult = dbExecuteAssoc($rgquery); - - foreach ($rgresult->readAll() as $rgrow) { + foreach ($rgresult as $rgrow) { $randomGroups[$rgrow['value']][] = $rgrow['qid']; // Get the question IDs for each randomization group } @@ -1519,12 +1517,9 @@ function doAssessment($surveyid) } } else { // Single choice question - $usquery = "SELECT assessment_value FROM {{answers}} where qid=".$field['qid']." and language='$baselang' and code=".App()->db->quoteValue($_SESSION['survey_'.$surveyid][$field['fieldname']]); - $usresult = dbExecuteAssoc($usquery); //Checked - - if ($usresult) { - $usrow = $usresult->read(); - $assessmentValue = $usrow['assessment_value']; + $usrow = Answer::findByAttributes(['qid'=>$field['qid'],'code'=>$_SESSION['survey_'.$surveyid][$field['fieldname']]]); + if (!empty($usrow)) { + $assessmentValue = $usrow->assessment_value; // $total = $total+$usrow['assessment_value']; } } @@ -1624,16 +1619,13 @@ function UpdateGroupList($surveyid, $language) unset ($_SESSION['survey_'.$surveyid]['grouplist']); - // TODO: replace by group model method - $query = "SELECT * FROM {{groups}} g join {{group_l10ns}} ls on ls.gid=g.gid WHERE sid=$surveyid AND language='".$language."' ORDER BY group_order"; - $result = dbExecuteAssoc($query) or safeDie("Couldn't get group list
$query
"); //Checked + $result = QuestionGroup::model()->findAllByAttributes(['sid'=>$surveyid]); $groupList = array(); - - foreach ($result->readAll() as $row) { + foreach ($result as $row) { $group = array( 'gid' => $row['gid'], - 'group_name' => $row['group_name'], - 'description' => $row['description']); + 'group_name' => $row->questionGroupL10ns[$language]->group_name, + 'description' => $row->questionGroupL10ns[$language]->description); $groupList[] = $group; $gidList[$row['gid']] = $group; } diff --git a/application/helpers/qanda_helper.php b/application/helpers/qanda_helper.php index a7b775ab01d..89492450bb5 100644 --- a/application/helpers/qanda_helper.php +++ b/application/helpers/qanda_helper.php @@ -4340,16 +4340,15 @@ function do_array($ia) $right_exists = false; } // $right_exists is a flag to find out if there are any right hand answer parts. If there arent we can leave out the right td column + if ($aQuestionAttributes['random_order'] == 1) { - $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='".$_SESSION['survey_'.Yii::app()->getConfig('surveyID')]['s_lang']."' ORDER BY ".dbRandom(); + $sOrder = dbRandom(); } else { - $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia[0]} AND language='".$_SESSION['survey_'.Yii::app()->getConfig('surveyID')]['s_lang']."' ORDER BY question_order"; + $sOrder = 'question_order'; } + $aQuestions = Question::model()->findAll(array('order'=>$sOrder, 'condition'=>'parent_qid=:parent_qid', 'params'=>array(':parent_qid'=>$ia[0]))); - $ansresult = dbExecuteAssoc($ansquery); //Checked - $aQuestions = $ansresult->readAll(); $fn = 1; - $inputnames = []; $sRows = "";