Example #1
0
function createinsertquery()
{
    global $thissurvey, $timeadjust, $move, $thisstep;
    global $deletenonvalues, $thistpl;
    global $surveyid, $connect, $clang, $postedfieldnames, $bFinalizeThisAnswer;
    require_once "classes/inputfilter/class.inputfilter_clean.php";
    $myFilter = new InputFilter('', '', 1, 1, 1);
    $fieldmap = createFieldMap($surveyid);
    //Creates a list of the legitimate questions for this survey
    if (isset($_SESSION['insertarray']) && is_array($_SESSION['insertarray'])) {
        $inserts = array_unique($_SESSION['insertarray']);
        $colnames_hidden = array();
        foreach ($inserts as $value) {
            //Work out if the field actually exists in this survey
            $fieldexists = '';
            if (isset($fieldmap[$value])) {
                $fieldexists = $fieldmap[$value];
            }
            //Iterate through possible responses
            if (isset($_SESSION[$value]) && !empty($fieldexists)) {
                //Only create column name and data entry if there is actually data!
                $colnames[] = $value;
                //If deletenonvalues is ON, delete any values that shouldn't exist
                if ($deletenonvalues == 1 && !checkconfield($value)) {
                    $values[] = 'NULL';
                    $colnames_hidden[] = $value;
                } elseif ($_SESSION[$value] == '' && $fieldexists['type'] == 'D' || $_SESSION[$value] == '' && $fieldexists['type'] == 'K' || $_SESSION[$value] == '' && $fieldexists['type'] == 'N') {
                    // most databases do not allow to insert an empty value into a datefield,
                    // therefore if no date was chosen in a date question the insert value has to be NULL
                    $values[] = 'NULL';
                } else {
                    // Empty the 'Other' field if a value other than '-oth-' was set for the main field (prevent invalid other values being saved - for example if Javascript fails to hide the 'Other' input field)
                    if ($fieldexists['type'] == '!' && $fieldmap[$value]['aid'] == 'other' && isset($_POST[substr($value, 0, strlen($value) - 5)]) && $_POST[substr($value, 0, strlen($value) - 5)] != '-oth-') {
                        $_SESSION[$value] = '';
                    } elseif ($fieldexists['type'] == 'N') {
                        $_SESSION[$value] = sanitize_float($_SESSION[$value]);
                    } elseif ($fieldexists['type'] == 'D' && is_array($postedfieldnames) && in_array($value, $postedfieldnames)) {
                        // convert the date to the right DB Format but only if it was posted
                        $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
                        $datetimeobj = new Date_Time_Converter($_SESSION[$value], $dateformatdatat['phpdate']);
                        $_SESSION[$value] = $datetimeobj->convert("Y-m-d");
                        $_SESSION[$value] = $connect->BindDate($_SESSION[$value]);
                    }
                    $values[] = $connect->qstr($_SESSION[$value], get_magic_quotes_gpc());
                }
            }
        }
        if ($thissurvey['datestamp'] == "Y") {
            $_SESSION['datestamp'] = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
        }
        // First compute the submitdate
        if ($thissurvey['private'] == "Y" && $thissurvey['datestamp'] == "N") {
            // In case of anonymous answers survey with no datestamp
            // then the the answer submutdate gets a conventional timestamp
            // 1st Jan 1980
            $mysubmitdate = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
        } else {
            $mysubmitdate = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust);
        }
        // CHECK TO SEE IF ROW ALREADY EXISTS
        // srid (=Survey Record ID ) is set when the there were already answers saved for that survey
        if (!isset($_SESSION['srid'])) {
            //Prepare row insertion
            if (!isset($colnames) || !is_array($colnames)) {
                echo submitfailed();
                exit;
            }
            // INSERT NEW ROW
            $query = "INSERT INTO " . db_quote_id($thissurvey['tablename']) . "\n" . "(" . implode(', ', array_map('db_quote_id', $colnames));
            $query .= "," . db_quote_id('lastpage');
            if ($thissurvey['datestamp'] == "Y") {
                $query .= "," . db_quote_id('datestamp');
                $query .= "," . db_quote_id('startdate');
            }
            if ($thissurvey['ipaddr'] == "Y") {
                $query .= "," . db_quote_id('ipaddr');
            }
            $query .= "," . db_quote_id('startlanguage');
            if ($thissurvey['refurl'] == "Y") {
                $query .= "," . db_quote_id('refurl');
            }
            if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                $query .= "," . db_quote_id('submitdate');
            }
            $query .= ") ";
            $query .= "VALUES (" . implode(", ", $values);
            $query .= "," . ($thisstep + 1);
            if ($thissurvey['datestamp'] == "Y") {
                $query .= ", '" . $_SESSION['datestamp'] . "'";
                $query .= ", '" . $_SESSION['datestamp'] . "'";
            }
            if ($thissurvey['ipaddr'] == "Y") {
                $query .= ", '" . $_SERVER['REMOTE_ADDR'] . "'";
            }
            $query .= ", '" . $_SESSION['s_lang'] . "'";
            if ($thissurvey['refurl'] == "Y") {
                $query .= ", '" . $_SESSION['refurl'] . "'";
            }
            if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                // is if a ALL-IN-ONE survey, we don't set the submit date before the data is validated
                $query .= ", " . $connect->DBDate($mysubmitdate);
            }
            $query .= ")";
        } else {
            // UPDATE EXISTING ROW
            // Updates only the MODIFIED fields posted on current page.
            if (isset($postedfieldnames) && $postedfieldnames) {
                $query = "UPDATE {$thissurvey['tablename']} SET ";
                $query .= " lastpage = '" . $thisstep . "',";
                if ($thissurvey['datestamp'] == "Y") {
                    $query .= " datestamp = '" . $_SESSION['datestamp'] . "',";
                }
                if ($thissurvey['ipaddr'] == "Y") {
                    $query .= " ipaddr = '" . $_SERVER['REMOTE_ADDR'] . "',";
                }
                // is if a ALL-IN-ONE survey, we don't set the submit date before the data is validated
                if ($bFinalizeThisAnswer === true && $thissurvey['format'] != "A") {
                    $query .= " submitdate = " . $connect->DBDate($mysubmitdate) . ", ";
                }
                // Resets fields hidden due to conditions
                if ($deletenonvalues == 1) {
                    $hiddenfields = array_unique(array_values($colnames_hidden));
                    foreach ($hiddenfields as $hiddenfield) {
                        //$fieldinfo = arraySearchByKey($hiddenfield, $fieldmap, "fieldname", 1);
                        //if ($fieldinfo['type']=='D' || $fieldinfo['type']=='N' || $fieldinfo['type']=='K')
                        //{
                        $query .= db_quote_id($hiddenfield) . " = NULL,";
                        //}
                        //else
                        //{
                        //	$query .= db_quote_id($hiddenfield)." = '',";
                        //}
                    }
                } else {
                    $hiddenfields = array();
                }
                $fields = $postedfieldnames;
                $fields = array_unique($fields);
                $fields = array_diff($fields, $hiddenfields);
                // Do not take fields that are hidden
                foreach ($fields as $field) {
                    if (!empty($field)) {
                        $fieldinfo = $fieldmap[$field];
                        if (!isset($_POST[$field])) {
                            $_POST[$field] = '';
                        }
                        //fixed numerical question fields. They have to be NULL instead of '' to avoid database errors
                        if ($_POST[$field] == '' && $fieldinfo['type'] == 'D' || $_POST[$field] == '' && $fieldinfo['type'] == 'N' || $_POST[$field] == '' && $fieldinfo['type'] == 'K') {
                            $query .= db_quote_id($field) . " = NULL,";
                        } else {
                            // Empty the 'Other' field if a value other than '-oth-' was set for the main field (prevent invalid other values being saved - for example if Javascript fails to hide the 'Other' input field)
                            if ($fieldinfo['type'] == '!' && $fieldmap[$field]['aid'] == 'other' && $_POST[substr($field, 0, strlen($field) - 5)] != '-oth-') {
                                $qfield = "''";
                            } elseif ($fieldinfo['type'] == 'N') {
                                $qfield = db_quoteall(sanitize_float($_POST[$field]));
                            } elseif ($fieldinfo['type'] == 'D') {
                                $dateformatdatat = getDateFormatData($thissurvey['surveyls_dateformat']);
                                $datetimeobj = new Date_Time_Converter($_POST[$field], $dateformatdatat['phpdate']);
                                $qfield = db_quoteall($connect->BindDate($datetimeobj->convert("Y-m-d")));
                            } else {
                                $qfield = db_quoteall($_POST[$field], true);
                            }
                            $query .= db_quote_id($field) . " = " . $qfield . ",";
                        }
                    }
                }
                $query .= "WHERE id=" . $_SESSION['srid'];
                $query = str_replace(",WHERE", " WHERE", $query);
                // remove comma before WHERE clause
            } else {
                $query = "";
                if ($bFinalizeThisAnswer === true) {
                    $query = "UPDATE {$thissurvey['tablename']} SET ";
                    $query .= " submitdate = " . $connect->DBDate($mysubmitdate);
                    $query .= " WHERE id=" . $_SESSION['srid'];
                }
            }
        }
        //DEBUG START
        //echo $query;
        //DEBUG END
        return $query;
    } else {
        sendcacheheaders();
        doHeader();
        foreach (file("{$thistpl}/startpage.pstpl") as $op) {
            echo templatereplace($op);
        }
        echo "<br /><center><font face='verdana' size='2'><font color='red'><strong>" . $clang->gT("Error") . "</strong></font><br /><br />\n";
        echo $clang->gT("Cannot submit results - there are none to submit.") . "<br /><br />\n";
        echo "<font size='1'>" . $clang->gT("This error can occur if you have already submitted your responses and pressed 'refresh' on your browser. In this case, your responses have already been saved.") . "<br /><br />" . $clang->gT("If you receive this message in the middle of completing a survey, you should choose '<- BACK' on your browser and then refresh/reload the previous page. While you will lose answers from the last page all your others will still exist. This problem can occur if the webserver is suffering from overload or excessive use. We apologise for this problem.") . "<br />\n";
        echo "</font></center><br /><br />";
        exit;
    }
}
 /**
  * Write values to database.
  * @param <type> $updatedValues
  * @param <boolean> $finished - true if the survey needs to be finalized
  */
 private function _UpdateValuesInDatabase($updatedValues, $finished = false, $setSubmitDate = false)
 {
     // Update these values in the database
     global $connect;
     //  TODO - now that using $this->updatedValues, may be able to remove local copies of it (unless needed by other sub-systems)
     $updatedValues = $this->updatedValues;
     if (!$this->surveyOptions['deletenonvalues']) {
         $nonNullValues = array();
         foreach ($updatedValues as $key => $value) {
             if (!is_null($value)) {
                 if (isset($value['value']) && !is_null($value['value'])) {
                     $nonNullValues[$key] = $value;
                 }
             }
         }
         $updatedValues = $nonNullValues;
     }
     $message = '';
     if ($this->surveyOptions['datestamp'] == true && $this->surveyOptions['anonymized'] == true) {
         // On anonymous datestamped surveys, set the datestamp to 1-1-1980
         $datestamp = date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, 1980));
     } else {
         // Otherwise, use the real date/time, it will only be saved when the table holds a
         // datestamp field
         $datestamp = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
     }
     $_SESSION['datestamp'] = $datestamp;
     if ($this->surveyOptions['active'] && !isset($_SESSION['srid'])) {
         // Create initial insert row for this record
         $sdata = array("datestamp" => $datestamp, "ipaddr" => $this->surveyOptions['ipaddr'] ? getIPAddress() : '', "startlanguage" => $this->surveyOptions['startlanguage'], "token" => $this->surveyOptions['token'], "refurl" => $this->surveyOptions['refurl'] ? getenv("HTTP_REFERER") : NULL, "startdate" => $datestamp);
         //One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated
         if ($connect->AutoExecute($this->surveyOptions['tablename'], $sdata, 'INSERT')) {
             $srid = $connect->Insert_ID($this->surveyOptions['tablename'], "id");
             $_SESSION['srid'] = $srid;
         } else {
             $message .= $this->gT("Unable to insert record into survey table: ") . $connect->ErrorMsg() . "<br/>";
             $_SESSION['flashmessage'] = $message;
             echo $message;
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             $tdata = array('id' => $srid, 'interviewtime' => 0);
             if ($connect->AutoExecute($this->surveyOptions['tablename_timings'], $tdata, 'INSERT')) {
                 $trid = $connect->Insert_ID($this->surveyOptions['tablename_timings'], "sid");
             } else {
                 $message .= $this->gT("Unable to insert record into timings table ") . $connect->ErrorMsg() . "<br/>";
                 $_SESSION['flashmessage'] = $message;
                 echo $message;
             }
         }
     }
     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[] = db_quote_id('lastpage') . "=" . db_quoteall($thisstep);
         if ($this->surveyOptions['datestamp'] && isset($_SESSION['datestamp'])) {
             $setter[] = db_quote_id('datestamp') . "=" . db_quoteall($_SESSION['datestamp']);
         }
         if ($this->surveyOptions['ipaddr']) {
             $setter[] = db_quote_id('ipaddr') . "=" . db_quoteall(getIPAddress());
         }
         foreach ($updatedValues as $key => $value) {
             if (!empty($key)) {
                 $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[] = db_quote_id($key) . "=NULL";
                 } else {
                     $setter[] = db_quote_id($key) . "=" . db_quoteall($val, true);
                 }
             }
         }
         $query .= implode(', ', $setter);
         $query .= " WHERE ID=";
         if (isset($_SESSION['srid']) && $this->surveyOptions['active']) {
             $query .= $_SESSION['srid'];
             if (!db_execute_assoc($query)) {
                 echo submitfailed($connect->ErrorMsg());
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= 'Error in SQL update: ' . $connect->ErrorMsg() . '<br/>';
                 }
             }
             // Save Timings if needed
             if ($this->surveyOptions['savetimings']) {
                 set_answer_time();
             }
             if ($finished) {
                 // Delete the save control record if successfully finalize the submission
                 $query = "DELETE FROM " . db_table_name("saved_control") . " where srid=" . $_SESSION['srid'] . ' and sid=' . $this->sid;
                 $connect->Execute($query);
                 // Checked
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= ';<br/>' . $query;
                 }
             } elseif ($this->surveyOptions['allowsave'] && isset($_SESSION['scid'])) {
                 $connect->Execute("UPDATE " . db_table_name("saved_control") . " SET saved_thisstep=" . db_quoteall($thisstep) . " where scid=" . $_SESSION['scid']);
                 // Checked
             }
             // Check quotas whenever results are saved
             $bQuotaMatched = false;
             $aQuotas = check_quota('return', $this->sid);
             if ($aQuotas !== false) {
                 if ($aQuotas != false) {
                     foreach ($aQuotas as $aQuota) {
                         if (isset($aQuota['status']) && $aQuota['status'] == 'matched') {
                             $bQuotaMatched = true;
                         }
                     }
                 }
             }
             if ($bQuotaMatched) {
                 check_quota('enforce', $this->sid);
                 // will create a page and quit.
             } else {
                 if ($finished) {
                     $sQuery = 'UPDATE ' . $this->surveyOptions['tablename'] . " SET " . db_quote_id('submitdate') . "=" . db_quoteall($datestamp) . " WHERE ID=" . $_SESSION['srid'];
                     $connect->Execute($sQuery);
                     // Checked
                 }
             }
         }
         if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
             $message .= $query;
         }
     }
     return $message;
 }
 /**
  * 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;
 }
 /**
  * Write values to database.
  * @param <type> $updatedValues
  * @param <boolean> $finished - true if the survey needs to be finalized
  */
 private function _UpdateValuesInDatabase($updatedValues, $finished = false)
 {
     // Update these values in the database
     global $connect;
     $message = '';
     $_SESSION['datestamp'] = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
     if ($this->surveyOptions['active'] && !isset($_SESSION['srid'])) {
         // Create initial insert row for this record
         $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $this->surveyOptions['timeadjust']);
         $sdata = array("datestamp" => $today, "ipaddr" => $this->surveyOptions['ipaddr'] && isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '', "startlanguage" => $this->surveyOptions['startlanguage'], "token" => $this->surveyOptions['token'], "datestamp" => $this->surveyOptions['datestamp'] ? $_SESSION['datestamp'] : NULL, "refurl" => $this->surveyOptions['refurl'] ? getenv("HTTP_REFERER") : NULL, "startdate" => $this->surveyOptions['datestamp'] ? $_SESSION['datestamp'] : date("Y-m-d H:i:s", 0));
         //One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated
         if ($connect->AutoExecute($this->surveyOptions['tablename'], $sdata, 'INSERT')) {
             $srid = $connect->Insert_ID($this->surveyOptions['tablename'], "id");
             $_SESSION['srid'] = $srid;
         } else {
             $message .= $this->gT("Unable to insert record into survey table: ") . $connect->ErrorMsg() . "<br/>";
             $_SESSION['flashmessage'] = $message;
             echo $message;
         }
         //Insert Row for Timings, if needed
         if ($this->surveyOptions['savetimings']) {
             $tdata = array('id' => $srid, 'interviewtime' => 0);
             if ($connect->AutoExecute($this->surveyOptions['tablename_timings'], $tdata, 'INSERT')) {
                 $trid = $connect->Insert_ID($this->surveyOptions['tablename_timings'], "sid");
             } else {
                 $message .= $this->gT("Unable to insert record into timings table ") . $connect->ErrorMsg() . "<br/>";
                 $_SESSION['flashmessage'] = $message;
                 echo $message;
             }
         }
     }
     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[] = db_quote_id('lastpage') . "=" . db_quoteall($thisstep);
         if ($this->surveyOptions['datestamp'] && isset($_SESSION['datestamp'])) {
             $setter[] = db_quote_id('datestamp') . "=" . db_quoteall($_SESSION['datestamp']);
         }
         if ($this->surveyOptions['ipaddr'] && isset($_SERVER['REMOTE_ADDR'])) {
             $setter[] = db_quote_id('ipaddr') . "=" . db_quoteall($_SERVER['REMOTE_ADDR']);
         }
         if ($finished) {
             $setter[] = db_quote_id('submitdate') . "=" . db_quoteall($_SESSION['datestamp']);
         }
         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 '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[] = db_quote_id($key) . "=NULL";
             } else {
                 $setter[] = db_quote_id($key) . "=" . db_quoteall($val);
             }
         }
         $query .= implode(', ', $setter);
         $query .= " WHERE ID=";
         if (isset($_SESSION['srid']) && $this->surveyOptions['active']) {
             $query .= $_SESSION['srid'];
             if (!db_execute_assoc($query)) {
                 echo submitfailed($connect->ErrorMsg());
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= 'Error in SQL update: ' . $connect->ErrorMsg() . '<br/>';
                 }
             }
             // Save Timings if needed
             if ($this->surveyOptions['savetimings']) {
                 set_answer_time();
             }
             if ($finished) {
                 // Delete the save control record if successfully finalize the submission
                 $query = "DELETE FROM " . db_table_name("saved_control") . " where srid=" . $_SESSION['srid'] . ' and sid=' . $this->sid;
                 $connect->Execute($query);
                 // Checked
                 if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                     $message .= ';<br/>' . $query;
                 }
                 // Check Quotas
                 $bQuotaMatched = false;
                 $aQuotas = check_quota('return', $this->sid);
                 if ($aQuotas !== false) {
                     if ($aQuotas != false) {
                         foreach ($aQuotas as $aQuota) {
                             if (isset($aQuota['status']) && $aQuota['status'] == 'matched') {
                                 $bQuotaMatched = true;
                             }
                         }
                     }
                 }
                 if ($bQuotaMatched) {
                     check_quota('enforce', $this->sid);
                     // will create a page and quit.
                 }
             } else {
                 if ($this->surveyOptions['allowsave'] && isset($_SESSION['scid'])) {
                     $connect->Execute("UPDATE " . db_table_name("saved_control") . " SET saved_thisstep=" . db_quoteall($thisstep) . " where scid=" . $_SESSION['scid']);
                     // Checked
                 }
             }
         }
         if (($this->debugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
             $message .= $query;
         }
     }
     return $message;
 }