/**
  * 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 = '';
     $_SESSION[$this->sessid]['datestamp'] = dateShift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
     if ($this->surveyOptions['active'] && !isset($_SESSION[$this->sessid]['srid'])) {
         // 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 = array_merge($sdata, array("token" => $this->surveyOptions['token']));
         }
         if ($this->surveyOptions['datestamp'] == true) {
             $sdata = array_merge($sdata, array("datestamp" => $this->surveyOptions['datestamp'] ? $_SESSION[$this->sessid]['datestamp'] : NULL, "startdate" => $this->surveyOptions['datestamp'] ? $_SESSION[$this->sessid]['datestamp'] : date("Y-m-d H:i:s", 0)));
         }
         if ($this->surveyOptions['ipaddr'] == true) {
             $sdata = array_merge($sdata, array("ipaddr" => getIPAddress()));
         }
         if ($this->surveyOptions['refurl'] == true) {
             $sdata = array_merge($sdata, array("refurl" => $this->surveyOptions['refurl'] ? getenv("HTTP_REFERER") : NULL));
         }
         $sdata = array_filter($sdata);
         Survey_dynamic::sid($this->sid);
         $oSurvey = new Survey_dynamic();
         $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?
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             Survey_timings::sid($this->sid);
             $oSurveyTimings = new Survey_timings();
             $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'])) {
             $setter[] = dbQuoteID('datestamp') . "=" . dbQuoteAll($_SESSION[$this->sessid]['datestamp']);
         }
         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 = 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'])) {
                     Saved_control::model()->updateByPk($_SESSION[$this->sessid]['scid'], array('saved_thisstep' => $thisstep));
                 }
             }
             // Check Quotas
             $bQuotaMatched = false;
             $aQuotas = checkQuota('return', $this->sid);
             if ($aQuotas !== false) {
                 if ($aQuotas != false) {
                     foreach ($aQuotas as $aQuota) {
                         if (isset($aQuota['status']) && $aQuota['status'] == 'matched') {
                             $bQuotaMatched = true;
                         }
                     }
                 }
             }
             if ($bQuotaMatched) {
                 checkQuota('enforce', $this->sid);
                 // will create a page and quit.
             } 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($_SESSION[$this->sessid]['datestamp']);
                     } 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;
 }
示例#2
0
 private function _handleFileUpload($surveyid, $aData)
 {
     $vvoutput = '';
     $donotimport = array();
     $clang = $this->getController()->lang;
     $filePath = $this->_moveUploadedFile($aData);
     $aFileContents = $this->_readFile($filePath);
     unlink($filePath);
     //delete the uploaded file
     unset($aFileContents[0]);
     //delete the first line
     Survey_dynamic::sid($surveyid);
     $survey = new Survey_dynamic();
     list($aFieldnames, $nbOfFields) = $this->_getFieldInfo($aFileContents);
     $aRealFieldNames = Yii::app()->db->getSchema()->getTable($survey->tableName())->getColumnNames();
     if (Yii::app()->request->getPost('noid') == "noid") {
         unset($aRealFieldNames[0]);
     }
     if (Yii::app()->request->getPost('finalized') == "notfinalized") {
         unset($aRealFieldNames[1]);
     }
     unset($aFileContents[1]);
     //delete the second line
     //See if any fields in the import file don't exist in the active survey
     $missing = array_diff($aFieldnames, $aRealFieldNames);
     if (is_array($missing) && count($missing) > 0) {
         foreach ($missing as $key => $val) {
             $donotimport[] = $key;
             unset($aFieldnames[$key]);
         }
     }
     if (Yii::app()->request->getPost('finalized') == "notfinalized") {
         $donotimport[] = 1;
         unset($aFieldnames[1]);
     }
     $importcount = 0;
     $recordcount = 0;
     $aFieldnames = array_map('dbQuoteID', $aFieldnames);
     // Find out which fields are datefields, these have to be null if the imported string is empty
     $fieldmap = createFieldMap($surveyid, 'full', false, false, getBaseLanguageFromSurveyID($surveyid));
     $datefields = array();
     $numericfields = array();
     foreach ($fieldmap as $field) {
         if ($field['type'] == 'D') {
             $datefields[] = $field['fieldname'];
         }
         if ($field['type'] == 'N' || $field['type'] == 'K') {
             $numericfields[] = $field['fieldname'];
         }
     }
     foreach ($aFileContents as $row) {
         if (trim($row) != "") {
             $recordcount++;
             $fieldvalues = $this->_prepFieldValues($aFieldnames, $row, $nbOfFields, $donotimport);
             $fielddata = $aFieldnames === array() && $fieldvalues === array() ? array() : array_combine($aFieldnames, $fieldvalues);
             foreach ($datefields as $datefield) {
                 if (@$fielddata["'" . $datefield . "'"] == '') {
                     unset($fielddata["'" . $datefield . "'"]);
                 }
             }
             foreach ($numericfields as $numericfield) {
                 if ($fielddata["`" . $numericfield . "`"] == '') {
                     unset($fielddata["`" . $numericfield . "`"]);
                 }
             }
             if (isset($fielddata['`submitdate`']) && $fielddata['`submitdate`'] == 'NULL') {
                 unset($fielddata['`submitdate`']);
             }
             if ($fielddata['`lastpage`'] == '') {
                 $fielddata['`lastpage`'] = '0';
             }
             $recordexists = false;
             if (isset($fielddata['`id`'])) {
                 $result = $survey->findAllByAttributes(array('id' => $fielddata['`id`']));
                 $recordexists = $result > 0;
                 // Check if record with same id exists
                 if ($recordexists) {
                     if (Yii::app()->request->getPost('insert') == "ignore") {
                         $aData['msgs'][] .= sprintf($clang->gT("Record ID %s was skipped because of duplicate ID."), $fielddata['`id`']);
                         continue;
                     }
                     if (Yii::app()->request->getPost('insert') == "replace") {
                         $result = $survey->deleteSomeRecords(array('id' => $fielddata['`id`']));
                         $recordexists = false;
                     }
                 }
             }
             if (Yii::app()->request->getPost('insert') == "renumber") {
                 unset($fielddata['`id`']);
             }
             if (isset($fielddata['`id`'])) {
                 switchMSSQLIdentityInsert("survey_{$surveyid}", true);
             }
             $result = $survey->insertRecords($fielddata);
             if (isset($fielddata['id'])) {
                 switchMSSQLIdentityInsert("survey_{$surveyid}", false);
             }
             if (!$result) {
                 $aData['error_msg'] = sprintf($clang->gT("Import failed on record %d"), $recordcount);
                 $this->_renderWrappedTemplate('dataentry', 'warning_header', $aData);
                 die;
             } else {
                 $importcount++;
             }
             $aData['importcount'] = $importcount;
         }
     }
     $aData['noid'] = Yii::app()->request->getPost('noid');
     $aData['insertstyle'] = Yii::app()->request->getPost('insertstyle');
     $this->_renderWrappedTemplate('dataentry', 'vvimport_upload', $aData);
 }
示例#3
0
 /**
  * RPC Routine to add a response to the survey responses collection.
  * Returns the id of the inserted survey response
  *
  * @access public
  * @param string $sSessionKey Auth credentials
  * @param int $iSurveyID Id of the Survey to insert responses
  * @param struct $aResponseData The actual response
  * @return int The response ID
  */
 public function add_response($sSessionKey, $iSurveyID, $aResponseData)
 {
     if (!$this->_checkSessionKey($sSessionKey)) {
         return array('status' => 'Invalid session key');
     }
     $oSurvey = Survey::model()->findByPk($iSurveyID);
     if (is_null($oSurvey)) {
         return array('status' => 'Error: Invalid survey ID');
     }
     if (hasSurveyPermission($iSurveyID, 'responses', 'create')) {
         if (!Yii::app()->db->schema->getTable('{{survey_' . $iSurveyID . '}}')) {
             return array('status' => 'No survey response table');
         }
         //set required values if not set
         // @todo: Some of this is part of the validation and should be done in the model instead
         if (!isset($aResponseData['submitdate'])) {
             $aResponseData['submitdate'] = date("Y-m-d H:i:s");
         }
         if (!isset($aResponseData['startlanguage'])) {
             $aResponseData['startlanguage'] = getBaseLanguageFromSurveyID($iSurveyID);
         }
         if ($oSurvey->datestamp == 'Y') {
             if (!isset($aResponseData['datestamp'])) {
                 $aResponseData['datestamp'] = date("Y-m-d H:i:s");
             }
             if (!isset($aResponseData['startdate'])) {
                 $aResponseData['startdate'] = date("Y-m-d H:i:s");
             }
         }
         Survey_dynamic::sid($iSurveyID);
         $survey_dynamic = new Survey_dynamic();
         $result_id = $survey_dynamic->insertRecords($aResponseData);
         if ($result_id) {
             return $result_id;
         } else {
             return array('status' => 'Unable to add response');
         }
     } else {
         return array('status' => 'No permission');
     }
 }