/** * dataentry::update() * update dataentry * @return */ public function update() { $aData = array(); $subaction = Yii::app()->request->getPost('subaction'); if (isset($_REQUEST['surveyid'])) { $surveyid = $_REQUEST['surveyid']; } if (!empty($_REQUEST['sid'])) { $surveyid = (int) $_REQUEST['sid']; } $surveyid = sanitize_int($surveyid); $id = Yii::app()->request->getPost('id'); $lang = Yii::app()->request->getPost('lang'); if ($subaction == "update" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) { $baselang = Survey::model()->findByPk($surveyid)->language; Yii::app()->loadHelper("database"); $surveytable = "{{survey_" . $surveyid . '}}'; $aDataentryoutput = "<div class='header ui-widget-header'>" . gT("Data entry") . "</div>\n"; $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid)); // restet token if user is not allowed to update if (!Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'update')) { unset($fieldmap['token']); } // unset timings foreach ($fieldmap as $fname) { if ($fname['type'] == "interview_time" || $fname['type'] == "page_time" || $fname['type'] == "answer_time") { unset($fieldmap[$fname['fieldname']]); } } $thissurvey = getSurveyInfo($surveyid); $updateqr = "UPDATE {$surveytable} SET \n"; foreach ($fieldmap as $irow) { $fieldname = $irow['fieldname']; if ($fieldname == 'id') { continue; } if (isset($_POST[$fieldname])) { $thisvalue = $_POST[$fieldname]; } else { $thisvalue = ""; } if ($irow['type'] == 'lastpage') { $thisvalue = 0; } elseif ($irow['type'] == 'D') { if ($thisvalue == "") { $updateqr .= dbQuoteID($fieldname) . " = NULL, \n"; } else { $qidattributes = getQuestionAttributeValues($irow['qid']); $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey); $this->getController()->loadLibrary('Date_Time_Converter'); $datetimeobj = new date_time_converter($thisvalue, $dateformatdetails['phpdate']); //need to check if library get initialized with new value of constructor or not. //$datetimeobj = new Date_Time_Converter($thisvalue,$dateformatdetails['phpdate']); $updateqr .= dbQuoteID($fieldname) . " = '{$datetimeobj->convert("Y-m-d H:i:s")}', \n"; } } elseif (($irow['type'] == 'N' || $irow['type'] == 'K') && $thisvalue == "") { $updateqr .= dbQuoteID($fieldname) . " = NULL, \n"; } elseif ($irow['type'] == '|' && strpos($irow['fieldname'], '_filecount') && $thisvalue == "") { $updateqr .= dbQuoteID($fieldname) . " = NULL, \n"; } elseif ($irow['type'] == 'submitdate') { if (isset($_POST['completed']) && $_POST['completed'] == "N") { $updateqr .= dbQuoteID($fieldname) . " = NULL, \n"; } elseif (isset($_POST['completed']) && $thisvalue == "") { $updateqr .= dbQuoteID($fieldname) . " = " . dbQuoteAll($_POST['completed']) . ", \n"; } else { $updateqr .= dbQuoteID($fieldname) . " = " . dbQuoteAll($thisvalue) . ", \n"; } } else { $updateqr .= dbQuoteID($fieldname) . " = " . dbQuoteAll($thisvalue) . ", \n"; } } $updateqr = substr($updateqr, 0, -3); $updateqr .= " WHERE id={$id}"; $updateres = dbExecuteAssoc($updateqr) or safeDie("Update failed:<br />\n<br />{$updateqr}"); $onerecord_link = $this->getController()->createUrl('/admin/responses/sa/view/surveyid/' . $surveyid . '/id/' . $id); $allrecords_link = $this->getController()->createUrl('/admin/responses/sa/index/surveyid/' . $surveyid); $aDataentryoutput .= "<div class='messagebox ui-corner-all'><div class='successheader'>" . gT("Success") . "</div>\n" . gT("Record has been updated.") . "<br /><br />\n" . "<input type='submit' value='" . gT("View This Record") . "' onclick=\"window.open('{$onerecord_link}', '_top')\" /><br /><br />\n" . "<input type='submit' value='" . gT("Browse responses") . "' onclick=\"window.open('{$allrecords_link}', '_top')\" />\n" . "</div>\n"; $aDataentryoutput = '<div class="jumbotron message-box">'; $aDataentryoutput .= '<h2>' . gT("Success") . '</h2>'; $aDataentryoutput .= '<p class="lead">' . gT("Record has been updated.") . '</p>'; $aDataentryoutput .= "<input type='submit' class='btn btn-lg btn-default' value='" . gT("View This Record") . "' onclick=\"window.open('{$onerecord_link}', '_top')\" /><br /><br />\n" . "<input type='submit' class='btn btn-lg btn-default' value='" . gT("Browse responses") . "' onclick=\"window.open('{$allrecords_link}', '_top')\" />\n"; $aDataentryoutput .= '</div>'; $aViewUrls['output'] = $aDataentryoutput; $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData); } }
function fixLanguageConsistencyAllSurveys() { $surveyidquery = "SELECT sid,additional_languages FROM " . dbQuoteID('{{surveys}}'); $surveyidresult = Yii::app()->db->createCommand($surveyidquery)->queryAll(); foreach ($surveyidresult as $sv) { fixLanguageConsistency($sv['sid'], $sv['additional_languages']); } }
/** * Write values to database. * @param <type> $updatedValues * @param <boolean> $finished - true if the survey needs to be finalized */ private function _UpdateValuesInDatabase($updatedValues, $finished = false) { // TODO - now that using $this->updatedValues, may be able to remove local copies of it (unless needed by other sub-systems) $updatedValues = $this->updatedValues; $message = ''; if (!$this->surveyOptions['active'] || $this->sPreviewMode) { return $message; } if (!isset($_SESSION[$this->sessid]['srid'])) { $_SESSION[$this->sessid]['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']); // Create initial insert row for this record $today = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']); $sdata = array("startlanguage" => $this->surveyOptions['startlanguage']); if ($this->surveyOptions['anonymized'] == false) { $sdata['token'] = $this->surveyOptions['token']; } if ($this->surveyOptions['datestamp'] == true) { $sdata['datestamp'] = $_SESSION[$this->sessid]['datestamp']; $sdata['startdate'] = $_SESSION[$this->sessid]['datestamp']; } if ($this->surveyOptions['ipaddr'] == true) { $sdata['ipaddr'] = getIPAddress(); } if ($this->surveyOptions['refurl'] == true) { if (isset($_SESSION[$this->sessid]['refurl'])) { $sdata['refurl'] = $_SESSION[$this->sessid]['refurl']; } else { $sdata['refurl'] = getenv("HTTP_REFERER"); } } $sdata = array_filter($sdata); SurveyDynamic::sid($this->sid); $oSurvey = new SurveyDynamic(); $iNewID = $oSurvey->insertRecords($sdata); if ($iNewID) { $srid = $iNewID; $_SESSION[$this->sessid]['srid'] = $iNewID; } else { $message .= $this->gT("Unable to insert record into survey table"); // TODO - add SQL error? echo submitfailed(''); // TODO - report SQL error? } //Insert Row for Timings, if needed if ($this->surveyOptions['savetimings']) { SurveyTimingDynamic::sid($this->sid); $oSurveyTimings = new SurveyTimingDynamic(); $tdata = array('id' => $srid, 'interviewtime' => 0); switchMSSQLIdentityInsert("survey_{$this->sid}_timings", true); $iNewID = $oSurveyTimings->insertRecords($tdata); switchMSSQLIdentityInsert("survey_{$this->sid}_timings", false); } } if (count($updatedValues) > 0 || $finished) { $query = 'UPDATE ' . $this->surveyOptions['tablename'] . ' SET '; $setter = array(); switch ($this->surveyMode) { case 'question': $thisstep = $this->currentQuestionSeq; break; case 'group': $thisstep = $this->currentGroupSeq; break; case 'survey': $thisstep = 1; break; } $setter[] = dbQuoteID('lastpage') . "=" . dbQuoteAll($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[] = dbQuoteID('datestamp') . "=" . dbQuoteAll(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust'])); } if ($this->surveyOptions['ipaddr']) { $setter[] = dbQuoteID('ipaddr') . "=" . dbQuoteAll(getIPAddress()); } foreach ($updatedValues as $key => $value) { $val = is_null($value) ? NULL : $value['value']; $type = is_null($value) ? NULL : $value['type']; // Clean up the values to cope with database storage requirements switch ($type) { case 'D': //DATE if (trim($val) == '' || $val == "INVALID") { $val = NULL; // since some databases can't store blanks in date fields } // otherwise will already be in yyyy-mm-dd format after ProcessCurrentResponses() break; case '|': //File upload // This block can be removed once we require 5.3 or later if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) { $val = addslashes($val); } break; case 'N': //NUMERICAL QUESTION TYPE //NUMERICAL QUESTION TYPE case 'K': //MULTIPLE NUMERICAL QUESTION if (trim($val) == '') { $val = NULL; // since some databases can't store blanks in numerical inputs } break; default: break; } if (is_null($val)) { $setter[] = dbQuoteID($key) . "=NULL"; } else { $setter[] = dbQuoteID($key) . "=" . dbQuoteAll($val); } } $query .= implode(', ', $setter); $query .= " WHERE ID="; if (isset($_SESSION[$this->sessid]['srid']) && $this->surveyOptions['active']) { $query .= $_SESSION[$this->sessid]['srid']; if (!dbExecuteAssoc($query)) { echo submitfailed(''); // 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? } } elseif ($this->surveyOptions['savetimings']) { Yii::import("application.libraries.Save"); $cSave = new Save(); $cSave->set_answer_time(); } if ($finished) { // Delete the save control record if successfully finalize the submission $query = "DELETE FROM {{saved_control}} where srid=" . $_SESSION[$this->sessid]['srid'] . ' and sid=' . $this->sid; Yii::app()->db->createCommand($query)->execute(); if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) { $message .= ';<br />' . $query; } } else { if ($this->surveyOptions['allowsave'] && isset($_SESSION[$this->sessid]['scid'])) { SavedControl::model()->updateByPk($_SESSION[$this->sessid]['scid'], array('saved_thisstep' => $thisstep)); } } // Check Quotas $aQuotas = checkCompletedQuota($this->sid, 'return'); if ($aQuotas && !empty($aQuotas)) { checkCompletedQuota($this->sid); // will create a page and quit: why not use it directly ? } 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 .= dbQuoteID('submitdate') . "=" . dbQuoteAll(dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust'])); } else { $sQuery .= dbQuoteID('submitdate') . "=" . dbQuoteAll(date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980))); } $sQuery .= " WHERE ID=" . $_SESSION[$this->sessid]['srid']; dbExecuteAssoc($sQuery); // Checked } } } if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) { $message .= $query; } } return $message; }
/** * checkQuota() returns quota information for the current survey * @param string $checkaction - action the function must take after completing: * enforce: Enforce the Quota action * return: Return the updated quota array from getQuotaAnswers() * @param string $surveyid - Survey identification number * @return array - nested array, Quotas->Members->Fields, includes quota status and which members matched in session. */ function checkQuota($checkaction, $surveyid) { global $clienttoken; if (!isset($_SESSION['survey_' . $surveyid]['srid'])) { return; } $thissurvey = getSurveyInfo($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); $sTemplatePath = getTemplatePath($thissurvey['templatedir']); $global_matched = false; $quota_info = getQuotaInformation($surveyid, $_SESSION['survey_' . $surveyid]['s_lang']); $x = 0; $clang = Yii::app()->lang; if (count($quota_info) > 0) { // Check each quota on saved data to see if it is full $querycond = array(); foreach ($quota_info as $quota) { if (count($quota['members']) > 0) { $fields_list = array(); // Keep a list of fields for easy reference $y = 0; // We need to make the conditions for the select statement here unset($querycond); // fill the array of value and query for each fieldnames $fields_value_array = array(); $fields_query_array = array(); foreach ($quota['members'] as $member) { foreach ($member['fieldnames'] as $fieldname) { if (!in_array($fieldname, $fields_list)) { $fields_list[] = $fieldname; $fields_value_array[$fieldname] = array(); $fields_query_array[$fieldname] = array(); } $fields_value_array[$fieldname][] = $member['value']; $fields_query_array[$fieldname][] = dbQuoteID($fieldname) . " = '{$member['value']}'"; } } // fill the $querycond array with each fields_query grouped by fieldname foreach ($fields_list as $fieldname) { $select_query = " ( " . implode(' OR ', $fields_query_array[$fieldname]) . ' )'; $querycond[] = $select_query; } // Test if the fieldname is in the array of value in the session foreach ($quota['members'] as $member) { foreach ($member['fieldnames'] as $fieldname) { if (isset($_SESSION['survey_' . $surveyid][$fieldname])) { if (in_array($_SESSION['survey_' . $surveyid][$fieldname], $fields_value_array[$fieldname])) { $quota_info[$x]['members'][$y]['insession'] = "true"; } } } $y++; } unset($fields_query_array); unset($fields_value_array); // Lets only continue if any of the quota fields is in the posted page $matched_fields = false; if (isset($_POST['fieldnames'])) { $posted_fields = explode("|", $_POST['fieldnames']); foreach ($fields_list as $checkfield) { if (in_array($checkfield, $posted_fields)) { $matched_fields = true; $global_matched = true; } } } // A field was submitted that is part of the quota if ($matched_fields == true) { // Check the status of the quota, is it full or not $sQuery = "SELECT count(id) FROM {{survey_" . $surveyid . "}}\n WHERE " . implode(' AND ', $querycond) . " " . "\n AND submitdate IS NOT NULL"; $iRowCount = Yii::app()->db->createCommand($sQuery)->queryScalar(); if ($iRowCount >= $quota['Limit']) { // Now we have to check if the quota matches in the current session // This will let us know if this person is going to exceed the quota $counted_matches = 0; foreach ($quota_info[$x]['members'] as $member) { if (isset($member['insession']) && $member['insession'] == "true") { $counted_matches++; } } if ($counted_matches == count($quota['members'])) { // They are going to exceed the quota if data is submitted $quota_info[$x]['status'] = "matched"; } else { $quota_info[$x]['status'] = "notmatched"; } } else { // Quota is no in danger of being exceeded. $quota_info[$x]['status'] = "notmatched"; } } } $x++; } } else { return false; } // Now we have all the information we need about the quotas and their status. // Lets see what we should do now if ($checkaction == 'return') { return $quota_info; } elseif ($global_matched == true && $checkaction == 'enforce') { // Need to add Quota action enforcement here. reset($quota_info); $tempmsg = ""; $found = false; $redata = compact(array_keys(get_defined_vars())); foreach ($quota_info as $quota) { $quota['Message'] = templatereplace($quota['Message'], array(), $redata); $quota['Url'] = passthruReplace($quota['Url'], $thissurvey); $quota['Url'] = templatereplace($quota['Url'], array(), $redata); $quota['UrlDescrip'] = templatereplace($quota['UrlDescrip'], array(), $redata); if (isset($quota['status']) && $quota['status'] == "matched" && (isset($quota['Action']) && $quota['Action'] == "1")) { // If a token is used then mark the token as completed if (isset($clienttoken) && $clienttoken) { submittokens(true); } sendCacheHeaders(); if ($quota['AutoloadUrl'] == 1 && $quota['Url'] != "") { header("Location: " . $quota['Url']); killSurveySession($surveyid); } doHeader(); echo templatereplace(file_get_contents($sTemplatePath . "/startpage.pstpl"), array(), $redata, 'frontend_helper[2617]'); echo "\t<div class='quotamessage'>\n"; echo "\t" . $quota['Message'] . "<br /><br />\n"; echo "\t<a href='" . $quota['Url'] . "'>" . $quota['UrlDescrip'] . "</a><br />\n"; echo "\t</div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "/endpage.pstpl"), array(), $redata, 'frontend_helper[2622]'); doFooter(); killSurveySession($surveyid); exit; } if (isset($quota['status']) && $quota['status'] == "matched" && (isset($quota['Action']) && $quota['Action'] == "2")) { sendCacheHeaders(); doHeader(); $redata = compact(array_keys(get_defined_vars())); echo templatereplace(file_get_contents($sTemplatePath . "/startpage.pstpl"), array(), $redata, 'frontend_helper[2634]'); echo "\t<div class='quotamessage'>\n"; echo "\t" . $quota['Message'] . "<br /><br />\n"; echo "\t<a href='" . $quota['Url'] . "'>" . $quota['UrlDescrip'] . "</a><br />\n"; echo CHtml::form(array("/survey/index"), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey')) . "\n <input type='hidden' name='move' value='movenext' id='movenext' />\n <button class='nav-button nav-button-icon-left ui-corner-all' class='submit' accesskey='p' onclick=\"javascript:document.limesurvey.move.value = 'moveprev'; document.limesurvey.submit();\" id='moveprevbtn'>" . $clang->gT("Previous") . "</button>\n <input type='hidden' name='thisstep' value='" . $_SESSION['survey_' . $surveyid]['step'] . "' id='thisstep' />\n <input type='hidden' name='sid' value='" . returnGlobal('sid') . "' id='sid' />\n <input type='hidden' name='token' value='" . $clienttoken . "' id='token' />\n </form>\n"; echo "\t</div>\n"; echo templatereplace(file_get_contents($sTemplatePath . "/endpage.pstpl"), array(), $redata, 'frontend_helper[2644]'); doFooter(); exit; } } } else { // Unknown value return false; } }
/** * dataentry::update() * update dataentry * @return */ public function update() { $aData = array(); $subaction = Yii::app()->request->getPost('subaction'); if (isset($_REQUEST['surveyid'])) { $surveyid = $_REQUEST['surveyid']; } if (!empty($_REQUEST['sid'])) { $surveyid = (int) $_REQUEST['sid']; } $surveyid = sanitize_int($surveyid); $id = Yii::app()->request->getPost('id'); $lang = Yii::app()->request->getPost('lang'); if ($subaction == "update" && Permission::model()->hasSurveyPermission($surveyid, 'responses', 'update')) { $baselang = Survey::model()->findByPk($surveyid)->language; Yii::app()->loadHelper("database"); $surveytable = "{{survey_" . $surveyid . '}}'; $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid)); // restet token if user is not allowed to update if (!Permission::model()->hasSurveyPermission($surveyid, 'tokens', 'update')) { unset($fieldmap['token']); } // unset timings foreach ($fieldmap as $fname) { if ($fname['type'] == "interview_time" || $fname['type'] == "page_time" || $fname['type'] == "answer_time") { unset($fieldmap[$fname['fieldname']]); } } $thissurvey = getSurveyInfo($surveyid); $updateqr = "UPDATE {$surveytable} SET \n"; foreach ($fieldmap as $irow) { $fieldname = $irow['fieldname']; if ($fieldname == 'id') { continue; } if (isset($_POST[$fieldname])) { $thisvalue = $_POST[$fieldname]; } else { $thisvalue = ""; } if ($irow['type'] == 'lastpage') { $thisvalue = 0; } elseif ($irow['type'] == 'D') { if ($thisvalue == "") { $updateqr .= dbQuoteID($fieldname) . " = NULL, \n"; } else { $qidattributes = getQuestionAttributeValues($irow['qid']); $dateformatdetails = getDateFormatDataForQID($qidattributes, $thissurvey); $this->getController()->loadLibrary('Date_Time_Converter'); $datetimeobj = new date_time_converter($thisvalue, $dateformatdetails['phpdate']); //need to check if library get initialized with new value of constructor or not. //$datetimeobj = new Date_Time_Converter($thisvalue,$dateformatdetails['phpdate']); $updateqr .= dbQuoteID($fieldname) . " = '{$datetimeobj->convert("Y-m-d H:i:s")}', \n"; } } elseif (($irow['type'] == 'N' || $irow['type'] == 'K') && $thisvalue == "") { $updateqr .= dbQuoteID($fieldname) . " = NULL, \n"; } elseif ($irow['type'] == '|' && strpos($irow['fieldname'], '_filecount') && $thisvalue == "") { $updateqr .= dbQuoteID($fieldname) . " = NULL, \n"; } elseif ($irow['type'] == 'submitdate') { if (isset($_POST['completed']) && $_POST['completed'] == "N") { $updateqr .= dbQuoteID($fieldname) . " = NULL, \n"; } elseif (isset($_POST['completed']) && $thisvalue == "") { $updateqr .= dbQuoteID($fieldname) . " = " . dbQuoteAll($_POST['completed']) . ", \n"; } else { $updateqr .= dbQuoteID($fieldname) . " = " . dbQuoteAll($thisvalue) . ", \n"; } } else { $updateqr .= dbQuoteID($fieldname) . " = " . dbQuoteAll($thisvalue) . ", \n"; } } $updateqr = substr($updateqr, 0, -3); $updateqr .= " WHERE id={$id}"; $updateres = dbExecuteAssoc($updateqr) or safeDie("Update failed:<br />\n<br />{$updateqr}"); Yii::app()->setFlashMessage(sprintf(gT("The response record %s was updated."), $id)); if (Yii::app()->request->getPost('close-after-save') == 'true') { $this->getController()->redirect($this->getController()->createUrl("admin/responses/sa/view/surveyid/{$surveyid}/id/{$id}")); } else { $this->getController()->redirect($this->getController()->createUrl("admin/dataentry/sa/editdata/subaction/edit/surveyid/{$surveyid}/id/{$id}")); } } }