function spss_export_data($na = null) { global $length_data; // Build array that has to be returned $fields = spss_fieldmap(); //Now get the query string with all fields to export $query = spss_getquery(); $result = db_execute_num($query) or safe_die("Couldn't get results<br />{$query}<br />" . $connect->ErrorMsg()); //Checked $num_fields = $result->FieldCount(); //This shouldn't occur, but just to be safe: if (count($fields) != $num_fields) { safe_die("Database inconsistency error"); } while (!$result->EOF) { $row = $result->GetRowAssoc(true); //Get assoc array, use uppercase reset($fields); //Jump to the first element in the field array $i = 1; foreach ($fields as $field) { $fieldno = strtoupper($field['sql_name']); if ($field['SPSStype'] == 'DATETIME23.2') { #convert mysql datestamp (yyyy-mm-dd hh:mm:ss) to SPSS datetime (dd-mmm-yyyy hh:mm:ss) format if (isset($row[$fieldno])) { list($year, $month, $day, $hour, $minute, $second) = preg_split('([^0-9])', $row[$fieldno]); if ($year != '' && (int) $year >= 1970) { echo "'" . date('d-m-Y H:i:s', mktime($hour, $minute, $second, $month, $day, $year)) . "'"; } else { echo $na; } } else { echo $na; } } else { if ($field['LStype'] == 'Y') { if ($row[$fieldno] == 'Y') { echo "'1'"; } else { if ($row[$fieldno] == 'N') { echo "'2'"; } else { echo $na; } } } else { if ($field['LStype'] == 'G') { if ($row[$fieldno] == 'F') { echo "'1'"; } else { if ($row[$fieldno] == 'M') { echo "'2'"; } else { echo $na; } } } else { if ($field['LStype'] == 'C') { if ($row[$fieldno] == 'Y') { echo "'1'"; } else { if ($row[$fieldno] == 'N') { echo "'2'"; } else { if ($row[$fieldno] == 'U') { echo "'3'"; } else { echo $na; } } } } else { if ($field['LStype'] == 'E') { if ($row[$fieldno] == 'I') { echo "'1'"; } else { if ($row[$fieldno] == 'S') { echo "'2'"; } else { if ($row[$fieldno] == 'D') { echo "'3'"; } else { echo $na; } } } } elseif (($field['LStype'] == 'P' || $field['LStype'] == 'M') && (substr($field['code'], -7) != 'comment' && substr($field['code'], -5) != 'other')) { if ($row[$fieldno] == 'Y') { echo "'1'"; } else { echo "'0'"; } } elseif (!$field['hide']) { $strTmp = mb_substr(strip_tags_full($row[$fieldno]), 0, $length_data); if (trim($strTmp) != '') { $strTemp = str_replace(array("'", "\n", "\r"), array("''", ' ', ' '), trim($strTmp)); /* * Temp quick fix for replacing decimal dots with comma's if (my_is_numeric($strTemp)) { $strTemp = str_replace('.',',',$strTemp); } */ echo "'{$strTemp}'"; } else { echo $na; } } } } } } if ($i < $num_fields && !$field['hide']) { echo ','; } $i++; } echo "\n"; $result->MoveNext(); } }
/** * * Enter description here... * @param $surveyid * @param $sMod * @param $newGroup * @return unknown_type */ function importQuestion($surveyid, $sMod, $newGroup = false) { global $connect; global $dbprefix; $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; include "lsrc.config.php"; $newsid = $surveyid; $this->debugLsrc("wir sind in " . __FUNCTION__ . " Line " . __LINE__ . ", START OK {$dbprefix} "); //$getGidSql = "SELECT gid FROM {$dbprefix} "; $getGidSql = "SELECT gid\r\n\t FROM {$dbprefix}groups \r\n\t WHERE sid=" . $surveyid . " AND language='" . GetBaseLanguageFromSurveyID($surveyid) . "'\r\n\t ORDER BY gid desc "; $getGidRs = db_execute_num($getGidSql); $gidRow = $getGidRs->FetchRow(); $gid = $gidRow[0]; if ($gid == '') { $this->debugLsrc("No Group for importing the question, available!"); return "No Group for importing the question, available! Import failed."; } if ($newGroup === true) { ++$gid; } $the_full_file_path = $queDir . $sMod . ".csv"; $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK {$the_full_file_path} "); $handle = fopen($the_full_file_path, "r"); while (!feof($handle)) { $buffer = fgets($handle, 10240); //To allow for very long survey welcomes (up to 10k) $bigarray[] = $buffer; } fclose($handle); // Now we try to determine the dataformat of the survey file. if (substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP" && substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/") { $importversion = 100; // version 1.0 file } elseif (substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP" && substr($bigarray[4], 0, 37) == "# http://phpsurveyor.sourceforge.net/") { $importversion = 99; // Version 0.99 file or older - carries a different URL } elseif (substr($bigarray[0], 0, 26) == "# LimeSurvey Question Dump" || substr($bigarray[0], 0, 27) == "# PHPSurveyor Question Dump") { // Wow.. this seems to be a >1.0 version file - these files carry the version information to read in line two $importversion = substr($bigarray[1], 12, 3); } else { // $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n"; // $importquestion .= ("This file is not a LimeSurvey question file. Import failed.")."\n"; // $importquestion .= "</font></td></tr></table>\n"; // $importquestion .= "</body>\n</html>\n"; // unlink($the_full_file_path); return "This is not a Limesurvey question file. Import failed"; } // if ($importversion != $dbversionnumber) // { //// $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n"; //// $importquestion .= ("Sorry, importing questions is limited to the same version. Import failed.")."\n"; //// $importquestion .= "</font></td></tr></table>\n"; //// $importquestion .= "</body>\n</html>\n"; //// unlink($the_full_file_path); // return; // } $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); for ($i = 0; $i < 9; $i++) { unset($bigarray[$i]); } $bigarray = array_values($bigarray); $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //QUESTIONS if (array_search("# ANSWERS TABLE\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); } elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $questionarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //ANSWERS if (array_search("# LABELSETS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); } elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]); } unset($bigarray[$i]); } $bigarray = array_values($bigarray); $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //LABELSETS if (array_search("# LABELS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\n", $bigarray); } elseif (array_search("# LABELS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $labelsetsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //LABELS if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); } elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $labelsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //Question_attributes if (!isset($noconditions) || $noconditions != "Y") { $stoppoint = count($bigarray); for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 1) { $question_attributesarray[] = $bigarray[$i]; } unset($bigarray[$i]); } } $bigarray = array_values($bigarray); if (isset($questionarray)) { $countquestions = count($questionarray) - 1; } else { $countquestions = 0; } if (isset($answerarray)) { $answerfieldnames = convertCSVRowToArray($answerarray[0], ',', '"'); unset($answerarray[0]); $countanswers = count($answerarray); } else { $countanswers = 0; } if (isset($labelsetsarray)) { $countlabelsets = count($labelsetsarray) - 1; } else { $countlabelsets = 0; } if (isset($labelsarray)) { $countlabels = count($labelsarray) - 1; } else { $countlabels = 0; } if (isset($question_attributesarray)) { $countquestion_attributes = count($question_attributesarray) - 1; } else { $countquestion_attributes = 0; } $languagesSupported = array(); // this array will keep all the languages supported for the survey // Let's check that imported objects support at least the survey's baselang $langcode = GetBaseLanguageFromSurveyID($surveyid); $languagesSupported[$langcode] = 1; // adds the base language to the list of supported languages $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); if ($countquestions > 0) { $questionfieldnames = convertCSVRowToArray($questionarray[0], ',', '"'); $langfieldnum = array_search("language", $questionfieldnames); $qidfieldnum = array_search("qid", $questionfieldnames); $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray, array($qidfieldnum), $langfieldnum, $langcode, true); if (!$questionssupportbaselang) { // $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n" // .("You can't import a question which doesn't support the current survey's base language")."\n" // ."</td></tr></table>\n"; // unlink($the_full_file_path); return "You can't import a question which doesn't support the current survey's base language"; } } $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); foreach (GetAdditionalLanguagesFromSurveyID($surveyid) as $language) { $languagesSupported[$language] = 1; } // Let's assume that if the questions do support tye baselang // Then the answers do support it as well. // ==> So the following section is commented for now //if ($countanswers > 0) //{ // $langfieldnum = array_search("language", $answerfieldnames); // $answercodefilednum1 = array_search("qid", $answerfieldnames); // $answercodefilednum2 = array_search("code", $answerfieldnames); // $answercodekeysarr = Array($answercodefilednum1,$answercodefilednum2); // $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray,$answercodekeysarr,$langfieldnum,$langcode); // if (!$answerssupportbaselang) // { // $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n" // .("You can't import answers which don't support current survey's base language")."\n" // ."</td></tr></table>\n"; // return; // } // //} $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); if ($countlabelsets > 0) { $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0], ',', '"'); $langfieldnum = array_search("languages", $labelsetfieldname); $lidfilednum = array_search("lid", $labelsetfieldname); $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray, array($lidfilednum), $langfieldnum, $langcode, true); if (!$labelsetssupportbaselang) { // $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n" // .("You can't import label sets which don't support the current survey's base language")."\n" // ."</td></tr></table>\n"; // unlink($the_full_file_path); return "You can't import label sets which don't support the current survey's base language"; } } // I assume that if a labelset supports the survey's baselang, // then it's labels do support it as well // GET SURVEY AND GROUP DETAILS //$surveyid=$postsid; //$gid=$postgid; $newsid = $surveyid; $newgid = $gid; $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS if (isset($labelsetsarray) && $labelsetsarray) { $csarray = buildLabelSetCheckSumArray(); // build checksums over all existing labelsets $count = 0; $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); foreach ($labelsetsarray as $lsa) { $fieldorders = convertCSVRowToArray($labelsetsarray[0], ',', '"'); $fieldcontents = convertCSVRowToArray($lsa, ',', '"'); if ($count == 0) { $count++; continue; } $labelsetrowdata = array_combine($fieldorders, $fieldcontents); // Save old labelid $oldlid = $labelsetrowdata['lid']; // set the new language unset($labelsetrowdata['lid']); $newvalues = array_values($labelsetrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $lsainsert = "INSERT INTO {$dbprefix}labelsets (" . implode(',', array_keys($labelsetrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; //handle db prefix $lsiresult = $connect->Execute($lsainsert); // Get the new insert id for the labels inside this labelset $newlid = $connect->Insert_ID("{$dbprefix}labelsets", "lid"); if ($labelsarray) { $count = 0; foreach ($labelsarray as $la) { $lfieldorders = convertCSVRowToArray($labelsarray[0], ',', '"'); $lfieldcontents = convertCSVRowToArray($la, ',', '"'); if ($count == 0) { $count++; continue; } // Combine into one array with keys and values since its easier to handle $labelrowdata = array_combine($lfieldorders, $lfieldcontents); $labellid = $labelrowdata['lid']; if ($labellid == $oldlid) { $labelrowdata['lid'] = $newlid; // translate internal links $labelrowdata['title'] = translink('label', $oldlid, $newlid, $labelrowdata['title']); $newvalues = array_values($labelrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $lainsert = "INSERT INTO {$dbprefix}labels (" . implode(',', array_keys($labelrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; //handle db prefix $liresult = $connect->Execute($lainsert); } } } //CHECK FOR DUPLICATE LABELSETS $thisset = ""; $query2 = "SELECT code, title, sortorder, language\r\n\t\t FROM {$dbprefix}labels\r\n\t\t WHERE lid=" . $newlid . "\r\n\t\t ORDER BY language, sortorder, code"; $result2 = db_execute_num($query2) or $this->debugLsrc("Died querying labelset {$lid}{$query2}" . $connect->ErrorMsg()); while ($row2 = $result2->FetchRow()) { $thisset .= implode('.', $row2); } // while $newcs = dechex(crc32($thisset) * 1); unset($lsmatch); if (isset($csarray)) { foreach ($csarray as $key => $val) { if ($val == $newcs) { $lsmatch = $key; } } } if (isset($lsmatch)) { //There is a matching labelset. So, we will delete this one and refer //to the matched one. $query = "DELETE FROM {$dbprefix}labels WHERE lid={$newlid}"; $result = $connect->Execute($query) or $this->debugLsrc("Couldn't delete labels{$query}" . $connect->ErrorMsg()); $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}"; $result = $connect->Execute($query) or $this->debugLsrc("Couldn't delete labelset{$query}" . $connect->ErrorMsg()); $newlid = $lsmatch; } else { //There isn't a matching labelset, add this checksum to the $csarray array $csarray[$newlid] = $newcs; } //END CHECK FOR DUPLICATES $labelreplacements[] = array($oldlid, $newlid); } } $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); // QUESTIONS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT! if (isset($questionarray) && $questionarray) { $qafieldorders = convertCSVRowToArray($questionarray[0], ',', '"'); unset($questionarray[0]); //Assuming we will only import one question at a time we will now find out the maximum question order in this group //and save it for later $qmaxqo = "SELECT MAX(question_order) AS maxqo FROM " . db_table_name('questions') . " WHERE sid={$newsid} AND gid={$newgid}"; $qres = db_execute_assoc($qmaxqo) or $this->debugLsrc("Error: " . ": Failed to find out maximum question order value\n{$qmaxqo}\n" . $connect->ErrorMsg()); $qrow = $qres->FetchRow(); $newquestionorder = $qrow['maxqo'] + 1; $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); foreach ($questionarray as $qa) { $qacfieldcontents = convertCSVRowToArray($qa, ',', '"'); $newfieldcontents = $qacfieldcontents; $questionrowdata = array_combine($qafieldorders, $qacfieldcontents); if (isset($languagesSupported[$questionrowdata["language"]])) { $oldqid = $questionrowdata['qid']; $oldsid = $questionrowdata['sid']; $oldgid = $questionrowdata['gid']; // Remove qid field if there is no newqid; and set it to newqid if it's set if (!isset($newqid)) { unset($questionrowdata['qid']); } else { $questionrowdata['qid'] = $newqid; } $questionrowdata["sid"] = $newsid; $questionrowdata["gid"] = $newgid; $questionrowdata["question_order"] = $newquestionorder; $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); // Now we will fix up the label id $type = $questionrowdata["type"]; //Get the type if ($type == "F" || $type == "H" || $type == "1" || $type == ":" || $type == ";") { //IF this is a flexible label array, update the lid entry $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); if (isset($labelreplacements)) { foreach ($labelreplacements as $lrp) { if ($lrp[0] == $questionrowdata["lid"]) { $questionrowdata["lid"] = $lrp[1]; } if ($lrp[0] == $questionrowdata["lid1"]) { $questionrowdata["lid1"] = $lrp[1]; } } } } $other = $questionrowdata["other"]; //Get 'other' field value $oldlid = $questionrowdata["lid"]; $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata); // translate internal links $questionrowdata['title'] = translink('survey', $oldsid, $newsid, $questionrowdata['title']); $questionrowdata['question'] = translink('survey', $oldsid, $newsid, $questionrowdata['question']); $questionrowdata['help'] = translink('survey', $oldsid, $newsid, $questionrowdata['help']); $newvalues = array_values($questionrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $qinsert = "INSERT INTO {$dbprefix}questions (" . implode(',', array_keys($questionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $qres = $connect->Execute($qinsert) or $this->debugLsrc("Error: " . ": Failed to insert question\n{$qinsert}\n" . $connect->ErrorMsg()); $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); // set the newqid only if is not set if (!isset($newqid)) { $newqid = $connect->Insert_ID("{$dbprefix}questions", "qid"); } } } $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); //NOW DO ANSWERS FOR THIS QID - Is called just once and only if there was a question if (isset($answerarray) && $answerarray) { foreach ($answerarray as $aa) { $answerfieldcontents = convertCSVRowToArray($aa, ',', '"'); $answerrowdata = array_combine($answerfieldnames, $answerfieldcontents); if ($answerrowdata === false) { $importquestion .= '' . "Faulty line in import - fields and data don't match" . ":" . implode(',', $answerfieldcontents); } if (isset($languagesSupported[$answerrowdata["language"]])) { $code = $answerrowdata["code"]; $thisqid = $answerrowdata["qid"]; $answerrowdata["qid"] = $newqid; // translate internal links $answerrowdata['answer'] = translink('survey', $oldsid, $newsid, $answerrowdata['answer']); $newvalues = array_values($answerrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $ainsert = "INSERT INTO {$dbprefix}answers (" . implode(',', array_keys($answerrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $ares = $connect->Execute($ainsert) or $this->debugLsrc("Error: " . ": Failed to insert answer\n{$ainsert}\n" . $connect->ErrorMsg()); } } } $this->debugLsrc("wir sind in " . __FILE__ . " - " . __FUNCTION__ . " Line " . __LINE__ . ", OK "); // Finally the question attributes - Is called just once and only if there was a question if (isset($question_attributesarray) && $question_attributesarray) { //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES $fieldorders = convertCSVRowToArray($question_attributesarray[0], ',', '"'); unset($question_attributesarray[0]); foreach ($question_attributesarray as $qar) { $fieldcontents = convertCSVRowToArray($qar, ',', '"'); $qarowdata = array_combine($fieldorders, $fieldcontents); $qarowdata["qid"] = $newqid; unset($qarowdata["qaid"]); $newvalues = array_values($qarowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $qainsert = "INSERT INTO {$dbprefix}question_attributes (" . implode(',', array_keys($qarowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $result = $connect->Execute($qainsert) or $this->debugLsrc("Couldn't insert question_attribute{$qainsert}" . $connect->ErrorMsg()); } } } $this->debugLsrc("wir sind in - " . __FUNCTION__ . " Line " . __LINE__ . ", FERTIG "); // CONDITIONS is DONE return array('gid' => $newgid, 'qid' => $newqid); //return $newgid; }
/** * Generates statistics * * @param int $surveyid The survey id * @param mixed $allfields * @param mixed $q2show * @param mixed $usegraph * @param string $outputType Optional - Can be xls, html or pdf - Defaults to pdf * @param string $pdfOutput Sets the target for the PDF output: DD=File download , F=Save file to local disk * @param string $statlangcode Lamguage for statistics * @param mixed $browse Show browse buttons * @return buffer */ function generate_statistics($surveyid, $allfields, $q2show='all', $usegraph=0, $outputType='pdf', $pdfOutput='I',$statlangcode=null, $browse = true) { //$allfields =""; global $connect, $dbprefix, $clang, $rooturl, $rootdir, $homedir, $homeurl, $tempdir, $tempurl, $scriptname, $imagedir, $chartfontfile, $chartfontsize, $admintheme, $pdfdefaultfont, $pdffontsize; $fieldmap=createFieldMap($surveyid, "full"); if (is_null($statlangcode)) { $statlang=$clang; } else { $statlang = new limesurvey_lang($statlangcode); } /* * this variable is used in the function shortencode() which cuts off a question/answer title * after $maxchars and shows the rest as tooltip (in html mode) */ $maxchars = 13; //we collect all the html-output within this variable $statisticsoutput =''; /** * $outputType: html || pdf || */ /** * get/set Survey Details */ //no survey ID? -> come and get one if (!isset($surveyid)) {$surveyid=returnglobal('sid');} //Get an array of codes of all available languages in this survey $surveylanguagecodes = GetAdditionalLanguagesFromSurveyID($surveyid); $surveylanguagecodes[] = GetBaseLanguageFromSurveyID($surveyid); // Set language for questions and answers to base language of this survey $language=$statlangcode; if ($usegraph==1) { //for creating graphs we need some more scripts which are included here require_once(dirname(__FILE__).'/../classes/pchart/pchart/pChart.class'); require_once(dirname(__FILE__).'/../classes/pchart/pchart/pData.class'); require_once(dirname(__FILE__).'/../classes/pchart/pchart/pCache.class'); $MyCache = new pCache($tempdir.'/'); //pick the best font file if font setting is 'auto' if ($chartfontfile=='auto') { $chartfontfile='vera.ttf'; if ( $language=='ar') { $chartfontfile='KacstOffice.ttf'; } elseif ($language=='fa' ) { $chartfontfile='KacstFarsi.ttf'; } } } if($q2show=='all' ) { $summarySql=" SELECT gid, parent_qid, qid, type " ." FROM {$dbprefix}questions WHERE parent_qid=0" ." AND sid=$surveyid "; $summaryRs = db_execute_assoc($summarySql); foreach($summaryRs as $field) { $myField = $surveyid."X".$field['gid']."X".$field['qid']; // Multiple choice get special treatment if ($field['type'] == "M") {$myField = "M$myField";} if ($field['type'] == "P") {$myField = "P$myField";} //numerical input will get special treatment (arihtmetic mean, standard derivation, ...) if ($field['type'] == "N") {$myField = "N$myField";} if ($field['type'] == "|") {$myField = "|$myField";} if ($field['type'] == "Q") {$myField = "Q$myField";} // textfields get special treatment if ($field['type'] == "S" || $field['type'] == "T" || $field['type'] == "U"){$myField = "T$myField";} //statistics for Date questions are not implemented yet. if ($field['type'] == "D") {$myField = "D$myField";} if ($field['type'] == "F" || $field['type'] == "H") { //Get answers. We always use the answer code because the label might be too long elsewise $query = "SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='".$field['qid']."' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer"; $result = db_execute_num($query) or safe_die ("Couldn't get answers!<br />$query<br />".$connect->ErrorMsg()); $counter2=0; //check all the answers while ($row=$result->FetchRow()) { $myField = "$myField{$row[0]}"; } //$myField = "{$surveyid}X{$flt[1]}X{$flt[0]}{$row[0]}[]"; } if($q2show=='all') $summary[]=$myField; //$allfields[]=$myField; } } else { // This gets all the 'to be shown questions' from the POST and puts these into an array if (!is_array($q2show)) $summary=returnglobal('summary'); else $summary = $q2show; //print_r($_POST); //if $summary isn't an array we create one if (isset($summary) && !is_array($summary)) { $summary = explode("+", $summary); } } /* Some variable depend on output type, actually : only line feed */ switch($outputType) { case 'xls': $linefeed = "\n"; break; case 'pdf': $linefeed = "\n"; break; case 'html': $linefeed = "<br />\n"; break; default: break; } /** * pdf Config */ if($outputType=='pdf') { require_once('classes/tcpdf/config/lang/eng.php'); global $l; $l['w_page'] = $statlang->gT("Page",'unescaped'); require_once('classes/tcpdf/mypdf.php'); // create new PDF document $pdf = new MyPDF(); $pdf->SetFont($pdfdefaultfont,'',$pdffontsize); $surveyInfo = getSurveyInfo($surveyid,$language); // set document information $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('LimeSurvey'); $pdf->SetTitle('Statistic survey '.$surveyid); $pdf->SetSubject($surveyInfo['surveyls_title']); $pdf->SetKeywords('LimeSurvey, Statistics, Survey '.$surveyid.''); $pdf->SetDisplayMode('fullpage', 'two'); // set header and footer fonts $pdf->setHeaderFont(Array($pdfdefaultfont, '', PDF_FONT_SIZE_MAIN)); $pdf->setFooterFont(Array($pdfdefaultfont, '', PDF_FONT_SIZE_DATA)); // set default header data // the path looks awkward - did not find a better solution to set the image path? $pdf->SetHeaderData("statistics.png", 10, $statlang->gT("Quick statistics",'unescaped') , $statlang->gT("Survey")." ".$surveyid." '".FlattenText($surveyInfo['surveyls_title'],true,'UTF-8')."'"); // set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); //set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); //set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); //set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set some language-dependent strings $pdf->setLanguageArray($l); } if($outputType=='xls') { /** * Initiate the Spreadsheet_Excel_Writer */ include_once(dirname(__FILE__)."/classes/pear/Spreadsheet/Excel/Writer.php"); if($pdfOutput=='F') $workbook = new Spreadsheet_Excel_Writer($tempdir.'/statistic-survey'.$surveyid.'.xls'); else $workbook = new Spreadsheet_Excel_Writer(); $workbook->setVersion(8); // Inform the module that our data will arrive as UTF-8. // Set the temporary directory to avoid PHP error messages due to open_basedir restrictions and calls to tempnam("", ...) if (!empty($tempdir)) { $workbook->setTempDir($tempdir); } if ($pdfOutput!='F') $workbook->send('statistic-survey'.$surveyid.'.xls'); // Creating the first worksheet $sheet =& $workbook->addWorksheet(utf8_decode('results-survey'.$surveyid)); $sheet->setInputEncoding('utf-8'); $sheet->setColumn(0,20,20); $separator="~|"; } /** * Start generating */ // creates array of post variable names for (reset($_POST); $key=key($_POST); next($_POST)) { $postvars[]=$key;} $aQuestionMap=array(); foreach ($fieldmap as $field) { if(isset($field['qid']) && $field['qid']!='') $aQuestionMap[]=$field['sid'].'X'.$field['gid'].'X'.$field['qid']; } /* * Iterate through postvars to create "nice" data for SQL later. * * Remember there might be some filters applied which have to be put into an SQL statement */ if(isset($postvars)) foreach ($postvars as $pv) { //Only do this if there is actually a value for the $pv if (in_array($pv, $allfields) || in_array(substr($pv,1),$aQuestionMap) || in_array($pv,$aQuestionMap) || (($pv[0]=='D' || $pv[0]=='N' || $pv[0]=='K') && in_array(substr($pv,1,strlen($pv)-2),$aQuestionMap))) { $firstletter=substr($pv,0,1); /* * these question types WON'T be handled here: * M = Multiple choice * T - Long Free Text * Q - Multiple Short Text * D - Date * N - Numerical Input * | - File Upload * K - Multiple Numerical Input */ if ($pv != "sid" && $pv != "display" && $firstletter != "M" && $firstletter != "P" && $firstletter != "T" && $firstletter != "Q" && $firstletter != "D" && $firstletter != "N" && $firstletter != "K" && $firstletter != "|" && $pv != "summary" && substr($pv, 0, 2) != "id" && substr($pv, 0, 9) != "datestamp") //pull out just the fieldnames { //put together some SQL here $thisquestion = db_quote_id($pv)." IN ("; foreach ($_POST[$pv] as $condition) { $thisquestion .= "'$condition', "; } $thisquestion = substr($thisquestion, 0, -2) . ")"; //we collect all the to be selected data in this array $selects[]=$thisquestion; } //M - Multiple choice //P - Multiple choice with comments elseif ($firstletter == "M" || $firstletter == "P") { $mselects=array(); //create a list out of the $pv array list($lsid, $lgid, $lqid) = explode("X", $pv); $aquery="SELECT title FROM ".db_table_name("questions")." WHERE parent_qid=$lqid AND language='{$language}' and scale_id=0 ORDER BY question_order"; $aresult=db_execute_num($aquery) or safe_die ("Couldn't get subquestions<br />$aquery<br />".$connect->ErrorMsg()); // go through every possible answer while ($arow=$aresult->FetchRow()) { // only add condition if answer has been chosen if (in_array($arow[0], $_POST[$pv])) { $mselects[]=db_quote_id(substr($pv, 1, strlen($pv)).$arow[0])." = 'Y'"; } } if ($mselects) { $thismulti=implode(" OR ", $mselects); $selects[]="($thismulti)"; $mselects = ""; } } //N - Numerical Input //K - Multiple Numerical Input elseif ($firstletter == "N" || $firstletter == "K") { //value greater than if (substr($pv, strlen($pv)-1, 1) == "G" && $_POST[$pv] != "") { $selects[]=db_quote_id(substr($pv, 1, -1))." > ".sanitize_int($_POST[$pv]); } //value less than if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "") { $selects[]=db_quote_id(substr($pv, 1, -1))." < ".sanitize_int($_POST[$pv]); } } //| - File Upload Question Type else if ($firstletter == "|") { // no. of files greater than if (substr($pv, strlen($pv)-1, 1) == "G" && $_POST[$pv] != "") $selects[]=db_quote_id(substr($pv, 1, -1)."_filecount")." > ".sanitize_int($_POST[$pv]); // no. of files less than if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "") $selects[]=db_quote_id(substr($pv, 1, -1)."_filecount")." < ".sanitize_int($_POST[$pv]); } //"id" is a built in field, the unique database id key of each response row elseif (substr($pv, 0, 2) == "id") { if (substr($pv, strlen($pv)-1, 1) == "G" && $_POST[$pv] != "") { $selects[]=db_quote_id(substr($pv, 0, -1))." > '".$_POST[$pv]."'"; } if (substr($pv, strlen($pv)-1, 1) == "L" && $_POST[$pv] != "") { $selects[]=db_quote_id(substr($pv, 0, -1))." < '".$_POST[$pv]."'"; } } //T - Long Free Text //Q - Multiple Short Text elseif (($firstletter == "T" || $firstletter == "Q" ) && $_POST[$pv] != "") { $selectSubs = array(); //We intepret and * and % as wildcard matches, and use ' OR ' and , as the seperators $pvParts = explode(",",str_replace('*','%', str_replace(' OR ',',',$_POST[$pv]))); if(is_array($pvParts) AND count($pvParts)){ foreach($pvParts AS $pvPart){ $selectSubs[]=db_quote_id(substr($pv, 1, strlen($pv)))." LIKE '".trim($pvPart)."'"; } if(count($selectSubs)){ $selects[] = ' ('.implode(' OR ',$selectSubs).') '; } } } //D - Date elseif ($firstletter == "D" && $_POST[$pv] != "") { //Date equals if (substr($pv, -1, 1) == "=") { $selects[]=db_quote_id(substr($pv, 1, strlen($pv)-2))." = '".$_POST[$pv]."'"; } else { //date less than if (substr($pv, -1, 1) == "<") { $selects[]= db_quote_id(substr($pv, 1, strlen($pv)-2)) . " >= '".$_POST[$pv]."'"; } //date greater than if (substr($pv, -1, 1) == ">") { $selects[]= db_quote_id(substr($pv, 1, strlen($pv)-2)) . " <= '".$_POST[$pv]."'"; } } } //check for datestamp of given answer elseif (substr($pv, 0, 9) == "datestamp") { //timestamp equals $formatdata=getDateFormatData($_SESSION['dateformat']); if (substr($pv, -1, 1) == "E" && !empty($_POST[$pv])) { $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i'); $_POST[$pv]=$datetimeobj->convert("Y-m-d"); $selects[] = db_quote_id('datestamp')." >= '".$_POST[$pv]." 00:00:00' and ".db_quote_id('datestamp')." <= '".$_POST[$pv]." 23:59:59'"; } else { //timestamp less than if (substr($pv, -1, 1) == "L" && !empty($_POST[$pv])) { $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i'); $_POST[$pv]=$datetimeobj->convert("Y-m-d H:i:s"); $selects[]= db_quote_id('datestamp')." < '".$_POST[$pv]."'"; } //timestamp greater than if (substr($pv, -1, 1) == "G" && !empty($_POST[$pv])) { $datetimeobj = new Date_Time_Converter($_POST[$pv], $formatdata['phpdate'].' H:i'); $_POST[$pv]=$datetimeobj->convert("Y-m-d H:i:s"); $selects[]= db_quote_id('datestamp')." > '".$_POST[$pv]."'"; } } } } else { $statisticsoutput .= "<!-- $pv DOES NOT EXIST IN ARRAY -->"; } } //end foreach -> loop through filter options to create SQL //count number of answers $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid"); //if incompleted answers should be filtert submitdate has to be not null if (incompleteAnsFilterstate() == "inc") {$query .= " WHERE submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$query .= " WHERE submitdate is not null";} $result = db_execute_num($query) or safe_die ("Couldn't get total<br />$query<br />".$connect->ErrorMsg()); //$total = total number of answers while ($row=$result->FetchRow()) {$total=$row[0];} //are there any filters that have to be taken care of? if (isset($selects) && $selects) { //filter incomplete answers? if (incompleteAnsFilterstate() == "filter" || incompleteAnsFilterstate() == "inc") {$query .= " AND ";} else {$query .= " WHERE ";} //add filter criteria to SQL $query .= implode(" AND ", $selects); } //$_POST['sql'] is a post field that is sent from the statistics script to the export script in order // to export just those results filtered by this statistics script. It can also be passed to the statistics // script to filter from external scripts. elseif (!empty($_POST['sql']) && !isset($_POST['id='])) { $newsql=substr($_POST['sql'], strpos($_POST['sql'], "WHERE")+5, strlen($_POST['sql'])); //for debugging only //$query = $_POST['sql']; //filter incomplete answers? if (incompleteAnsFilterstate() == "inc") {$query .= " AND ".$newsql;} elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND ".$newsql;} else {$query .= " WHERE ".$newsql;} } //get me some data Scotty $result=db_execute_num($query) or safe_die("Couldn't get results<br />$query<br />".$connect->ErrorMsg()); //put all results into $results while ($row=$result->FetchRow()) {$results=$row[0];} if ($total) { $percent=sprintf("%01.2f", ($results/$total)*100); } switch($outputType) { case "xls": $xlsRow = 0; $sheet->write($xlsRow,0,$statlang->gT("Number of records in this query:")); $sheet->write($xlsRow,1,$results); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Total records in survey:")); $sheet->write($xlsRow,1,$total); if($total) { ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Percentage of total:")); $sheet->write($xlsRow,1,$percent."%"); } break; case 'pdf': // add summary to pdf $array = array(); //$array[] = array($statlang->gT("Results"),""); $array[] = array($statlang->gT("Number of records in this query:"), $results); $array[] = array($statlang->gT("Total records in survey:"), $total); if($total) $array[] = array($statlang->gT("Percentage of total:"), $percent."%"); $pdf->addPage('P','A4'); $pdf->Bookmark($pdf->delete_html($statlang->gT("Results")), 0, 0); $pdf->titleintopdf($statlang->gT("Results"),$statlang->gT("Survey")." ".$surveyid); $pdf->tableintopdf($array); $pdf->addPage('P','A4'); break; case 'html': $statisticsoutput .= "<br />\n<table class='statisticssummary' >\n" ."\t<thead><tr><th colspan='2'>".$statlang->gT("Results")."</th></tr></thead>\n" ."\t<tr><th >".$statlang->gT("Number of records in this query:").'</th>' ."<td>$results</td></tr>\n" ."\t<tr><th>".$statlang->gT("Total records in survey:").'</th>' ."<td>$total</td></tr>\n"; //only calculate percentage if $total is set if ($total) { $percent=sprintf("%01.2f", ($results/$total)*100); $statisticsoutput .= "\t<tr><th align='right'>".$statlang->gT("Percentage of total:").'</th>' ."<td>$percent%</td></tr>\n"; } $statisticsoutput .="</table>\n"; break; default: break; } //put everything from $selects array into a string connected by AND if (isset ($selects) && $selects) {$sql=implode(" AND ", $selects);} elseif (!empty($newsql)) {$sql = $newsql;} if (!isset($sql) || !$sql) {$sql="NULL";} //only continue if we have something to output if ($results > 0) { if($outputType=='html' && $browse === true) { //add a buttons to browse results $statisticsoutput .= "<form action='$scriptname?action=browse' method='post' target='_blank'>\n" ."\t\t<p>" ."\t\t\t<input type='submit' value='".$statlang->gT("Browse")."' />\n" ."\t\t\t<input type='hidden' name='sid' value='$surveyid' />\n" ."\t\t\t<input type='hidden' name='sql' value=\"$sql\" />\n" ."\t\t\t<input type='hidden' name='subaction' value='all' />\n" ."\t\t</p>" ."\t\t</form>\n"; } } //end if (results > 0) //Show Summary results if (isset($summary) && $summary) { //let's run through the survey $runthrough=$summary; //START Chop up fieldname and find matching questions //GET LIST OF LEGIT QIDs FOR TESTING LATER $lq = "SELECT DISTINCT qid FROM ".db_table_name("questions")." WHERE sid=$surveyid and parent_qid=0"; $lr = db_execute_assoc($lq); //loop through the IDs while ($lw = $lr->FetchRow()) { //this creates an array of question id's' $legitqids[] = $lw['qid']; } //loop through all selected questions foreach ($runthrough as $rt) { $firstletter = substr($rt, 0, 1); // 1. Get answers for question ############################################################## //M - Multiple choice, therefore multiple fields if ($firstletter == "M" || $firstletter == "P") { //get SGQ data list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3); //select details for this question $nquery = "SELECT title, type, question, parent_qid, other FROM ".db_table_name("questions")." WHERE language='{$language}' AND parent_qid=0 AND qid='$qqid'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=$nrow[0]; $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $qlid=$nrow[3]; $qother=$nrow[4]; } //1. Get list of answers $query="SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qqid' AND language='{$language}' and scale_id=0 ORDER BY question_order"; $result=db_execute_num($query) or safe_die("Couldn't get list of subquestions for multitype<br />$query<br />".$connect->ErrorMsg()); //loop through multiple answers while ($row=$result->FetchRow()) { $mfield=substr($rt, 1, strlen($rt))."$row[0]"; //create an array containing answer code, answer and fieldname(??) $alist[]=array("$row[0]", FlattenText($row[1]), $mfield); } //check "other" field. is it set? if ($qother == "Y") { $mfield=substr($rt, 1, strlen($rt))."other"; //create an array containing answer code, answer and fieldname(??) $alist[]=array($statlang->gT("Other"), $statlang->gT("Other"), $mfield); } } //S - Short Free Text //T - Long Free Text elseif ($firstletter == "T" || $firstletter == "S") //Short and long text { //search for key $fld = substr($rt, 1, strlen($rt)); $fielddata=$fieldmap[$fld]; //get SGQA IDs $qsid=$fielddata['sid']; $qgid=$fielddata['gid']; $qqid=$fielddata['qid']; list($qanswer, $qlid)=!empty($fielddata['aid']) ? explode("_", $fielddata['aid']) : array("", ""); //get SGQ data //list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3); //get question data $nquery = "SELECT title, type, question, other, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg()); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]); $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $nlid=$nrow[4]; } $mfield=substr($rt, 1, strlen($rt)); //Text questions either have an answer, or they don't. There's no other way of quantising the results. // So, instead of building an array of predefined answers like we do with lists & other types, // we instead create two "types" of possible answer - either there is a response.. or there isn't. // This question type then can provide a % of the question answered in the summary. $alist[]=array("Answers", $statlang->gT("Answer"), $mfield); $alist[]=array("NoAnswer", $statlang->gT("No answer"), $mfield); } //Multiple short text elseif ($firstletter == "Q") { //get SGQ data list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3); //separating another ID $tmpqid=substr($qqid, 0, strlen($qqid)-1); //check if we have legid QIDs. if not create them by substringing while (!in_array ($tmpqid,$legitqids)) $tmpqid=substr($tmpqid, 0, strlen($tmpqid)-1); //length of QID $qidlength=strlen($tmpqid); //we somehow get the answer code (see SQL later) from the $qqid $qaid=substr($qqid, $qidlength, strlen($qqid)-$qidlength); //get some question data $nquery = "SELECT title, type, question, other FROM ".db_table_name("questions")." WHERE qid='".substr($qqid, 0, $qidlength)."' AND parent_qid=0 AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg()); //more substrings $count = substr($qqid, strlen($qqid)-1); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]).'-'.$count; $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); } //get answers $qquery = "SELECT title as code, question as answer FROM ".db_table_name("questions")." WHERE parent_qid='".substr($qqid, 0, $qidlength)."' AND title='$qaid' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 5p Q)<br />$qquery<br />".$connect->ErrorMsg()); //loop through answer data while ($qrow=$qresult->FetchRow()) { //store each answer here $atext=FlattenText($qrow[1]); } //add this to the question title $qtitle .= " [$atext]"; //even more substrings... $mfield=substr($rt, 1, strlen($rt)); //Text questions either have an answer, or they don't. There's no other way of quantising the results. // So, instead of building an array of predefined answers like we do with lists & other types, // we instead create two "types" of possible answer - either there is a response.. or there isn't. // This question type then can provide a % of the question answered in the summary. $alist[]=array("Answers", $statlang->gT("Answer"), $mfield); $alist[]=array("NoAnswer", $statlang->gT("No answer"), $mfield); } //RANKING OPTION THEREFORE CONFUSING elseif ($firstletter == "R") { //getting the needed IDs somehow $lengthofnumeral=substr($rt, strpos($rt, "-")+1, 1); list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strpos($rt, "-")-($lengthofnumeral+1)), 3); //get question data $nquery = "SELECT title, type, question FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]). " [".substr($rt, strpos($rt, "-")-($lengthofnumeral), $lengthofnumeral)."]"; $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]). "[".$statlang->gT("Ranking")." ".substr($rt, strpos($rt, "-")-($lengthofnumeral), $lengthofnumeral)."]"; } //get answers $query="SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='$qqid' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer"; $result=db_execute_num($query) or safe_die("Couldn't get list of answers for multitype<br />$query<br />".$connect->ErrorMsg()); //loop through answers while ($row=$result->FetchRow()) { //create an array containing answer code, answer and fieldname(??) $mfield=substr($rt, 1, strpos($rt, "-")-1); $alist[]=array("$row[0]", FlattenText($row[1]), $mfield); } } else if ($firstletter == "|") // File UPload { //get SGQ data list($qsid, $qgid, $qqid) = explode("X", substr($rt, 1, strlen($rt)), 3); //select details for this question $nquery = "SELECT title, type, question, parent_qid, other FROM ".db_table_name("questions")." WHERE language='{$language}' AND parent_qid=0 AND qid='$qqid'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); //loop through question data while ($nrow=$nresult->FetchRow()) { $qtitle=$nrow[0]; $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $qlid=$nrow[3]; $qother=$nrow[4]; } /* 4) Average size of file per respondent 5) Average no. of files 5) Summary/count of file types (ie: 37 jpg, 65 gif, 12 png) 6) Total size of all files (useful if you're about to download them all) 7) You could also add things like smallest file size, largest file size, median file size 8) no. of files corresponding to each extension 9) max file size 10) min file size */ // 1) Total number of files uploaded // 2) Number of respondents who uploaded at least one file (with the inverse being the number of respondents who didn’t upload any) $fieldname=substr($rt, 1, strlen($rt)); $query = "SELECT SUM(".db_quote_id($fieldname.'_filecount').") as sum, AVG(".db_quote_id($fieldname.'_filecount').") as avg FROM ".db_table_name("survey_$surveyid"); $result=db_execute_assoc($query) or safe_die("Couldn't fetch the records<br />$query<br />".$connect->ErrorMsg()); $showem = array(); while ($row = $result->FetchRow()) { $showem[]=array($statlang->gT("Total number of files"), $row['sum']); $showem[]=array($statlang->gT("Average no. of files per respondent"), $row['avg']); } $query = "SELECT ". $fieldname ." as json FROM ".db_table_name("survey_$surveyid"); $result=db_execute_assoc($query) or safe_die("Couldn't fetch the records<br />$query<br />".$connect->ErrorMsg()); $responsecount = 0; $filecount = 0; $size = 0; while ($row = $result->FetchRow()) { $json = $row['json']; $phparray = json_decode($json); foreach ($phparray as $metadata) { $size += (int) $metadata->size; $filecount++; } $responsecount++; } $showem[] = array($statlang->gT("Total size of files"), $size." KB"); $showem[] = array($statlang->gT("Average file size"), $size/$filecount . " KB"); $showem[] = array($statlang->gT("Average size per respondent"), $size/$responsecount . " KB"); /* $query="SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qqid' AND language='{$language}' ORDER BY question_order"; $result=db_execute_num($query) or safe_die("Couldn't get list of subquestions for multitype<br />$query<br />".$connect->ErrorMsg()); //loop through multiple answers while ($row=$result->FetchRow()) { $mfield=substr($rt, 1, strlen($rt))."$row[0]"; //create an array containing answer code, answer and fieldname(??) $alist[]=array("$row[0]", FlattenText($row[1]), $mfield); } */ //outputting switch($outputType) { case 'xls': $headXLS = array(); $tableXLS = array(); $footXLS = array(); $xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); ++$xlsRow; ++$xlsRow; ++$xlsRow; $sheet->setCellValueByColumnAndRow(0,$xlsRow,$xlsTitle); ++$xlsRow; $sheet->setCellValueByColumnAndRow(0,$xlsRow,$xlsDesc); $headXLS[] = array($statlang->gT("Calculation"),$statlang->gT("Result")); ++$xlsRow; $sheet->setCellValueByColumnAndRow(0, $xlsRow,$statlang->gT("Calculation")); $sheet->setCellValueByColumnAndRow(1, $xlsRow,$statlang->gT("Result")); break; case 'pdf': $headPDF = array(); $tablePDF = array(); $footPDF = array(); $pdfTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $titleDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); $headPDF[] = array($statlang->gT("Calculation"),$statlang->gT("Result")); break; case 'html': $statisticsoutput .= "\n<table class='statisticstable' >\n" ."\t<thead><tr><th colspan='2' align='center'><strong>".sprintf($statlang->gT("Field summary for %s"),$qtitle).":</strong>" ."</th></tr>\n" ."\t<tr><th colspan='2' align='center'><strong>$qquestion</strong></th></tr>\n" ."\t<tr>\n\t\t<th width='50%' align='center' ><strong>" .$statlang->gT("Calculation")."</strong></th>\n" ."\t\t<th width='50%' align='center' ><strong>" .$statlang->gT("Result")."</strong></th>\n" ."\t</tr></thead>\n"; foreach ($showem as $res) $statisticsoutput .= "<tr><td>".$res[0]."</td><td>".$res[1]."</td></tr>"; break; default: break; } } //N = numerical input //K = multiple numerical input elseif ($firstletter == "N" || $firstletter == "K") //NUMERICAL TYPE { //Zero handling if (!isset($excludezeros)) //If this hasn't been set, set it to on as default: { $excludezeros=1; } //check last character, greater/less/equals don't need special treatment if (substr($rt, -1) == "G" || substr($rt, -1) == "L" || substr($rt, -1) == "=") { //DO NOTHING } else { //create SGQ identifier list($qsid, $qgid, $qqid) = explode("X", $rt, 3); //multiple numerical input if($firstletter == "K") { // This is a multiple numerical question so we need to strip of the answer id to find the question title $tmpqid=substr($qqid, 0, strlen($qqid)-1); //did we get a valid ID? while (!in_array ($tmpqid,$legitqids)) $tmpqid=substr($tmpqid, 0, strlen($tmpqid)-1); //check lenght of ID $qidlength=strlen($tmpqid); //get answer ID from qid $qaid=substr($qqid, $qidlength, strlen($qqid)-$qidlength); //get question details from DB $nquery = "SELECT title, type, question, qid, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='".substr($qqid, 0, $qidlength)."' AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die("Couldn't get text question<br />$nquery<br />".$connect->ErrorMsg()); } //probably question type "N" = numerical input else { //we can use the qqid without any editing $nquery = "SELECT title, type, question, qid, parent_qid FROM ".db_table_name("questions")." WHERE parent_qid=0 AND qid='$qqid' AND language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); } //loop through results while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]); //clean up title $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $qiqid=$nrow[3]; $qlid=$nrow[4]; } //Get answer texts for multiple numerical if(substr($rt, 0, 1) == "K") { //get answer data $atext=$connect->GetOne("SELECT question FROM ".db_table_name("questions")." WHERE parent_qid='{$qiqid}' AND scale_id=0 AND title='{$qaid}' AND language='{$language}'"); //put single items in brackets at output $qtitle .= " [$atext]"; } //outputting switch($outputType) { case 'xls': $headXLS = array(); $tableXLS = array(); $footXLS = array(); $xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); ++$xlsRow; ++$xlsRow; ++$xlsRow; $sheet->write($xlsRow, 0,$xlsTitle); ++$xlsRow; $sheet->write($xlsRow, 0,$xlsDesc); $headXLS[] = array($statlang->gT("Calculation"),$statlang->gT("Result")); ++$xlsRow; $sheet->write($xlsRow, 0,$statlang->gT("Calculation")); $sheet->write($xlsRow, 1,$statlang->gT("Result")); break; case 'pdf': $headPDF = array(); $tablePDF = array(); $footPDF = array(); $pdfTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $titleDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); $headPDF[] = array($statlang->gT("Calculation"),$statlang->gT("Result")); break; case 'html': $statisticsoutput .= "\n<table class='statisticstable' >\n" ."\t<thead><tr><th colspan='2' align='center'><strong>".sprintf($statlang->gT("Field summary for %s"),$qtitle).":</strong>" ."</th></tr>\n" ."\t<tr><th colspan='2' align='center'><strong>$qquestion</strong></th></tr>\n" ."\t<tr>\n\t\t<th width='50%' align='center' ><strong>" .$statlang->gT("Calculation")."</strong></th>\n" ."\t\t<th width='50%' align='center' ><strong>" .$statlang->gT("Result")."</strong></th>\n" ."\t</tr></thead>\n"; break; default: break; } //this field is queried using mathematical functions $fieldname=substr($rt, 1, strlen($rt)); //special treatment for MS SQL databases if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative') { //standard deviation $query = "SELECT STDEVP(".db_quote_id($fieldname)."*1) as stdev"; } //other databases (MySQL, Postgres) else { //standard deviation $query = "SELECT STDDEV(".db_quote_id($fieldname).") as stdev"; } //sum $query .= ", SUM(".db_quote_id($fieldname)."*1) as sum"; //average $query .= ", AVG(".db_quote_id($fieldname)."*1) as average"; //min $query .= ", MIN(".db_quote_id($fieldname)."*1) as minimum"; //max $query .= ", MAX(".db_quote_id($fieldname)."*1) as maximum"; //Only select responses where there is an actual number response, ignore nulls and empties (if these are included, they are treated as zeroes, and distort the deviation/mean calculations) //special treatment for MS SQL databases if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative') { //no NULL/empty values please $query .= " FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT NULL"; if(!$excludezeros) { //NO ZERO VALUES $query .= " AND (".db_quote_id($fieldname)." <> 0)"; } } //other databases (MySQL, Postgres) else { //no NULL/empty values please $query .= " FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT NULL"; if(!$excludezeros) { //NO ZERO VALUES $query .= " AND (".db_quote_id($fieldname)." != 0)"; } } //filter incomplete answers if set if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";} //$sql was set somewhere before if ($sql != "NULL") {$query .= " AND $sql";} //execute query $result=db_execute_assoc($query) or safe_die("Couldn't do maths testing<br />$query<br />".$connect->ErrorMsg()); //get calculated data while ($row=$result->FetchRow()) { //put translation of mean and calculated data into $showem array $showem[]=array($statlang->gT("Sum"), $row['sum']); $showem[]=array($statlang->gT("Standard deviation"), round($row['stdev'],2)); $showem[]=array($statlang->gT("Average"), round($row['average'],2)); $showem[]=array($statlang->gT("Minimum"), $row['minimum']); //Display the maximum and minimum figures after the quartiles for neatness $maximum=$row['maximum']; $minimum=$row['minimum']; } //CALCULATE QUARTILES //get data $query ="SELECT ".db_quote_id($fieldname)." FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT null"; //NO ZEROES if(!$excludezeros) { $query .= " AND ".db_quote_id($fieldname)." != 0"; } //filtering enabled? if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";} //if $sql values have been passed to the statistics script from another script, incorporate them if ($sql != "NULL") {$query .= " AND $sql";} //execute query $result=$connect->Execute($query) or safe_die("Disaster during median calculation<br />$query<br />".$connect->ErrorMsg()); $querystarter="SELECT ".db_quote_id($fieldname)." FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($fieldname)." IS NOT null"; //No Zeroes if(!$excludezeros) { $querystart .= " AND ".db_quote_id($fieldname)." != 0"; } //filtering enabled? if (incompleteAnsFilterstate() == "inc") {$querystarter .= " AND submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$querystarter .= " AND submitdate is not null";} //if $sql values have been passed to the statistics script from another script, incorporate them if ($sql != "NULL") {$querystarter .= " AND $sql";} //we just count the number of records returned $medcount=$result->RecordCount(); //put the total number of records at the beginning of this array array_unshift($showem, array($statlang->gT("Count"), $medcount)); //no more comment from Mazi regarding the calculation // Calculating only makes sense with more than one result if ($medcount>1) { //1ST QUARTILE (Q1) $q1=(1/4)*($medcount+1); $q1b=(int)((1/4)*($medcount+1)); $q1c=$q1b-1; $q1diff=$q1-$q1b; $total=0; // fix if there are too few values to evaluate. if ($q1c<0) {$q1c=0;} if ($q1 != $q1b) { //ODD NUMBER $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result=db_select_limit_assoc($query, 2, $q1c) or safe_die("1st Quartile query failed<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { if ($total == 0) {$total=$total-$row[$fieldname];} else {$total=$total+$row[$fieldname];} $lastnumber=$row[$fieldname]; } $q1total=$lastnumber-((1-$q1diff)*$total); if ($q1total < $minimum) {$q1total=$minimum;} $showem[]=array($statlang->gT("1st quartile (Q1)"), $q1total); } else { //EVEN NUMBER $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result=db_select_limit_assoc($query,1, $q1c) or safe_die ("1st Quartile query failed<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { $showem[]=array($statlang->gT("1st quartile (Q1)"), $row[$fieldname]); } } $total=0; //MEDIAN (Q2) $median=(1/2)*($medcount+1); $medianb=(int)((1/2)*($medcount+1)); $medianc=$medianb-1; $mediandiff=$median-$medianb; if ($median != $medianb) { //remainder $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result=db_select_limit_assoc($query,2, $medianc) or safe_die("What a complete mess with the remainder<br />$query<br />".$connect->ErrorMsg()); while ( $row=$result->FetchRow()) {$total=$total+$row[$fieldname]; } $showem[]=array($statlang->gT("2nd quartile (Median)"), $total/2); } else { //EVEN NUMBER $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result=db_select_limit_assoc($query,1, $medianc-1) or safe_die("What a complete mess<br />$query<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { $showem[]=array($statlang->gT("Median value"), $row[$fieldname]); } } $total=0; //3RD QUARTILE (Q3) $q3=(3/4)*($medcount+1); $q3b=(int)((3/4)*($medcount+1)); $q3c=$q3b-1; $q3diff=$q3-$q3b; if ($q3 != $q3b) { $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1 "; $result = db_select_limit_assoc($query,2,$q3c) or safe_die("3rd Quartile query failed<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { if ($total == 0) {$total=$total-$row[$fieldname];} else {$total=$total+$row[$fieldname];} $lastnumber=$row[$fieldname]; } $q3total=$lastnumber-((1-$q3diff)*$total); if ($q3total < $maximum) {$q1total=$maximum;} $showem[]=array($statlang->gT("3rd quartile (Q3)"), $q3total); } else { $query = $querystarter . " ORDER BY ".db_quote_id($fieldname)."*1"; $result = db_select_limit_assoc($query,1, $q3c) or safe_die("3rd Quartile even query failed<br />".$connect->ErrorMsg()); while ($row=$result->FetchRow()) { $showem[]=array($statlang->gT("3rd quartile (Q3)"), $row[$fieldname]); } } $total=0; $showem[]=array($statlang->gT("Maximum"), $maximum); //output results foreach ($showem as $shw) { switch($outputType) { case 'xls': ++$xlsRow; $sheet->write($xlsRow, 0,html_entity_decode($shw[0],ENT_QUOTES,'UTF-8')); $sheet->write($xlsRow, 1,html_entity_decode($shw[1],ENT_QUOTES,'UTF-8')); $tableXLS[] = array($shw[0],$shw[1]); break; case 'pdf': $tablePDF[] = array(html_entity_decode($shw[0],ENT_QUOTES,'UTF-8'),html_entity_decode($shw[1],ENT_QUOTES,'UTF-8')); break; case 'html': $statisticsoutput .= "\t<tr>\n" ."\t\t<td align='center' >$shw[0]</td>\n" ."\t\t<td align='center' >$shw[1]</td>\n" ."\t</tr>\n"; break; default: break; } } switch($outputType) { case 'xls': ++$xlsRow; $sheet->write($xlsRow, 0,$statlang->gT("Null values are ignored in calculations")); ++$xlsRow; $sheet->write($xlsRow, 0,sprintf($statlang->gT("Q1 and Q3 calculated using %s"), $statlang->gT("minitab method"))); $footXLS[] = array($statlang->gT("Null values are ignored in calculations")); $footXLS[] = array(sprintf($statlang->gT("Q1 and Q3 calculated using %s"), $statlang->gT("minitab method"))); break; case 'pdf': $footPDF[] = array($statlang->gT("Null values are ignored in calculations")); $footPDF[] = array(sprintf($statlang->gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>".$statlang->gT("minitab method")."</a>")); $pdf->addPage('P','A4'); $pdf->Bookmark($pdf->delete_html($qquestion), 1, 0); $pdf->titleintopdf($pdfTitle,$titleDesc); $pdf->headTable($headPDF, $tablePDF); $pdf->tablehead($footPDF); break; case 'html': //footer of question type "N" $statisticsoutput .= "\t<tr>\n" ."\t\t<td colspan='4' align='center' bgcolor='#EEEEEE'>\n" ."\t\t\t<font size='1'>".$statlang->gT("Null values are ignored in calculations")."<br />\n" ."\t\t\t".sprintf($statlang->gT("Q1 and Q3 calculated using %s"), "<a href='http://mathforum.org/library/drmath/view/60969.html' target='_blank'>".$statlang->gT("minitab method")."</a>") ."</font>\n" ."\t\t</td>\n" ."\t</tr>\n</table>\n"; break; default: break; } //clean up unset($showem); } //end if (enough results?) //not enough (<1) results for calculation else { switch($outputType) { case 'xls': $tableXLS = array(); $tableXLS[] = array($statlang->gT("Not enough values for calculation")); ++$xlsRow; $sheet->write($xlsRow, 0, $statlang->gT("Not enough values for calculation")); break; case 'pdf': $tablePDF = array(); $tablePDF[] = array($statlang->gT("Not enough values for calculation")); $pdf->addPage('P','A4'); $pdf->Bookmark($pdf->delete_html($qquestion), 1, 0); $pdf->titleintopdf($pdfTitle,$titleDesc); $pdf->equalTable($tablePDF); break; case 'html': //output $statisticsoutput .= "\t<tr>\n" ."\t\t<td align='center' colspan='4'>".$statlang->gT("Not enough values for calculation")."</td>\n" ."\t</tr>\n</table><br />\n"; break; default: break; } unset($showem); } } //end else -> check last character, greater/less/equals don't need special treatment } //end else-if -> multiple numerical types //is there some "id", "datestamp" or "D" within the type? elseif (substr($rt, 0, 2) == "id" || substr($rt, 0, 9) == "datestamp" || ($firstletter == "D")) { /* * DON'T show anything for date questions * because there aren't any statistics implemented yet! * * See bug report #2539 and * feature request #2620 */ } // NICE SIMPLE SINGLE OPTION ANSWERS else { //search for key $fielddata=$fieldmap[$rt]; //print_r($fielddata); //get SGQA IDs $qsid=$fielddata['sid']; $qgid=$fielddata['gid']; $qqid=$fielddata['qid']; $qanswer=$fielddata['aid']; //question type $qtype=$fielddata['type']; //question string $qastring=$fielddata['question']; //question ID $rqid=$qqid; //get question data $nquery = "SELECT title, type, question, qid, parent_qid, other FROM ".db_table_name("questions")." WHERE qid='{$rqid}' AND parent_qid=0 and language='{$language}'"; $nresult = db_execute_num($nquery) or safe_die ("Couldn't get question<br />$nquery<br />".$connect->ErrorMsg()); //loop though question data while ($nrow=$nresult->FetchRow()) { $qtitle=FlattenText($nrow[0]); $qtype=$nrow[1]; $qquestion=FlattenText($nrow[2]); $qiqid=$nrow[3]; $qparentqid=$nrow[4]; $qother=$nrow[5]; } //check question types switch($qtype) { //Array of 5 point choices (several items to rank!) case "A": //get data $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 5p Q)<br />$qquery<br />".$connect->ErrorMsg()); //loop through results while ($qrow=$qresult->FetchRow()) { //5-point array for ($i=1; $i<=5; $i++) { //add data $alist[]=array("$i", "$i"); } //add counter $atext=FlattenText($qrow[1]); } //list IDs and answer codes in brackets $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; //Array of 10 point choices //same as above just with 10 items case "B": $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details (Array 10p Q)<br />$qquery<br />".$connect->ErrorMsg()); while ($qrow=$qresult->FetchRow()) { for ($i=1; $i<=10; $i++) { $alist[]=array("$i", "$i"); } $atext=FlattenText($qrow[1]); } $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; //Array of Yes/No/$statlang->gT("Uncertain") case "C": $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg()); //loop thorugh results while ($qrow=$qresult->FetchRow()) { //add results $alist[]=array("Y", $statlang->gT("Yes")); $alist[]=array("N", $statlang->gT("No")); $alist[]=array("U", $statlang->gT("Uncertain")); $atext=FlattenText($qrow[1]); } //output $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; //Array of Yes/No/$statlang->gT("Uncertain") //same as above case "E": $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg()); while ($qrow=$qresult->FetchRow()) { $alist[]=array("I", $statlang->gT("Increase")); $alist[]=array("S", $statlang->gT("Same")); $alist[]=array("D", $statlang->gT("Decrease")); $atext=FlattenText($qrow[1]); } $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; case ";": //Array (Multi Flexi) (Text) list($qacode, $licode)=explode("_", $qanswer); $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qacode' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg()); while ($qrow=$qresult->FetchRow()) { $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qiqid}' AND scale_id=0 AND code = '{$licode}' AND language='{$language}'ORDER BY sortorder, code"; $fresult = db_execute_assoc($fquery); while ($frow=$fresult->FetchRow()) { $alist[]=array($frow['code'], $frow['answer']); $ltext=$frow['answer']; } $atext=FlattenText($qrow[1]); } $qquestion .= $linefeed."[".$atext."] [".$ltext."]"; $qtitle .= "($qanswer)"; break; case ":": //Array (Multiple Flexi) (Numbers) $qidattributes=getQuestionAttributes($qiqid); if (trim($qidattributes['multiflexible_max'])!='') { $maxvalue=$qidattributes['multiflexible_max']; } else { $maxvalue=10; } if (trim($qidattributes['multiflexible_min'])!='') { $minvalue=$qidattributes['multiflexible_min']; } else { $minvalue=1; } if (trim($qidattributes['multiflexible_step'])!='') { $stepvalue=$qidattributes['multiflexible_step']; } else { $stepvalue=1; } if ($qidattributes['multiflexible_checkbox']!=0) { $minvalue=0; $maxvalue=1; $stepvalue=1; } for($i=$minvalue; $i<=$maxvalue; $i+=$stepvalue) { $alist[]=array($i, $i); } $qquestion .= $linefeed."[".$fielddata['subquestion1']."] [".$fielddata['subquestion2']."]"; list($myans, $mylabel)=explode("_", $qanswer); $qtitle .= "[$myans][$mylabel]"; break; case "F": //Array of Flexible case "H": //Array of Flexible by Column $qquery = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $qresult=db_execute_num($qquery) or safe_die ("Couldn't get answer details<br />$qquery<br />".$connect->ErrorMsg()); //loop through answers while ($qrow=$qresult->FetchRow()) { //this question type uses its own labels $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qiqid}' AND scale_id=0 AND language='{$language}'ORDER BY sortorder, code"; $fresult = db_execute_assoc($fquery); //add code and title to results for outputting them later while ($frow=$fresult->FetchRow()) { $alist[]=array($frow['code'], FlattenText($frow['answer'])); } //counter $atext=FlattenText($qrow[1]); } //output $qquestion .= $linefeed."[".$atext."]"; $qtitle .= "($qanswer)"; break; case "G": //Gender $alist[]=array("F", $statlang->gT("Female")); $alist[]=array("M", $statlang->gT("Male")); break; case "Y": //Yes\No $alist[]=array("Y", $statlang->gT("Yes")); $alist[]=array("N", $statlang->gT("No")); break; case "I": //Language // Using previously defined $surveylanguagecodes array of language codes foreach ($surveylanguagecodes as $availlang) { $alist[]=array($availlang, getLanguageNameFromCode($availlang,false)); } break; case "5": //5 Point (just 1 item to rank!) for ($i=1; $i<=5; $i++) { $alist[]=array("$i", "$i"); } break; case "1": //array (dual scale) $sSubquestionQuery = "SELECT question FROM ".db_table_name("questions")." WHERE parent_qid='$qiqid' AND title='$qanswer' AND language='{$language}' ORDER BY question_order"; $sSubquestion=FlattenText($connect->GetOne($sSubquestionQuery)); //get question attributes $qidattributes=getQuestionAttributes($qqid); //check last character -> label 1 if (substr($rt,-1,1) == 0) { //get label 1 $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qqid}' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, code"; //header available? if (trim($qidattributes['dualscale_headerA'])!='') { //output $labelheader= "[".$qidattributes['dualscale_headerA']."]"; } //no header else { $labelheader =''; } //output $labelno = sprintf($clang->gT('Label %s'),'1'); } //label 2 else { //get label 2 $fquery = "SELECT * FROM ".db_table_name("answers")." WHERE qid='{$qqid}' AND scale_id=1 AND language='{$language}' ORDER BY sortorder, code"; //header available? if (trim($qidattributes['dualscale_headerB'])!='') { //output $labelheader= "[".$qidattributes['dualscale_headerB']."]"; } //no header else { $labelheader =''; } //output $labelno = sprintf($clang->gT('Label %s'),'2'); } //get data $fresult = db_execute_assoc($fquery); //put label code and label title into array while ($frow=$fresult->FetchRow()) { $alist[]=array($frow['code'], FlattenText($frow['answer'])); } //adapt title and question $qtitle = $qtitle." [".$sSubquestion."][".$labelno."]"; $qquestion = $qastring .$labelheader; break; default: //default handling //get answer code and title $qquery = "SELECT code, answer FROM ".db_table_name("answers")." WHERE qid='$qqid' AND scale_id=0 AND language='{$language}' ORDER BY sortorder, answer"; $qresult = db_execute_num($qquery) or safe_die ("Couldn't get answers list<br />$qquery<br />".$connect->ErrorMsg()); //put answer code and title into array while ($qrow=$qresult->FetchRow()) { $alist[]=array("$qrow[0]", FlattenText($qrow[1])); } //handling for "other" field for list radio or list drowpdown if ((($qtype == "L" || $qtype == "!") && $qother == "Y")) { //add "other" $alist[]=array($statlang->gT("Other"),$statlang->gT("Other"),$fielddata['fieldname'].'other'); } if ( $qtype == "O") { //add "comment" $alist[]=array($statlang->gT("Comments"),$statlang->gT("Comments"),$fielddata['fieldname'].'comment'); } } //end switch question type //moved because it's better to have "no answer" at the end of the list instead of the beginning //put data into array $alist[]=array("", $statlang->gT("No answer")); } //end else -> single option answers //foreach ($alist as $al) {$statisticsoutput .= "$al[0] - $al[1]<br />";} //debugging line //foreach ($fvalues as $fv) {$statisticsoutput .= "$fv | ";} //debugging line //2. Collect and Display results ####################################################################### if (isset($alist) && $alist) //Make sure there really is an answerlist, and if so: { // this will count the answers considered completed $TotalCompleted = 0; switch($outputType) { case 'xls': $xlsTitle = sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8')); $xlsDesc = html_entity_decode($qquestion,ENT_QUOTES,'UTF-8'); ++$xlsRow; ++$xlsRow; ++$xlsRow; $sheet->write($xlsRow, 0,$xlsTitle); ++$xlsRow; $sheet->write($xlsRow, 0,$xlsDesc); $tableXLS = array(); $footXLS = array(); break; case 'pdf': $sPDFQuestion=FlattenText($qquestion,true); $pdfTitle = $pdf->delete_html(sprintf($statlang->gT("Field summary for %s"),html_entity_decode($qtitle,ENT_QUOTES,'UTF-8'))); $titleDesc = $sPDFQuestion; $pdf->addPage('P','A4'); $pdf->Bookmark($sPDFQuestion, 1, 0); $pdf->titleintopdf($pdfTitle,$sPDFQuestion); $tablePDF = array(); $footPDF = array(); break; case 'html': //output $statisticsoutput .= "<table class='statisticstable'>\n" ."\t<thead><tr><th colspan='4' align='center'><strong>" //headline .sprintf($statlang->gT("Field summary for %s"),$qtitle)."</strong>" ."</th></tr>\n" ."\t<tr><th colspan='4' align='center'><strong>" //question title .$qquestion."</strong></th></tr>\n" ."\t<tr>\n\t\t<th width='50%' align='center' >"; break; default: break; } echo ''; //loop thorugh the array which contains all answer data foreach ($alist as $al) { //picks out alist that come from the multiple list above if (isset($al[2]) && $al[2]) { //handling for "other" option if ($al[0] == $statlang->gT("Other")) { if($qtype=='!' || $qtype=='L') { // It is better for single choice question types to filter on the number of '-oth-' entries, than to // just count the number of 'other' values - that way with failing Javascript the statistics don't get messed up $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id(substr($al[2],0,strlen($al[2])-5))."='-oth-'"; } else { //get data $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE "; $query .= ($connect->databaseType == "mysql")? db_quote_id($al[2])." != ''" : "NOT (".db_quote_id($al[2])." LIKE '')"; } } /* * text questions: * * U = huge free text * T = long free text * S = short free text * Q = multiple short text */ elseif ($qtype == "U" || $qtype == "T" || $qtype == "S" || $qtype == "Q" || $qtype == ";") { //free text answers if($al[0]=="Answers") { $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE "; $query .= ($connect->databaseType == "mysql")? db_quote_id($al[2])." != ''" : "NOT (".db_quote_id($al[2])." LIKE '')"; } //"no answer" handling elseif($al[0]=="NoAnswer") { $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( "; $query .= ($connect->databaseType == "mysql")? db_quote_id($al[2])." = '')" : " (".db_quote_id($al[2])." LIKE ''))"; } } elseif ($qtype == "O") { $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( "; $query .= ($connect->databaseType == "mysql")? db_quote_id($al[2])." <> '')" : " (".db_quote_id($al[2])." NOT LIKE ''))"; // all other question types } else { $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($al[2])." ="; //ranking question? if (substr($rt, 0, 1) == "R") { $query .= " '$al[0]'"; } else { $query .= " 'Y'"; } } } //end if -> alist set else { if ($al[0] != "") { //get more data if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative') { // mssql cannot compare text blobs so we have to cast here $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE cast(".db_quote_id($rt)." as varchar)= '$al[0]'"; } else $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ".db_quote_id($rt)." = '$al[0]'"; } else { // This is for the 'NoAnswer' case // We need to take into account several possibilities // * NoAnswer cause the participant clicked the NoAnswer radio // ==> in this case value is '' or ' ' // * NoAnswer in text field // ==> value is '' // * NoAnswer due to conditions, or a page not displayed // ==> value is NULL if ($connect->databaseType == 'odbc_mssql' || $connect->databaseType == 'odbtp' || $connect->databaseType == 'mssql_n' || $connect->databaseType == 'mssqlnative') { // mssql cannot compare text blobs so we have to cast here //$query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE (".db_quote_id($rt)." IS NULL " $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( " // . "OR cast(".db_quote_id($rt)." as varchar) = '' " . "cast(".db_quote_id($rt)." as varchar) = '' " . "OR cast(".db_quote_id($rt)." as varchar) = ' ' )"; } else // $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE (".db_quote_id($rt)." IS NULL " $query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." WHERE ( " // . "OR ".db_quote_id($rt)." = '' " . " ".db_quote_id($rt)." = '' " . "OR ".db_quote_id($rt)." = ' ') "; } } //check filter option if (incompleteAnsFilterstate() == "inc") {$query .= " AND submitdate is null";} elseif (incompleteAnsFilterstate() == "filter") {$query .= " AND submitdate is not null";} //check for any "sql" that has been passed from another script if ($sql != "NULL") {$query .= " AND $sql";} //get data $result=db_execute_num($query) or safe_die ("Couldn't do count of values<br />$query<br />".$connect->ErrorMsg()); // $statisticsoutput .= "\n<!-- ($sql): $query -->\n\n"; // this just extracts the data, after we present while ($row=$result->FetchRow()) { //increase counter $TotalCompleted += $row[0]; //"no answer" handling if ($al[0] === "") {$fname=$statlang->gT("No answer");} //"other" handling //"Answers" means that we show an option to list answer to "other" text field elseif ($al[0] === $statlang->gT("Other") || $al[0] === "Answers" || ($qtype === "O" && $al[0] === $statlang->gT("Comments")) || $qtype === "P") { if ($qtype == "P" ) $ColumnName_RM = $al[2]."comment"; else $ColumnName_RM = $al[2]; if ($qtype=='O') { $TotalCompleted -=$row[0]; } $fname="$al[1]"; if ($browse===true) $fname .= " <input type='button' value='".$statlang->gT("Browse")."' onclick=\"window.open('admin.php?action=listcolumn&sid=$surveyid&column=$ColumnName_RM&sql=".urlencode($sql)."', 'results', 'width=460, height=500, left=50, top=50, resizable=yes, scrollbars=yes, menubar=no, status=no, location=no, toolbar=no')\" />"; } /* * text questions: * * U = huge free text * T = long free text * S = short free text * Q = multiple short text */ elseif ($qtype == "S" || $qtype == "U" || $qtype == "T" || $qtype == "Q") { $headPDF = array(); $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); //show free text answers if ($al[0] == "Answers") { $fname= "$al[1]"; if ($browse===true) $fname .= " <input type='submit' value='" . $statlang->gT("Browse")."' onclick=\"window.open('admin.php?action=listcolumn&sid=$surveyid&column=$al[2]&sql=" . urlencode($sql)."', 'results', 'width=460, height=500, left=50, top=50, resizable=yes, scrollbars=yes, menubar=no, status=no, location=no, toolbar=no')\" />"; } elseif ($al[0] == "NoAnswer") { $fname= "$al[1]"; } $statisticsoutput .= "</th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Count")."</strong></th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Percentage")."</strong></th>\n" ."\t</tr></thead>\n"; } //check if aggregated results should be shown elseif (isset($showaggregateddata) && $showaggregateddata == 1) { if(!isset($showheadline) || $showheadline != false) { if($qtype == "5" || $qtype == "A") { switch($outputType) { case 'xls': $headXLS = array(); $headXLS[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"),$statlang->gT("Sum")); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Answer")); $sheet->write($xlsRow,1,$statlang->gT("Count")); $sheet->write($xlsRow,2,$statlang->gT("Percentage")); $sheet->write($xlsRow,3,$statlang->gT("Sum")); break; case 'pdf': $headPDF = array(); $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage"),$statlang->gT("Sum")); break; case 'html': //four columns $statisticsoutput .= "<strong>".$statlang->gT("Answer")."</strong></th>\n" ."\t\t<th width='15%' align='center' >" ."<strong>".$statlang->gT("Count")."</strong></th>\n" ."\t\t<th width='20%' align='center' >" ."<strong>".$statlang->gT("Percentage")."</strong></th>\n" ."\t\t<th width='15%' align='center' >" ."<strong>".$statlang->gT("Sum")."</strong></th>\n" ."\t</tr></thead>\n"; break; default: break; } $showheadline = false; } else { switch($outputType) { case 'xls': $headXLS = array(); $headXLS[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Answer")); $sheet->write($xlsRow,1,$statlang->gT("Count")); $sheet->write($xlsRow,2,$statlang->gT("Percentage")); break; case 'pdf': $headPDF = array(); $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); break; case 'html': //three columns $statisticsoutput .= "<strong>".$statlang->gT("Answer")."</strong></td>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Count")."</strong></th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Percentage")."</strong></th>\n" ."\t</tr></thead>\n"; break; default: break; } $showheadline = false; } } //text for answer column is always needed $fname="$al[1] ($al[0])"; //these question types get special treatment by $showaggregateddata if($qtype == "5" || $qtype == "A") { //put non-edited data in here because $row will be edited later $grawdata[]=$row[0]; $showaggregated_indice=count($grawdata) - 1; $showaggregated_indice_table[$showaggregated_indice]="aggregated"; $showaggregated_indice=-1; //keep in mind that we already added data (will be checked later) $justadded = true; //we need a counter because we want to sum up certain values //reset counter if 5 items have passed if(!isset($testcounter) || $testcounter >= 4) { $testcounter = 0; } else { $testcounter++; } //beside the known percentage value a new aggregated value should be shown //therefore this item is marked in a certain way if($testcounter == 0 ) //add 300 to original value { //HACK: add three times the total number of results to the value //This way we get a 300 + X percentage which can be checked later $row[0] += (3*$results); } //the third value should be shown twice later -> mark it if($testcounter == 2) //add 400 to original value { //HACK: add four times the total number of results to the value //This way there should be a 400 + X percentage which can be checked later $row[0] += (4*$results); } //the last value aggregates the data of item 4 + item 5 later if($testcounter == 4 ) //add 200 to original value { //HACK: add two times the total number of results to the value //This way there should be a 200 + X percentage which can be checked later $row[0] += (2*$results); } } //end if -> question type = "5"/"A" } //end if -> show aggregated data //handling what's left else { if(!isset($showheadline) || $showheadline != false) { switch($outputType) { case 'xls': $headXLS = array(); $headXLS[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Answer")); $sheet->write($xlsRow,1,$statlang->gT("Count")); $sheet->write($xlsRow,2,$statlang->gT("Percentage")); break; case 'pdf': $headPDF = array(); $headPDF[] = array($statlang->gT("Answer"),$statlang->gT("Count"),$statlang->gT("Percentage")); break; case 'html': //three columns $statisticsoutput .= "<strong>".$statlang->gT("Answer")."</strong></th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Count")."</strong></th>\n" ."\t\t<th width='25%' align='center' >" ."<strong>".$statlang->gT("Percentage")."</strong></th>\n" ."\t</tr></thead>\n"; break; default: break; } $showheadline = false; } //answer text $fname="$al[1] ($al[0])"; } //are there some results to play with? if ($results > 0) { //calculate percentage $gdata[] = ($row[0]/$results)*100; } //no results else { //no data! $gdata[] = "N/A"; } //only add this if we don't handle question type "5"/"A" if(!isset($justadded)) { //put absolute data into array $grawdata[]=$row[0]; } else { //unset to handle "no answer" data correctly unset($justadded); } //put question title and code into array $label[]=$fname; //put only the code into the array $justcode[]=$al[0]; //edit labels and put them into antoher array $lbl[] = wordwrap(FlattenText("$al[1] ($row[0])"), 25, "\n"); // NMO 2009-03-24 $lblrtl[] = utf8_strrev(wordwrap(FlattenText("$al[1] )$row[0]("), 25, "\n")); // NMO 2009-03-24 } //end while -> loop through results } //end foreach -> loop through answer data //no filtering of incomplete answers and NO multiple option questions //if ((incompleteAnsFilterstate() != "filter") and ($qtype != "M") and ($qtype != "P")) //error_log("TIBO ".print_r($showaggregated_indice_table,true)); if (($qtype != "M") and ($qtype != "P")) { //is the checkbox "Don't consider NON completed responses (only works when Filter incomplete answers is Disable)" checked? //if (isset($_POST["noncompleted"]) and ($_POST["noncompleted"] == "on") && (isset($showaggregateddata) && $showaggregateddata == 0)) // TIBO: TODO WE MUST SKIP THE FOLLOWING SECTION FOR TYPE A and 5 when // showaggreagated data is set and set to 1 if (isset($_POST["noncompleted"]) and ($_POST["noncompleted"] == "on") ) { //counter $i=0; while (isset($gdata[$i])) { if (isset($showaggregated_indice_table[$i]) && $showaggregated_indice_table[$i]=="aggregated") { // do nothing, we don't rewrite aggregated results // or at least I don't know how !!! (lemeur) } else { //we want to have some "real" data here if ($gdata[$i] != "N/A") { //calculate percentage $gdata[$i] = ($grawdata[$i]/$TotalCompleted)*100; } } //increase counter $i++; } //end while (data available) } //end if -> noncompleted checked //noncompleted is NOT checked else { //calculate total number of incompleted records $TotalIncomplete = $results - $TotalCompleted; //output if ((incompleteAnsFilterstate() != "filter")) { $fname=$statlang->gT("Not completed or Not displayed"); } else { $fname=$statlang->gT("Not displayed"); } //we need some data if ($results > 0) { //calculate percentage $gdata[] = ($TotalIncomplete/$results)*100; } //no data :( else { $gdata[] = "N/A"; } //put data of incompleted records into array $grawdata[]=$TotalIncomplete; //put question title ("Not completed") into array $label[]= $fname; //put the code ("Not completed") into the array $justcode[]=$fname; //edit labels and put them into antoher array if ((incompleteAnsFilterstate() != "filter")) { $lbl[] = wordwrap(FlattenText($statlang->gT("Not completed or Not displayed")." ($TotalIncomplete)"), 20, "\n"); // NMO 2009-03-24 } else { $lbl[] = wordwrap(FlattenText($statlang->gT("Not displayed")." ($TotalIncomplete)"), 20, "\n"); // NMO 2009-03-24 } } //end else -> noncompleted NOT checked } //end if -> no filtering of incomplete answers and no multiple option questions //counter $i=0; //we need to know which item we are editing $itemcounter = 1; //array to store items 1 - 5 of question types "5" and "A" $stddevarray = array(); //loop through all available answers while (isset($gdata[$i])) { //repeat header (answer, count, ...) for each new question unset($showheadline); /* * there are 3 colums: * * 1 (50%) = answer (title and code in brackets) * 2 (25%) = count (absolute) * 3 (25%) = percentage */ $statisticsoutput .= "\t<tr>\n\t\t<td align='center' >" . $label[$i] ."\n" ."\t\t</td>\n" //output absolute number of records ."\t\t<td align='center' >" . $grawdata[$i] . "\n</td>"; //no data if ($gdata[$i] == "N/A") { switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $gdata[$i]). "%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $gdata[$i]). "%"); break; case 'pdf': $tablePDF[] = array(FlattenText($label[$i]),$grawdata[$i],sprintf("%01.2f", $gdata[$i]). "%", ""); break; case 'html': //output when having no data $statisticsoutput .= "\t\t<td align='center' >"; //percentage = 0 $statisticsoutput .= sprintf("%01.2f", $gdata[$i]) . "%"; $gdata[$i] = 0; //check if we have to adjust ouput due to $showaggregateddata setting if(isset($showaggregateddata) && $showaggregateddata == 1 && ($qtype == "5" || $qtype == "A")) { $statisticsoutput .= "\t\t</td>"; } elseif ($qtype == "S" || $qtype == "U" || $qtype == "T" || $qtype == "Q") { $statisticsoutput .= "</td>\n\t</tr>\n"; } break; default: break; } } //data available else { //check if data should be aggregated if(isset($showaggregateddata) && $showaggregateddata == 1 && ($qtype == "5" || $qtype == "A")) { //mark that we have done soemthing special here $aggregated = true; //just calculate everything once. the data is there in the array if($itemcounter == 1) { //there are always 5 answers for($x = 0; $x < 5; $x++) { //put 5 items into array for further calculations array_push($stddevarray, $grawdata[$x]); } } //"no answer" & items 2 / 4 - nothing special to do here, just adjust output if($gdata[$i] <= 100) { if($itemcounter == 2 && $label[$i+4] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+4]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+4])) * 100; } else { $percentage = 0; } } elseif($itemcounter == 4 && $label[$i+2] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+2]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+2])) * 100; } else { $percentage = 0; } } else { $percentage = $gdata[$i]; } switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[]= array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%", ""); break; case 'html': //output $statisticsoutput .= "\t\t<td align='center'>"; //output percentage $statisticsoutput .= sprintf("%01.2f", $percentage) . "%"; //adjust output $statisticsoutput .= "\t\t</td>"; break; default: break; } } //item 3 - just show results twice //old: if($gdata[$i] >= 400) //trying to fix bug #2583: if($gdata[$i] >= 400 && $i != 0) { //remove "400" which was added before $gdata[$i] -= 400; if($itemcounter == 3 && $label[$i+3] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+3]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+3])) * 100; } else { $percentage = 0; } } else { //get the original percentage $percentage = $gdata[$i]; } switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $percentage)."%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%"); $sheet->write($xlsRow,3,sprintf("%01.2f", $percentage)."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $percentage)."%"); break; case 'html': //output percentage $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>"; //output again (no real aggregation here) $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $percentage)."%"; $statisticsoutput .= "</td>\t\t"; break; default: break; } } //FIRST value -> add percentage of item 1 + item 2 //old: if($gdata[$i] >= 300 && $gdata[$i] < 400) //trying to fix bug #2583: if(($gdata[$i] >= 300 && $gdata[$i] < 400) || ($i == 0 && $gdata[$i] <= 400)) { //remove "300" which was added before $gdata[$i] -= 300; if($itemcounter == 1 && $label[$i+5] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+5]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+5])) * 100; $percentage2 = ($grawdata[$i + 1] / ($results - $grawdata[$i+5])) * 100; } else { $percentage = 0; $percentage2 = 0; } } else { $percentage = $gdata[$i]; $percentage2 = $gdata[$i+1]; } //percentage of item 1 + item 2 $aggregatedgdata = $percentage + $percentage2; switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%"); $sheet->write($xlsRow,3,sprintf("%01.2f", $aggregatedgdata)."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%"); break; case 'html': //output percentage $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>"; //output aggregated data $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata)."%"; $statisticsoutput .= "</td>\t\t"; break; default: break; } } //LAST value -> add item 4 + item 5 if($gdata[$i] > 100 && $gdata[$i] < 300) { //remove "200" which was added before $gdata[$i] -= 200; if($itemcounter == 5 && $label[$i+1] == $statlang->gT("No answer")) { //prevent division by zero if(($results - $grawdata[$i+1]) > 0) { //re-calculate percentage $percentage = ($grawdata[$i] / ($results - $grawdata[$i+1])) * 100; $percentage2 = ($grawdata[$i - 1] / ($results - $grawdata[$i+1])) * 100; } else { $percentage = 0; $percentage2 = 0; } } else { $percentage = $gdata[$i]; $percentage2 = $gdata[$i-1]; } //item 4 + item 5 $aggregatedgdata = $percentage + $percentage2; switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%"); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $percentage)."%"); $sheet->write($xlsRow,3,sprintf("%01.2f", $aggregatedgdata)."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $percentage)."%",sprintf("%01.2f", $aggregatedgdata)."%"); break; case 'html': //output percentage $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>"; //output aggregated data $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata)."%"; $statisticsoutput .= "</td>\t\t"; break; default: break; } // create new row "sum" //calculate sum of items 1-5 $sumitems = $grawdata[$i] + $grawdata[$i-1] + $grawdata[$i-2] + $grawdata[$i-3] + $grawdata[$i-4]; //special treatment for zero values if($sumitems > 0) { $sumpercentage = "100.00"; } else { $sumpercentage = "0"; } //special treatment for zero values if($TotalCompleted > 0) { $casepercentage = "100.00"; } else { $casepercentage = "0"; } switch($outputType) { case 'xls': $footXLS[] = array($statlang->gT("Sum")." (".$statlang->gT("Answers").")",$sumitems,$sumpercentage."%",$sumpercentage."%"); $footXLS[] = array($statlang->gT("Number of cases"),$TotalCompleted,$casepercentage."%",""); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Sum")." (".$statlang->gT("Answers").")"); $sheet->write($xlsRow,1,$sumitems); $sheet->write($xlsRow,2,$sumpercentage."%"); $sheet->write($xlsRow,3,$sumpercentage."%"); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Number of cases")); $sheet->write($xlsRow,1,$TotalCompleted); $sheet->write($xlsRow,2,$casepercentage."%"); break; case 'pdf': $footPDF[] = array($statlang->gT("Sum")." (".$statlang->gT("Answers").")",$sumitems,$sumpercentage."%",$sumpercentage."%"); $footPDF[] = array($statlang->gT("Number of cases"),$TotalCompleted,$casepercentage."%",""); break; case 'html': $statisticsoutput .= "\t\t \n\t</tr>\n"; $statisticsoutput .= "<tr><td align='center'><strong>".$statlang->gT("Sum")." (".$statlang->gT("Answers").")</strong></td>"; $statisticsoutput .= "<td align='center' ><strong>".$sumitems."</strong></td>"; $statisticsoutput .= "<td align='center' ><strong>$sumpercentage%</strong></td>"; $statisticsoutput .= "<td align='center' ><strong>$sumpercentage%</strong></td>"; $statisticsoutput .= "\t\t \n\t</tr>\n"; $statisticsoutput .= "<tr><td align='center'>".$statlang->gT("Number of cases")."</td>"; //German: "Fallzahl" $statisticsoutput .= "<td align='center' >".$TotalCompleted."</td>"; $statisticsoutput .= "<td align='center' >$casepercentage%</td>"; //there has to be a whitespace within the table cell to display correctly $statisticsoutput .= "<td align='center' > </td></tr>"; break; default: break; } } } //end if -> show aggregated data //don't show aggregated data else { switch($outputType) { case 'xls': $label[$i]=FlattenText($label[$i]); $tableXLS[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $gdata[$i])."%", ""); ++$xlsRow; $sheet->write($xlsRow,0,$label[$i]); $sheet->write($xlsRow,1,$grawdata[$i]); $sheet->write($xlsRow,2,sprintf("%01.2f", $gdata[$i])."%"); //$sheet->write($xlsRow,3,$sumpercentage."%"); break; case 'pdf': $label[$i]=FlattenText($label[$i]); $tablePDF[] = array($label[$i],$grawdata[$i],sprintf("%01.2f", $gdata[$i])."%", ""); break; case 'html': //output percentage $statisticsoutput .= "\t\t<td align='center' >"; $statisticsoutput .= sprintf("%01.2f", $gdata[$i]) . "%"; $statisticsoutput .= "\t\t"; //end output per line. there has to be a whitespace within the table cell to display correctly $statisticsoutput .= "\t\t </td>\n\t</tr>\n"; break; default: break; } } } //end else -> $gdata[$i] != "N/A" //increase counter $i++; $itemcounter++; } //end while //only show additional values when this setting is enabled if(isset($showaggregateddata) && $showaggregateddata == 1 ) { //it's only useful to calculate standard deviation and arithmetic means for question types //5 = 5 Point Scale //A = Array (5 Point Choice) if($qtype == "5" || $qtype == "A") { $stddev = 0; $am = 0; //calculate arithmetic mean if(isset($sumitems) && $sumitems > 0) { //calculate and round results //there are always 5 items for($x = 0; $x < 5; $x++) { //create product of item * value $am += (($x+1) * $stddevarray[$x]); } //prevent division by zero if(isset($stddevarray) && array_sum($stddevarray) > 0) { $am = round($am / array_sum($stddevarray),2); } else { $am = 0; } //calculate standard deviation -> loop through all data /* * four steps to calculate the standard deviation * 1 = calculate difference between item and arithmetic mean and multiply with the number of elements * 2 = create sqaure value of difference * 3 = sum up square values * 4 = multiply result with 1 / (number of items) * 5 = get root */ for($j = 0; $j < 5; $j++) { //1 = calculate difference between item and arithmetic mean $diff = (($j+1) - $am); //2 = create square value of difference $squarevalue = square($diff); //3 = sum up square values and multiply them with the occurence //prevent divison by zero if($squarevalue != 0 && $stddevarray[$j] != 0) { $stddev += $squarevalue * $stddevarray[$j]; } } //4 = multiply result with 1 / (number of items (=5)) //There are two different formulas to calculate standard derivation //$stddev = $stddev / array_sum($stddevarray); //formula source: http://de.wikipedia.org/wiki/Standardabweichung //prevent division by zero if((array_sum($stddevarray)-1) != 0 && $stddev != 0) { $stddev = $stddev / (array_sum($stddevarray)-1); //formula source: http://de.wikipedia.org/wiki/Empirische_Varianz } else { $stddev = 0; } //5 = get root $stddev = sqrt($stddev); $stddev = round($stddev,2); } switch($outputType) { case 'xls': $tableXLS[] = array($statlang->gT("Arithmetic mean"),$am,'',''); $tableXLS[] = array($statlang->gT("Standard deviation"),$stddev,'',''); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Arithmetic mean")); $sheet->write($xlsRow,1,$am); ++$xlsRow; $sheet->write($xlsRow,0,$statlang->gT("Standard deviation")); $sheet->write($xlsRow,1,$stddev); break; case 'pdf': $tablePDF[] = array($statlang->gT("Arithmetic mean"),$am,'',''); $tablePDF[] = array($statlang->gT("Standard deviation"),$stddev,'',''); break; case 'html': //calculate standard deviation $statisticsoutput .= "<tr><td align='center'>".$statlang->gT("Arithmetic mean")."</td>"; //German: "Fallzahl" $statisticsoutput .= "<td> </td><td align='center'> $am</td><td> </td></tr>"; $statisticsoutput .= "<tr><td align='center'>".$statlang->gT("Standard deviation")."</td>"; //German: "Fallzahl" $statisticsoutput .= "<td> </td><td align='center'>$stddev</td><td> </td></tr>"; break; default: break; } } } if($outputType=='pdf') //XXX TODO PDF { //$tablePDF = array(); $tablePDF = array_merge_recursive($tablePDF, $footPDF); $pdf->headTable($headPDF,$tablePDF); //$pdf->tableintopdf($tablePDF); // if(isset($footPDF)) // foreach($footPDF as $foot) // { // $footA = array($foot); // $pdf->tablehead($footA); // } } //-------------------------- PCHART OUTPUT ---------------------------- //PCHART has to be enabled and we need some data if ($usegraph==1 && array_sum($gdata)>0) { $graph = ""; $p1 = ""; // $statisticsoutput .= "<pre>"; // $statisticsoutput .= "GDATA:\n"; // print_r($gdata); // $statisticsoutput .= "GRAWDATA\n"; // print_r($grawdata); // $statisticsoutput .= "LABEL\n"; // print_r($label); // $statisticsoutput .= "JUSTCODE\n"; // print_r($justcode); // $statisticsoutput .= "LBL\n"; // print_r($lbl); // $statisticsoutput .= "</pre>"; //First, lets delete any earlier graphs from the tmp directory //$gdata and $lbl are arrays built at the end of the last section //that contain the values, and labels for the data we are about //to send to pchart. $i = 0; foreach ($gdata as $data) { if ($data != 0){$i++;} } $totallines=$i; if ($totallines>15) { $gheight=320+(6.7*($totallines-15)); $fontsize=7; $legendtop=0.01; $setcentrey=0.5/(($gheight/320)); } else { $gheight=320; $fontsize=8; $legendtop=0.07; $setcentrey=0.5; } // Create bar chart for Multiple choice if ($qtype == "M" || $qtype == "P") { //new bar chart using data from array $grawdata which contains percentage $DataSet = new pData; $counter=0; $maxyvalue=0; foreach ($grawdata as $datapoint) { $DataSet->AddPoint(array($datapoint),"Serie$counter"); $DataSet->AddSerie("Serie$counter"); $counter++; if ($datapoint>$maxyvalue) $maxyvalue=$datapoint; } if ($maxyvalue<10) {++$maxyvalue;} $counter=0; foreach ($lbl as $label) { $DataSet->SetSerieName($label,"Serie$counter"); $counter++; } if ($MyCache->IsInCache("graph".$surveyid,$DataSet->GetData())) { $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData())); } else { $graph = new pChart(1,1); $graph->setFontProperties($rootdir."/fonts/".$chartfontfile, $chartfontsize); $legendsize=$graph->getLegendBoxSize($DataSet->GetDataDescription()); if ($legendsize[1]<320) $gheight=420; else $gheight=$legendsize[1]+100; $graph = new pChart(690+$legendsize[0],$gheight); $graph->loadColorPalette($homedir.'/styles/'.$admintheme.'/limesurvey.pal'); $graph->setFontProperties($rootdir."/fonts/".$chartfontfile,$chartfontsize); $graph->setGraphArea(50,30,500,$gheight-60); $graph->drawFilledRoundedRectangle(7,7,523+$legendsize[0],$gheight-7,5,254,255,254); $graph->drawRoundedRectangle(5,5,525+$legendsize[0],$gheight-5,5,230,230,230); $graph->drawGraphArea(255,255,255,TRUE); $graph->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,150,150,150,TRUE,90,0,TRUE,5,false); $graph->drawGrid(4,TRUE,230,230,230,50); // Draw the 0 line $graph->setFontProperties($rootdir."/fonts/".$chartfontfile,$chartfontsize); $graph->drawTreshold(0,143,55,72,TRUE,TRUE); // Draw the bar graph $graph->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),FALSE); //$Test->setLabel($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie4","1","Important point!"); // Finish the graph $graph->setFontProperties($rootdir."/fonts/".$chartfontfile, $chartfontsize); $graph->drawLegend(510,30,$DataSet->GetDataDescription(),255,255,255); $MyCache->WriteToCache("graph".$surveyid,$DataSet->GetData(),$graph); $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData())); unset($graph); } } //end if (bar chart) //Pie Chart else { // this block is to remove the items with value == 0 $i = 0; while (isset ($gdata[$i])) { if ($gdata[$i] == 0) { array_splice ($gdata, $i, 1); array_splice ($lbl, $i, 1); } else {$i++;} } $lblout=array(); if ($language=='ar') { $lblout=$lbl; //reset text order to original include_once($rootdir.'/classes/core/Arabic.php'); $Arabic = new Arabic('ArGlyphs'); foreach($lblout as $kkey => $kval){ if (preg_match("^[A-Za-z]^", $kval)) { //auto detect if english //eng //no reversing } else{ $kval = $Arabic->utf8Glyphs($kval,50,false); $lblout[$kkey] = $kval; } } } elseif (getLanguageRTL($language)) { $lblout=$lblrtl; } else { $lblout=$lbl; } //create new 3D pie chart if ($usegraph==1) { $DataSet = new pData; $DataSet->AddPoint($gdata,"Serie1"); $DataSet->AddPoint($lblout,"Serie2"); $DataSet->AddAllSeries(); $DataSet->SetAbsciseLabelSerie("Serie2"); if ($MyCache->IsInCache("graph".$surveyid,$DataSet->GetData())) { $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData())); } else { $gheight=ceil($gheight); $graph = new pChart(690,$gheight); $graph->loadColorPalette($homedir.'/styles/'.$admintheme.'/limesurvey.pal'); $graph->drawFilledRoundedRectangle(7,7,687,$gheight-3,5,254,255,254); $graph->drawRoundedRectangle(5,5,689,$gheight-1,5,230,230,230); // Draw the pie chart $graph->setFontProperties($rootdir."/fonts/".$chartfontfile, $chartfontsize); $graph->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),225,round($gheight/2),170,PIE_PERCENTAGE,TRUE,50,20,5); $graph->setFontProperties($rootdir."/fonts/".$chartfontfile,$chartfontsize); $graph->drawPieLegend(430,12,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250); $MyCache->WriteToCache("graph".$surveyid,$DataSet->GetData(),$graph); $cachefilename=basename($MyCache->GetFileFromCache("graph".$surveyid,$DataSet->GetData())); unset($graph); } //print_r($DataSet->GetData()); echo "<br/><br/>"; } } //end else -> pie charts //introduce new counter if (!isset($ci)) {$ci=0;} //increase counter, start value -> 1 $ci++; switch($outputType) { case 'xls': /** * No Image for Excel... */ break; case 'pdf': $pdf->AddPage('P','A4'); $pdf->titleintopdf($pdfTitle,$titleDesc); $pdf->Image($tempdir."/".$cachefilename, 0, 70, 180, 0, '', $homeurl."/admin.php?sid=$surveyid", 'B', true, 150,'C',false,false,0,true); break; case 'html': $statisticsoutput .= "<tr><td colspan='4' style=\"text-align:center\"><img src=\"$tempurl/".$cachefilename."\" border='1' /></td></tr>"; break; default: break; } } //close table/output if($outputType=='html') $statisticsoutput .= "</table><br /> \n"; } //end if -> collect and display results //delete data unset($gdata); unset($grawdata); unset($label); unset($lbl); unset($lblrtl); unset($lblout); unset($justcode); unset ($alist); } // end foreach -> loop through all questions //output if($outputType=='html') $statisticsoutput .= "<br /> \n"; } //end if -> show summary results switch($outputType) { case 'xls': //$workbook-> $workbook->close(); if($pdfOutput=='F') { return $sFileName; } else { return; } break; case 'pdf': $pdf->lastPage(); if($pdfOutput=='F') { // This is only used by lsrc to send an E-Mail attachment, so it gives back the filename to send and delete afterwards $pdf->Output($tempdir."/".$statlang->gT('Survey').'_'.$surveyid."_".$surveyInfo['surveyls_title'].'.pdf', $pdfOutput); return $tempdir."/".$statlang->gT('Survey').'_'.$surveyid."_".$surveyInfo['surveyls_title'].'.pdf'; } else return $pdf->Output($statlang->gT('Survey').'_'.$surveyid."_".$surveyInfo['surveyls_title'].'.pdf', $pdfOutput); break; case 'html': return $statisticsoutput; break; default: return $statisticsoutput; break; } }
$count = $result->RecordCount(); //loop through all answers. if there are 3 items to rate there will be 3 statistics for ($i=1; $i<=$count; $i++) { $myfield2 = "R" . $myfield . $i . "-" . strlen($i); $allfields[]=$myfield2; } break; //Boilerplate questions are only used to put some text between other questions -> no analysis needed case "X": //This is a boilerplate question and it has no business in this script break; case "1": // MULTI SCALE //get answers $query = "SELECT title, question FROM ".db_table_name("questions")." WHERE parent_qid='$flt[0]' AND language='{$language}' ORDER BY question_order"; $result = db_execute_num($query) or safe_die ("Couldn't get answers!<br />$query<br />".$connect->ErrorMsg()); //loop through answers while ($row=$result->FetchRow()) { //----------------- LABEL 1 --------------------- $myfield2 = $myfield . "$row[0]#0"; $allfields[]=$myfield2; //----------------- LABEL 2 --------------------- $myfield2 = $myfield . "$row[0]#1"; $allfields[]=$myfield2; } //end WHILE -> loop through all answers break; case "P": //P - Multiple choice with comments case "M": //M - Multiple choice
function savedcontrol() { //This data will be saved to the "saved_control" table with one row per response. // - a unique "saved_id" value (autoincremented) // - the "sid" for this survey // - the "srid" for the survey_x row id // - "saved_thisstep" which is the step the user is up to in this survey // - "saved_ip" which is the ip address of the submitter // - "saved_date" which is the date ofthe saved response // - an "identifier" which is like a username // - a "password" // - "fieldname" which is the fieldname of the saved response // - "value" which is the value of the response //We start by generating the first 5 values which are consistent for all rows. global $connect, $surveyid, $dbprefix, $thissurvey, $errormsg, $publicurl, $sitename, $timeadjust, $clang, $clienttoken, $thisstep; //Check that the required fields have been completed. $errormsg = ""; if (!isset($_POST['savename']) || !$_POST['savename']) { $errormsg .= $clang->gT("You must supply a name for this saved session.") . "<br />\n"; } if (!isset($_POST['savepass']) || !$_POST['savepass']) { $errormsg .= $clang->gT("You must supply a password for this saved session.") . "<br />\n"; } if (isset($_POST['savepass']) && !isset($_POST['savepass2']) || $_POST['savepass'] != $_POST['savepass2']) { $errormsg .= $clang->gT("Your passwords do not match.") . "<br />\n"; } // if security question asnwer is incorrect if (function_exists("ImageCreate") && captcha_enabled('saveandloadscreen', $thissurvey['usecaptcha'])) { if (!isset($_POST['loadsecurity']) || !isset($_SESSION['secanswer']) || $_POST['loadsecurity'] != $_SESSION['secanswer']) { $errormsg .= $clang->gT("The answer to the security question is incorrect.") . "<br />\n"; } } if ($errormsg) { return; } //All the fields are correct. Now make sure there's not already a matching saved item $query = "SELECT COUNT(*) FROM {$dbprefix}saved_control\n" . "WHERE sid={$surveyid}\n" . "AND identifier=" . db_quoteall($_POST['savename'], true); $result = db_execute_num($query) or safe_die("Error checking for duplicates!<br />{$query}<br />" . $connect->ErrorMsg()); // Checked list($count) = $result->FetchRow(); if ($count > 0) { $errormsg .= $clang->gT("This name has already been used for this survey. You must use a unique save name.") . "<br />\n"; return; } else { //INSERT BLANK RECORD INTO "survey_x" if one doesn't already exist if (!isset($_SESSION['srid'])) { $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust); $sdata = array("datestamp" => $today, "ipaddr" => $_SERVER['REMOTE_ADDR'], "startlanguage" => $_SESSION['s_lang'], "refurl" => getenv("HTTP_REFERER")); //One of the strengths of ADOdb's AutoExecute() is that only valid field names for $table are updated if ($connect->AutoExecute($thissurvey['tablename'], $sdata, 'INSERT')) { $srid = $connect->Insert_ID($thissurvey['tablename'], "sid"); $_SESSION['srid'] = $srid; } else { safe_die("Unable to insert record into survey table.<br /><br />" . $connect->ErrorMsg()); } } //CREATE ENTRY INTO "saved_control" $today = date_shift(date("Y-m-d H:i:s"), "Y-m-d H:i:s", $timeadjust); $scdata = array("sid" => $surveyid, "srid" => $_SESSION['srid'], "identifier" => $_POST['savename'], "access_code" => md5($_POST['savepass']), "email" => $_POST['saveemail'], "ip" => $_SERVER['REMOTE_ADDR'], "refurl" => getenv("HTTP_REFERER"), "saved_thisstep" => $thisstep, "status" => "S", "saved_date" => $today); if ($connect->AutoExecute("{$dbprefix}saved_control", $scdata, 'INSERT')) { $scid = $connect->Insert_ID("{$dbprefix}saved_control", 'scid'); $_SESSION['scid'] = $scid; } else { safe_die("Unable to insert record into saved_control table.<br /><br />" . $connect->ErrorMsg()); } $_SESSION['holdname'] = $_POST['savename']; //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output $_SESSION['holdpass'] = $_POST['savepass']; //Session variable used to load answers every page. Unsafe - so it has to be taken care of on output //Email if needed if (isset($_POST['saveemail'])) { if (validate_email($_POST['saveemail'])) { $subject = $clang->gT("Saved Survey Details") . " - " . $thissurvey['name']; $message = $clang->gT("Thank you for saving your survey in progress. The following details can be used to return to this survey and continue where you left off. Please keep this e-mail for your reference - we cannot retrieve the password for you.", "unescaped"); $message .= "\n\n" . $thissurvey['name'] . "\n\n"; $message .= $clang->gT("Name", "unescaped") . ": " . $_POST['savename'] . "\n"; $message .= $clang->gT("Password", "unescaped") . ": " . $_POST['savepass'] . "\n\n"; $message .= $clang->gT("Reload your survey by clicking on the following link (or pasting it into your browser):", "unescaped") . ":\n"; $message .= $publicurl . "/index.php?sid={$surveyid}&loadall=reload&scid=" . $scid . "&loadname=" . urlencode($_POST['savename']) . "&loadpass="******"&token=" . $clienttoken; } $from = "{$thissurvey['adminname']} <{$thissurvey['adminemail']}>"; if (SendEmailMessage($message, $subject, $_POST['saveemail'], $from, $sitename, false, getBounceEmail($surveyid))) { $emailsent = "Y"; } else { echo "Error: Email failed, this may indicate a PHP Mail Setup problem on your server. Your survey details have still been saved, however you will not get an email with the details. You should note the \"name\" and \"password\" you just used for future reference."; } } } return $clang->gT('Your survey was successfully saved.'); } }
."' onclick=\"window.open('{$scriptname}?action=tokens&sid={$surveyid}&subaction=edit&tid=".$brow['tid']."&start={$start}&limit={$limit}&order={$order}', '_top')\" /> "; } if (bHasSurveyPermission($surveyid, 'tokens','delete')) { $tokenoutput .="<input style='height: 16; width: 16px; font-size: 8; font-family: verdana' type='image' src='{$imageurl}/token_delete.png' title='" .$clang->gT("Delete token entry") ."' alt='" .$clang->gT("Delete token entry") ."' onclick=\"if (confirm('".$clang->gT("Are you sure you want to delete this entry?","js")." (".$brow['tid'].")')) {".get2post("$scriptname?action=tokens&sid=$surveyid&subaction=delete&tid=".$brow['tid']."&limit=$limit&start=$start&order=$order")."}\" />"; } if ($brow['completed'] != "N" && $brow['completed']!="" && $surveyprivate == "N" && $thissurvey['active']=='Y') { // Get response Id $query="SELECT id FROM ".db_table_name('survey_'.$surveyid)." WHERE token='{$brow['token']}' ORDER BY id desc"; $result=db_execute_num($query) or safe_die ("<br />Could not find token!<br />\n" .$connect->ErrorMsg()); list($id) = $result->FetchRow(); // UPDATE button to the tokens display in the MPID Actions column if ($id) { $tokenoutput .= "<input type='image' src='{$imageurl}/token_viewanswer.png' style='height: 16; width: 16px;' onclick=\"window.open('$scriptname?action=browse&sid=$surveyid&subaction=id&id=$id', '_top')\" title='" .$clang->gT("View/Update last response") ."' alt='" .$clang->gT("View/Update last response") ."' />\n"; } } elseif ($brow['completed'] == "N" && $brow['token'] && $brow['sent'] == "N" && trim($brow['email'])!='' && bHasSurveyPermission($surveyid, 'tokens','update')) { $tokenoutput .= "<input style='height: 16; width: 16px; font-size: 8; font-family: verdana' type='image' src='{$imageurl}/token_invite.png' title='"
/** * This function builds all the required session variables when a survey is first started and * it loads any answer defaults from command line or from the table defaultvalues * It is called from the related format script (group.php, question.php, survey.php) * if the survey has just started. * * @returns $totalquestions Total number of questions in the survey * */ function buildsurveysession() { global $thissurvey, $secerror, $clienttoken; global $tokensexist, $thistpl; global $surveyid, $dbprefix, $connect; global $register_errormsg, $clang; global $totalBoilerplatequestions; global $templang, $move, $rooturl, $publicurl; if (!isset($templang) || $templang == '') { $templang = $thissurvey['language']; } $totalBoilerplatequestions = 0; // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS if ($tokensexist == 0 && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET if (!isset($_GET['loadsecurity']) || !isset($_SESSION['secanswer']) || $_GET['loadsecurity'] != $_SESSION['secanswer']) { sendcacheheaders(); doHeader(); // No or bad answer to required security question echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); //echo makedropdownlist(); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); if (isset($_GET['loadsecurity'])) { // was a bad answer echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />"; } echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>\n\t\t\t <form class='captcha' method='get' action='{$publicurl}/index.php'>\n\t\t\t <table align='center'>\n\t\t\t\t <tr>\n\t\t\t\t\t <td align='right' valign='middle'>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; // In case we this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n\t\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "\n\t\t\t\t </td>\n\t\t\t </tr>"; if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<tr>\n\t\t\t\t <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /></td>\n <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n\t\t\t\t </td>\n\t\t\t </tr>"; } echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n\t\t </table>\n\t\t </form>"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED! // TOKEN REQUIRED BUT NO TOKEN PROVIDED if ($tokensexist == 1 && !returnglobal('token')) { // DISPLAY REGISTER-PAGE if needed // DISPLAY CAPTCHA if needed sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); //echo makedropdownlist(); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents("{$thistpl}/register.pstpl")); } else { if (isset($secerror)) { echo "<span class='error'>" . $secerror . "</span><br />"; } echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />"; echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <script type='text/javascript'>var focus_element='#token';</script>\n\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n\n <ul>\n <li>\n <label for='token'>" . $clang->gT("Token") . "</label><input class='text' id='token' type='text' name='token' />\n <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t<input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['newtest']) && ($_GET['newtest'] = "Y")) { echo " <input type='hidden' name='newtest' value='Y' id='newtest' />"; } // If this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "</li>"; if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n\t\t\t <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n\t\t </li>"; } echo "<li>\n <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n </li>\n </ul>\n\t </form></div>"; } echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } elseif ($tokensexist == 1 && returnglobal('token') && !captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { //check if token actually does exist $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' AND (completed = 'N' or completed='')"; $tkresult = db_execute_num($tkquery); //Checked list($tkexist) = $tkresult->FetchRow(); if (!$tkexist) { //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT killSession(); sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br />\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS CORRECT if (isset($_GET['loadsecurity']) && isset($_SESSION['secanswer']) && $_GET['loadsecurity'] == $_SESSION['secanswer']) { //check if token actually does exist $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "' AND (completed = 'N' or completed='')"; $tkresult = db_execute_num($tkquery); //Checked list($tkexist) = $tkresult->FetchRow(); if (!$tkexist) { sendcacheheaders(); doHeader(); //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo "\t<center><br />\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/>\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } else { if (!isset($move) || is_null($move)) { $gettoken = $clienttoken; sendcacheheaders(); doHeader(); // No or bad answer to required security question echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); // If token wasn't provided and public registration // is enabled then show registration form if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents("{$thistpl}/register.pstpl")); } else { // only show CAPTCHA echo '<div id="wrapper"><p id="tokenmessage">'; if (isset($_GET['loadsecurity'])) { // was a bad answer echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />"; } echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />"; // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT // AND HIDE ENTRY FIELD if (!isset($gettoken)) { echo $clang->gT("If you have been issued with a token, please enter it in the box below and click continue.") . "</p>\n\t\t\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n <li>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id=token name='token'></li>"; } else { echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n\t\t\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n\t\t\t <li>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token:") . "</label><span id=token>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>"; } if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n\t\t </ul>\n\t\t </form>\n\t\t </id>"; } echo '</div>' . templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } } //RESET ALL THE SESSION VARIABLES AND START AGAIN unset($_SESSION['grouplist']); unset($_SESSION['fieldarray']); unset($_SESSION['insertarray']); unset($_SESSION['thistoken']); unset($_SESSION['fieldnamesInfo']); $_SESSION['fieldnamesInfo'] = array(); //RL: multilingual support if (isset($_GET['token']) && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) { //get language from token (if one exists) $tkquery2 = "SELECT * FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote($clienttoken) . "' AND (completed = 'N' or completed='')"; //echo $tkquery2; $result = db_execute_assoc($tkquery2) or safe_die("Couldn't get tokens<br />{$tkquery}<br />" . $connect->ErrorMsg()); //Checked while ($rw = $result->FetchRow()) { $tklanguage = $rw['language']; } } if (returnglobal('lang')) { $language_to_set = returnglobal('lang'); } elseif (isset($tklanguage)) { $language_to_set = $tklanguage; } else { $language_to_set = $thissurvey['language']; } if (!isset($_SESSION['s_lang'])) { SetSurveyLanguage($surveyid, $language_to_set); } UpdateSessionGroupList($_SESSION['s_lang']); // Optimized Query // Change query to use sub-select to see if conditions exist. $query = "SELECT " . db_table_name('questions') . ".*, " . db_table_name('groups') . ".*,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".qid) AS hasconditions,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".cqid) AS usedinconditions\n" . " FROM " . db_table_name('groups') . " INNER JOIN " . db_table_name('questions') . " ON " . db_table_name('groups') . ".gid = " . db_table_name('questions') . ".gid\n" . " WHERE " . db_table_name('questions') . ".sid=" . $surveyid . "\n" . " AND " . db_table_name('groups') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".parent_qid=0\n" . " ORDER BY " . db_table_name('groups') . ".group_order," . db_table_name('questions') . ".question_order"; //var_dump($_SESSION); $result = db_execute_assoc($query); //Checked $arows = $result->GetRows(); $totalquestions = $result->RecordCount(); //2. SESSION VARIABLE: totalsteps //The number of "pages" that will be presented in this survey //The number of pages to be presented will differ depending on the survey format switch ($thissurvey['format']) { case "A": $_SESSION['totalsteps'] = 1; break; case "G": if (isset($_SESSION['grouplist'])) { $_SESSION['totalsteps'] = count($_SESSION['grouplist']); } break; case "S": $_SESSION['totalsteps'] = $totalquestions; } if ($totalquestions == "0") { sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo "\t<center><br />\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } //Perform a case insensitive natural sort on group name then question title of a multidimensional array // usort($arows, 'GroupOrderThenQuestionOrder'); //3. SESSION VARIABLE - insertarray //An array containing information about used to insert the data into the db at the submit stage //4. SESSION VARIABLE - fieldarray //See rem at end.. $_SESSION['token'] = $clienttoken; if ($thissurvey['private'] == "N") { $_SESSION['insertarray'][] = "token"; } if ($tokensexist == 1 && $thissurvey['private'] == "N" && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) { //Gather survey data for "non anonymous" surveys, for use in presenting questions $_SESSION['thistoken'] = getTokenData($surveyid, $clienttoken); } $qtypes = getqtypelist('', 'array'); $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['s_lang']); $_SESSION['fieldmap'] = $fieldmap; foreach ($fieldmap as $field) { if ($field['qid'] != '') { $_SESSION['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']; $_SESSION['insertarray'][] = $field['fieldname']; //fieldarray ARRAY CONTENTS - // [0]=questions.qid, // [1]=fieldname, // [2]=questions.title, // [3]=questions.question // [4]=questions.type, // [5]=questions.gid, // [6]=questions.mandatory, // [7]=conditionsexist, // [8]=usedinconditions if (!isset($_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) { $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $field['title'], $field['question'], $field['type'], $field['gid'], $field['mandatory'], $field['hasconditions'], $field['usedinconditions']); } } } // Prefill question/answer from defaultvalues foreach ($fieldmap as $field) { if (isset($field['defaultvalue'])) { $_SESSION[$field['fieldname']] = $field['defaultvalue']; } } // Prefill questions/answers from command line params if (isset($_SESSION['insertarray'])) { foreach ($_SESSION['insertarray'] as $field) { if (isset($_GET[$field]) && $field != 'token') { $_SESSION[$field] = $_GET[$field]; } } } $_SESSION['fieldarray'] = array_values($_SESSION['fieldarray']); // Check if the current survey language is set - if not set it // this way it can be changed later (for example by a special question type) //Check if a passthru label and value have been included in the query url if (isset($_GET['passthru']) && $_GET['passthru'] != "") { if (isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "") { $_SESSION['passthrulabel'] = $_GET['passthru']; $_SESSION['passthruvalue'] = $_GET[$_GET['passthru']]; } } return $totalquestions; }
$sec = $median % 60; $browseoutput .= '<tr><Th>' . $clang->gT('Median: ') . "</th><td>{$min} min. {$sec} sec.</td></tr>"; } $browseoutput .= '</table>'; } elseif ($subaction == "time") { $browseoutput .= $surveyoptions; $browseoutput .= "<div class='header ui-widget-header'>" . $clang->gT("Timings") . "</div>"; $browseoutput .= "Timing saving is disabled or the timing table does not exist. Try to reactivate survey.\n"; } else { $browseoutput .= $surveyoptions; $num_total_answers = 0; $num_completed_answers = 0; $gnquery = "SELECT count(id) FROM {$surveytable}"; $gnquery2 = "SELECT count(id) FROM {$surveytable} WHERE submitdate IS NOT NULL"; $gnresult = db_execute_num($gnquery); $gnresult2 = db_execute_num($gnquery2); while ($gnrow = $gnresult->FetchRow()) { $num_total_answers = $gnrow[0]; } while ($gnrow2 = $gnresult2->FetchRow()) { $num_completed_answers = $gnrow2[0]; } $browseoutput .= "<div class='header ui-widget-header'>" . $clang->gT("Response summary") . "</div>" . "<p><table class='statisticssummary'>\n" . "<tfoot><tr><th>" . $clang->gT("Total responses:") . "</th><td>" . $num_total_answers . "</td></tr></tfoot>" . "\t<tbody>" . "<tr><th>" . $clang->gT("Full responses:") . "</th><td>" . $num_completed_answers . "</td></tr>" . "<tr><th>" . $clang->gT("Incomplete responses:") . "</th><td>" . ($num_total_answers - $num_completed_answers) . "</td></tr></tbody>" . "</table>"; } /** * Supply an array with the responseIds and all files will be added to the zip * and it will be be spit out on success * * @param array $responseIds * @return ZipArchive */
{$showQuestion} }); \$(document).bind('keydown',function(e) { if (e.keyCode == 9) { {$showQuestion} return true; } return true; }); // --> </script> EOD; $answer = $answers[0][1]; //GET HELP $hquery = "SELECT help FROM {$dbprefix}questions WHERE qid={$ia['0']} AND language='" . $_SESSION['s_lang'] . "'"; $hresult = db_execute_num($hquery) or safe_die($connect->ErrorMsg()); //Checked $help = ""; while ($hrow = $hresult->FetchRow()) { $help = $hrow[0]; } $question = $answers[0][0]; $question['code'] = $answers[0][5]; $question['class'] = question_class($qrows['type']); $question['essentials'] = 'id="question' . $qrows['qid'] . '"'; $question['sgq'] = $ia[1]; $question['aid'] = 'unknown'; $question['sqid'] = 'unknown'; $question['type'] = $qrows['type']; if ($qrows['mandatory'] == 'Y') { $question['man_class'] = ' mandatory';
function datadump($table) { global $connect; $result = "#\n"; $result .= "# Table data for {$table}" . "\n"; $result .= "#\n"; $query = db_execute_num("select * from {$table}"); $num_fields = $query->FieldCount(); $aFieldNames = $connect->MetaColumnNames($table, true); $sFieldNames = implode('`,`', $aFieldNames); $numrow = $query->RecordCount(); if ($numrow > 0) { $result .= "INSERT INTO `{$table}` (`{$sFieldNames}`) VALUES"; while ($row = $query->FetchRow()) { @set_time_limit(5); $result .= "("; for ($j = 0; $j < $num_fields; $j++) { if (isset($row[$j]) && !is_null($row[$j])) { $row[$j] = addslashes($row[$j]); $row[$j] = preg_replace("#\n#", "\\n", $row[$j]); $result .= "\"{$row[$j]}\""; } else { $result .= "NULL"; } if ($j < $num_fields - 1) { $result .= ","; } } $result .= "),\n"; } // while $result = substr($result, 0, -2); } return $result . ";\n\n"; }
/** * Retrieves the token attribute value from the related token table * * @param mixed $surveyid The survey ID * @param mixed $attrName The token-attribute field name * @param mixed $token The token code * @return string The token attribute value (or null on error) */ function GetAttributeValue($surveyid, $attrName, $token) { global $dbprefix, $connect; $attrName = strtolower($attrName); if ($attrName == 'callattempts' || $attrName == 'onappointment' || $attrName == 'perccomplete' || $attrName == 'messagesleft') { include_once "quexs.php"; $quexs_operator_id = get_operator_id(); $quexs_case_id = get_case_id($quexs_operator_id); if ($quexs_case_id) { if ($attrName == 'callattempts') { return get_call_attempts($quexs_case_id); } else { if ($attrName == 'onappointment') { return is_on_appointment($quexs_case_id, $quexs_operator_id); } else { if ($attrName == 'perccomplete') { return get_percent_complete($quexs_case_id); } else { if ($attrName == 'messagesleft') { return get_messages_left($quexs_case_id); } } } } } else { return 0; } } else { if (!tableExists('tokens_' . $surveyid) || !in_array($attrName, GetTokenConditionsFieldNames($surveyid))) { return null; } } $sanitized_token = $connect->qstr($token, get_magic_quotes_gpc()); $surveyid = sanitize_int($surveyid); $query = "SELECT {$attrName} FROM {$dbprefix}tokens_{$surveyid} WHERE token={$sanitized_token}"; $result = db_execute_num($query); $count = $result->RecordCount(); if ($count != 1) { return null; } else { $row = $result->FetchRow(); return $row[0]; } }
/** * This function builds all the required session variables when a survey is first started and * it loads any answer defaults from command line or from the table defaultvalues * It is called from the related format script (group.php, question.php, survey.php) * if the survey has just started. * * @returns $totalquestions Total number of questions in the survey * */ function buildsurveysession() { global $thissurvey, $secerror, $clienttoken, $databasetype; global $tokensexist, $thistpl; global $surveyid, $dbprefix, $connect; global $register_errormsg, $clang; global $totalBoilerplatequestions; global $templang, $move, $rooturl, $publicurl; if (!isset($templang) || $templang == '') { $templang = $thissurvey['language']; } $totalBoilerplatequestions = 0; $loadsecurity = returnglobal('loadsecurity'); // NO TOKEN REQUIRED BUT CAPTCHA ENABLED FOR SURVEY ACCESS if ($tokensexist == 0 && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS NOT CORRECT OR NOT SET if (!isset($loadsecurity) || !isset($_SESSION['secanswer']) || $loadsecurity != $_SESSION['secanswer']) { sendcacheheaders(); doHeader(); // No or bad answer to required security question echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); //echo makedropdownlist(); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); if (isset($loadsecurity)) { // was a bad answer echo "<font color='#FF0000'>" . $clang->gT("The answer to the security question is incorrect.") . "</font><br />"; } echo "<p class='captcha'>" . $clang->gT("Please confirm access to survey by answering the security question below and click continue.") . "</p>\n\t\t\t <form class='captcha' method='get' action='{$publicurl}/index.php'>\n\t\t\t <table align='center'>\n\t\t\t\t <tr>\n\t\t\t\t\t <td align='right' valign='middle'>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; // In case we this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n\t\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "\n\t\t\t\t </td>\n\t\t\t </tr>"; if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<tr>\n\t\t\t\t <td align='center' valign='middle'><label for='captcha'>" . $clang->gT("Security question:") . "</label></td><td align='left' valign='middle'><table><tr><td valign='middle'><img src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /></td>\n <td valign='middle'><input id='captcha' type='text' size='5' maxlength='3' name='loadsecurity' value='' /></td></tr></table>\n\t\t\t\t </td>\n\t\t\t </tr>"; } echo "<tr><td colspan='2' align='center'><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></td></tr>\n\t\t </table>\n\t\t </form>"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } //BEFORE BUILDING A NEW SESSION FOR THIS SURVEY, LET'S CHECK TO MAKE SURE THE SURVEY SHOULD PROCEED! // TOKEN REQUIRED BUT NO TOKEN PROVIDED if ($tokensexist == 1 && !returnglobal('token')) { if ($thissurvey['nokeyboard'] == 'Y') { vIncludeKeypad(); $kpclass = "text-keypad"; } else { $kpclass = ""; } // DISPLAY REGISTER-PAGE if needed // DISPLAY CAPTCHA if needed sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); //echo makedropdownlist(); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); if (isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents("{$thistpl}/register.pstpl")); } else { if (isset($secerror)) { echo "<span class='error'>" . $secerror . "</span><br />"; } echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br />"; echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n <script type='text/javascript'>var focus_element='#token';</script>\n\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n <li>\n <label for='token'>" . $clang->gT("Token") . "</label><input class='text {$kpclass}' id='token' type='text' name='token' />"; echo "<input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t<input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['newtest']) && $_GET['newtest'] == "Y") { echo " <input type='hidden' name='newtest' value='Y' id='newtest' />"; } // If this is a direct Reload previous answers URL, then add hidden fields if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "\n\t\t\t\t\t<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t<input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t<input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t<input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo "</li>"; if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n\t\t\t <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n\t\t </li>"; } echo "<li>\n <input class='submit' type='submit' value='" . $clang->gT("Continue") . "' />\n </li>\n </ul>\n\t </form></div>"; } echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } elseif ($tokensexist == 1 && returnglobal('token') && !captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { //check if tokens actually haven't been already used $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token'))))); //check if token actually does exist // check also if it is allowed to change survey after completion if ($thissurvey['alloweditaftercompletion'] == 'Y') { $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' "; } else { $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(strip_tags(returnglobal('token')))) . "' AND (completed = 'N' or completed='')"; } $tkresult = db_execute_num($tkquery); //Checked list($tkexist) = $tkresult->FetchRow(); if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') { //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT killSession(); sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo '<div id="wrapper"><p id="tokenmessage">' . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)</p></div>\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } elseif ($tokensexist == 1 && returnglobal('token') && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { // IF CAPTCHA ANSWER IS CORRECT if (isset($loadsecurity) && isset($_SESSION['secanswer']) && $loadsecurity == $_SESSION['secanswer']) { //check if tokens actually haven't been already used $areTokensUsed = usedTokens(db_quote(trim(strip_tags(returnglobal('token'))))); //check if token actually does exist if ($thissurvey['alloweditaftercompletion'] == 'Y') { $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "'"; } else { $tkquery = "SELECT COUNT(*) FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote(trim(sanitize_xss_string(strip_tags(returnglobal('token'))))) . "' AND (completed = 'N' or completed='')"; } $tkresult = db_execute_num($tkquery); //Checked list($tkexist) = $tkresult->FetchRow(); if (!$tkexist || $areTokensUsed && $thissurvey['alloweditaftercompletion'] != 'Y') { sendcacheheaders(); doHeader(); //TOKEN DOESN'T EXIST OR HAS ALREADY BEEN USED. EXPLAIN PROBLEM AND EXIT echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />\n" . "\t" . $clang->gT("The token you have provided is either not valid, or has already been used.") . "<br/>\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } } else { if (!isset($move) || is_null($move)) { $gettoken = $clienttoken; sendcacheheaders(); doHeader(); // No or bad answer to required security question echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); // If token wasn't provided and public registration // is enabled then show registration form if (!isset($gettoken) && isset($thissurvey) && $thissurvey['allowregister'] == "Y") { echo templatereplace(file_get_contents("{$thistpl}/register.pstpl")); } else { // only show CAPTCHA echo '<div id="wrapper"><p id="tokenmessage">'; if (isset($loadsecurity)) { // was a bad answer echo "<span class='error'>" . $clang->gT("The answer to the security question is incorrect.") . "</span><br />"; } echo $clang->gT("This is a controlled survey. You need a valid token to participate.") . "<br /><br />"; // IF TOKEN HAS BEEN GIVEN THEN AUTOFILL IT // AND HIDE ENTRY FIELD if (!isset($gettoken)) { echo $clang->gT("If you have been issued a token, please enter it in the box below and click continue.") . "</p>\n\t\t\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n <li>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n\t\t\t\t\t\t <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n\t\t\t\t\t\t <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n\t\t\t\t\t\t <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token") . "</label><input class='text' type='text' id='token' name='token'></li>"; } else { echo $clang->gT("Please confirm the token by answering the security question below and click continue.") . "</p>\n\t\t\t <form id='tokenform' method='get' action='{$publicurl}/index.php'>\n <ul>\n\t\t\t <li>\n\t\t\t\t\t <input type='hidden' name='sid' value='" . $surveyid . "' id='sid' />\n\t\t\t\t\t\t <input type='hidden' name='lang' value='" . $templang . "' id='lang' />"; if (isset($_GET['loadall']) && isset($_GET['scid']) && isset($_GET['loadname']) && isset($_GET['loadpass'])) { echo "<input type='hidden' name='loadall' value='" . htmlspecialchars($_GET['loadall']) . "' id='loadall' />\n <input type='hidden' name='scid' value='" . returnglobal('scid') . "' id='scid' />\n <input type='hidden' name='loadname' value='" . htmlspecialchars($_GET['loadname']) . "' id='loadname' />\n <input type='hidden' name='loadpass' value='" . htmlspecialchars($_GET['loadpass']) . "' id='loadpass' />"; } echo '<label for="token">' . $clang->gT("Token:") . "</label><span id='token'>{$gettoken}</span>" . "<input type='hidden' name='token' value='{$gettoken}'></li>"; } if (function_exists("ImageCreate") && captcha_enabled('surveyaccessscreen', $thissurvey['usecaptcha'])) { echo "<li>\n <label for='captchaimage'>" . $clang->gT("Security Question") . "</label><img id='captchaimage' src='{$rooturl}/verification.php?sid={$surveyid}' alt='captcha' /><input type='text' size='5' maxlength='3' name='loadsecurity' value='' />\n </li>"; } echo "<li><input class='submit' type='submit' value='" . $clang->gT("Continue") . "' /></li>\n\t\t </ul>\n\t\t </form>\n\t\t </id>"; } echo '</div>' . templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); unset($_SESSION['srid']); exit; } } } //RESET ALL THE SESSION VARIABLES AND START AGAIN unset($_SESSION['grouplist']); unset($_SESSION['fieldarray']); unset($_SESSION['insertarray']); unset($_SESSION['thistoken']); unset($_SESSION['fieldnamesInfo']); $_SESSION['fieldnamesInfo'] = array(); //RL: multilingual support if (isset($_GET['token']) && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) { //get language from token (if one exists) $tkquery2 = "SELECT * FROM " . db_table_name('tokens_' . $surveyid) . " WHERE token='" . db_quote($clienttoken) . "' AND (completed = 'N' or completed='')"; //echo $tkquery2; $result = db_execute_assoc($tkquery2) or safe_die("Couldn't get tokens<br />{$tkquery}<br />" . $connect->ErrorMsg()); //Checked while ($rw = $result->FetchRow()) { $tklanguage = $rw['language']; } } if (returnglobal('lang')) { $language_to_set = returnglobal('lang'); } elseif (isset($tklanguage)) { $language_to_set = $tklanguage; } else { $language_to_set = $thissurvey['language']; } if (!isset($_SESSION['s_lang'])) { SetSurveyLanguage($surveyid, $language_to_set); } UpdateSessionGroupList($_SESSION['s_lang']); // Optimized Query // Change query to use sub-select to see if conditions exist. $query = "SELECT " . db_table_name('questions') . ".*, " . db_table_name('groups') . ".*,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".qid) AS hasconditions,\n" . " (SELECT count(1) FROM " . db_table_name('conditions') . "\n" . " WHERE " . db_table_name('questions') . ".qid = " . db_table_name('conditions') . ".cqid) AS usedinconditions\n" . " FROM " . db_table_name('groups') . " INNER JOIN " . db_table_name('questions') . " ON " . db_table_name('groups') . ".gid = " . db_table_name('questions') . ".gid\n" . " WHERE " . db_table_name('questions') . ".sid=" . $surveyid . "\n" . " AND " . db_table_name('groups') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".language='" . $_SESSION['s_lang'] . "'\n" . " AND " . db_table_name('questions') . ".parent_qid=0\n" . " ORDER BY " . db_table_name('groups') . ".group_order," . db_table_name('questions') . ".question_order"; //var_dump($_SESSION); $result = db_execute_assoc($query); //Checked $arows = $result->GetRows(); $totalquestions = $result->RecordCount(); //2. SESSION VARIABLE: totalsteps //The number of "pages" that will be presented in this survey //The number of pages to be presented will differ depending on the survey format switch ($thissurvey['format']) { case "A": $_SESSION['totalsteps'] = 1; break; case "G": if (isset($_SESSION['grouplist'])) { $_SESSION['totalsteps'] = count($_SESSION['grouplist']); } break; case "S": $_SESSION['totalsteps'] = $totalquestions; } if ($totalquestions == "0") { sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents("{$thistpl}/startpage.pstpl")); echo templatereplace(file_get_contents("{$thistpl}/survey.pstpl")); echo "\t<div id='wrapper'>\n" . "\t<p id='tokenmessage'>\n" . "\t" . $clang->gT("This survey does not yet have any questions and cannot be tested or completed.") . "<br /><br />\n" . "\t" . sprintf($clang->gT("For further information please contact %s"), $thissurvey['adminname']) . " (<a href='mailto:{$thissurvey['adminemail']}'>" . "{$thissurvey['adminemail']}</a>)<br /><br />\n" . "\t</p>\n" . "\t</div>\n"; echo templatereplace(file_get_contents("{$thistpl}/endpage.pstpl")); doFooter(); exit; } //Perform a case insensitive natural sort on group name then question title of a multidimensional array // usort($arows, 'GroupOrderThenQuestionOrder'); //3. SESSION VARIABLE - insertarray //An array containing information about used to insert the data into the db at the submit stage //4. SESSION VARIABLE - fieldarray //See rem at end.. $_SESSION['token'] = $clienttoken; if ($thissurvey['anonymized'] == "N") { $_SESSION['insertarray'][] = "token"; } if ($tokensexist == 1 && $thissurvey['anonymized'] == "N" && db_tables_exist($dbprefix . 'tokens_' . $surveyid)) { //Gather survey data for "non anonymous" surveys, for use in presenting questions $_SESSION['thistoken'] = getTokenData($surveyid, $clienttoken); } $qtypes = getqtypelist('', 'array'); $fieldmap = createFieldMap($surveyid, 'full', false, false, $_SESSION['s_lang']); // Randomization Groups // Find all defined randomization groups through question attribute values $randomGroups = array(); if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative') { $rgquery = "SELECT attr.qid, CAST(value as varchar(255)) FROM " . db_table_name('question_attributes') . " as attr right join " . db_table_name('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))"; } else { $rgquery = "SELECT attr.qid, value FROM " . db_table_name('question_attributes') . " as attr right join " . db_table_name('questions') . " as quests on attr.qid=quests.qid WHERE attribute='random_group' and value <> '' and sid={$surveyid} GROUP BY attr.qid, value"; } $rgresult = db_execute_assoc($rgquery); while ($rgrow = $rgresult->FetchRow()) { // Get the question IDs for each randomization group $randomGroups[$rgrow['value']][] = $rgrow['qid']; } // If we have randomization groups set, then lets cycle through each group and // replace questions in the group with a randomly chosen one from the same group if (count($randomGroups) > 0) { $copyFieldMap = array(); $oldQuestOrder = array(); $newQuestOrder = array(); $randGroupNames = array(); foreach ($randomGroups as $key => $value) { $oldQuestOrder[$key] = $randomGroups[$key]; $newQuestOrder[$key] = $oldQuestOrder[$key]; // We shuffle the question list to get a random key->qid which will be used to swap from the old key shuffle($newQuestOrder[$key]); $randGroupNames[] = $key; } // Loop through the fieldmap and swap each question as they come up while (list($fieldkey, $fieldval) = each($fieldmap)) { $found = 0; foreach ($randomGroups as $gkey => $gval) { // We found a qid that is in the randomization group if (isset($fieldval['qid']) && in_array($fieldval['qid'], $oldQuestOrder[$gkey])) { // Get the swapped question $oldQuestFlip = array_flip($oldQuestOrder[$gkey]); $qfieldmap = createFieldMap($surveyid, 'full', true, $newQuestOrder[$gkey][$oldQuestFlip[$fieldval['qid']]], $_SESSION['s_lang']); unset($qfieldmap['id']); unset($qfieldmap['submitdate']); unset($qfieldmap['lastpage']); unset($qfieldmap['lastpage']); unset($qfieldmap['token']); foreach ($qfieldmap as $tkey => $tval) { // Assign the swapped question (Might be more than one field) $tval['random_gid'] = $fieldval['gid']; //$tval['gid'] = $fieldval['gid']; $copyFieldMap[$tkey] = $tval; } $found = 1; break; } else { $found = 2; } } if ($found == 2) { $copyFieldMap[$fieldkey] = $fieldval; } reset($randomGroups); } $fieldmap = $copyFieldMap; } //die(print_r($fieldmap)); $_SESSION['fieldmap'] = $fieldmap; foreach ($fieldmap as $field) { if (isset($field['qid']) && $field['qid'] != '') { $_SESSION['fieldnamesInfo'][$field['fieldname']] = $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']; $_SESSION['insertarray'][] = $field['fieldname']; //fieldarray ARRAY CONTENTS - // [0]=questions.qid, // [1]=fieldname, // [2]=questions.title, // [3]=questions.question // [4]=questions.type, // [5]=questions.gid, // [6]=questions.mandatory, // [7]=conditionsexist, // [8]=usedinconditions // [8]=usedinconditions // [9]=used in group.php for question count // [10]=new group id for question in randomization group (GroupbyGroup Mode) if (!isset($_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']])) { $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']] = array($field['qid'], $field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid'], $field['title'], $field['question'], $field['type'], $field['gid'], $field['mandatory'], $field['hasconditions'], $field['usedinconditions']); } if (isset($field['random_gid'])) { $_SESSION['fieldarray'][$field['sid'] . 'X' . $field['gid'] . 'X' . $field['qid']][10] = $field['random_gid']; } } } // Prefill question/answer from defaultvalues foreach ($fieldmap as $field) { if (isset($field['defaultvalue'])) { $_SESSION[$field['fieldname']] = $field['defaultvalue']; } } // Prefill questions/answers from command line params if (isset($_SESSION['insertarray'])) { foreach ($_SESSION['insertarray'] as $field) { if (isset($_GET[$field]) && $field != 'token') { $_SESSION[$field] = $_GET[$field]; } } } if (isset($_SESSION['fieldarray'])) { $_SESSION['fieldarray'] = array_values($_SESSION['fieldarray']); } // Check if the current survey language is set - if not set it // this way it can be changed later (for example by a special question type) //Check if a passthru label and value have been included in the query url if (isset($_GET['passthru']) && $_GET['passthru'] != "") { if (isset($_GET[$_GET['passthru']]) && $_GET[$_GET['passthru']] != "") { $_SESSION['passthrulabel'] = $_GET['passthru']; $_SESSION['passthruvalue'] = $_GET[$_GET['passthru']]; } } elseif (isset($_SERVER['QUERY_STRING'])) { $_SESSION['ls_initialquerystr'] = $_SERVER['QUERY_STRING']; } // END NEW // Fix totalquestions by substracting Test Display questions $sNoOfTextDisplayQuestions = (int) $connect->GetOne("SELECT count(*)\n" . " FROM " . db_table_name('questions') . " WHERE type='X'\n" . " AND sid={$surveyid}" . " AND language='" . $_SESSION['s_lang'] . "'" . " AND parent_qid=0"); $_SESSION['therearexquestions'] = $totalquestions - $sNoOfTextDisplayQuestions; // must be global for THEREAREXQUESTIONS replacement field to work return $totalquestions - $sNoOfTextDisplayQuestions; }
/** * This function imports an old-school question file (*.csv,*.sql) * * @param mixed $sFullFilepath Full file patch to the import file * @param mixed $newsid Survey ID to which the question is attached * @param mixed $newgid Group ID top which the question is attached */ function CSVImportQuestion($sFullFilepath, $newsid, $newgid) { global $dbprefix, $connect, $clang; $aLIDReplacements = array(); $aQIDReplacements = array(); // this array will have the "new qid" for the questions, the key will be the "old qid" $aSQIDReplacements = array(); $results['labelsets'] = 0; $results['labels'] = 0; $handle = fopen($sFullFilepath, "r"); while (!feof($handle)) { $buffer = fgets($handle); //To allow for very long survey welcomes (up to 10k) $bigarray[] = $buffer; } fclose($handle); $importversion = 0; // Now we try to determine the dataformat of the survey file. if (substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP") { $importversion = 100; // version 1.0 or 0.99 file } elseif (substr($bigarray[0], 0, 26) == "# LimeSurvey Question Dump" || substr($bigarray[0], 0, 27) == "# PHPSurveyor Question Dump") { // This is a >1.0 version file - these files carry the version information to read in line two $importversion = (int) substr($bigarray[1], 12, 3); } else { $results['fatalerror'] = $clang->gT("This file is not a LimeSurvey question file. Import failed."); return $results; } if ((int) $importversion < 112) { $results['fatalerror'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported."); return $results; } for ($i = 0; $i < 9; $i++) { unset($bigarray[$i]); } $bigarray = array_values($bigarray); //QUESTIONS if (array_search("# ANSWERS TABLE\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); } elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $questionarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //ANSWERS if (array_search("# LABELSETS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); } elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $answerarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LABELSETS if (array_search("# LABELS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\n", $bigarray); } elseif (array_search("# LABELS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $labelsetsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LABELS if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); } elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $labelsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //Question_attributes $stoppoint = count($bigarray); for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 1) { $question_attributesarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); if (isset($questionarray)) { $questionfieldnames = convertCSVRowToArray($questionarray[0], ',', '"'); unset($questionarray[0]); $countquestions = count($questionarray) - 1; } else { $countquestions = 0; } if (isset($answerarray)) { $answerfieldnames = convertCSVRowToArray($answerarray[0], ',', '"'); unset($answerarray[0]); $countanswers = count($answerarray); } else { $countanswers = 0; } if (isset($labelsetsarray)) { $countlabelsets = count($labelsetsarray) - 1; } else { $countlabelsets = 0; } if (isset($labelsarray)) { $countlabels = count($labelsarray) - 1; } else { $countlabels = 0; } if (isset($question_attributesarray)) { $countquestion_attributes = count($question_attributesarray) - 1; } else { $countquestion_attributes = 0; } $aLanguagesSupported = array(); // this array will keep all the languages supported for the survey $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid); $aLanguagesSupported[] = $sBaseLanguage; // adds the base language to the list of supported languages $aLanguagesSupported = array_merge($aLanguagesSupported, GetAdditionalLanguagesFromSurveyID($newsid)); // Let's check that imported objects support at least the survey's baselang if (isset($questionarray)) { $langfieldnum = array_search("language", $questionfieldnames); $qidfieldnum = array_search("qid", $questionfieldnames); $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray, array($qidfieldnum), $langfieldnum, $sBaseLanguage, true); if (!$questionssupportbaselang) { $results['fatalerror'] = $clang->gT("You can't import a question which doesn't support at least the survey base language."); return $results; } } if ($countanswers > 0) { $langfieldnum = array_search("language", $answerfieldnames); $answercodefilednum1 = array_search("qid", $answerfieldnames); $answercodefilednum2 = array_search("code", $answerfieldnames); $answercodekeysarr = array($answercodefilednum1, $answercodefilednum2); $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray, $answercodekeysarr, $langfieldnum, $sBaseLanguage); if (!$answerssupportbaselang) { $results['fatalerror'] = $clang->gT("You can't import answers which doesn't support at least the survey base language."); return $results; } } if ($countlabelsets > 0) { $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0], ',', '"'); $langfieldnum = array_search("languages", $labelsetfieldname); $lidfilednum = array_search("lid", $labelsetfieldname); $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray, array($lidfilednum), $langfieldnum, $sBaseLanguage, true); if (!$labelsetssupportbaselang) { $results['fatalerror'] = $clang->gT("You can't import label sets which don't support the current survey's base language"); return $results; } } // I assume that if a labelset supports the survey's baselang, // then it's labels do support it as well //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS if (isset($labelsetsarray) && $labelsetsarray) { $csarray = buildLabelSetCheckSumArray(); // build checksums over all existing labelsets $count = 0; foreach ($labelsetsarray as $lsa) { $fieldorders = convertCSVRowToArray($labelsetsarray[0], ',', '"'); $fieldcontents = convertCSVRowToArray($lsa, ',', '"'); if ($count == 0) { $count++; continue; } $results['labelsets']++; $labelsetrowdata = array_combine($fieldorders, $fieldcontents); // Save old labelid $oldlid = $labelsetrowdata['lid']; // set the new language unset($labelsetrowdata['lid']); $newvalues = array_values($labelsetrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $lsainsert = "INSERT INTO {$dbprefix}labelsets (" . implode(',', array_keys($labelsetrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; //handle db prefix $lsiresult = $connect->Execute($lsainsert); // Get the new insert id for the labels inside this labelset $newlid = $connect->Insert_ID("{$dbprefix}labelsets", 'lid'); if ($labelsarray) { $count = 0; foreach ($labelsarray as $la) { $lfieldorders = convertCSVRowToArray($labelsarray[0], ',', '"'); $lfieldcontents = convertCSVRowToArray($la, ',', '"'); if ($count == 0) { $count++; continue; } // Combine into one array with keys and values since its easier to handle $labelrowdata = array_combine($lfieldorders, $lfieldcontents); $labellid = $labelrowdata['lid']; if ($importversion <= 132) { $labelrowdata["assessment_value"] = (int) $labelrowdata["code"]; } if ($labellid == $oldlid) { $labelrowdata['lid'] = $newlid; // translate internal links $labelrowdata['title'] = translink('label', $oldlid, $newlid, $labelrowdata['title']); $newvalues = array_values($labelrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $lainsert = "INSERT INTO {$dbprefix}labels (" . implode(',', array_keys($labelrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; //handle db prefix $liresult = $connect->Execute($lainsert); $results['labels']++; } } } //CHECK FOR DUPLICATE LABELSETS $thisset = ""; $query2 = "SELECT code, title, sortorder, language, assessment_value\n FROM {$dbprefix}labels\n WHERE lid=" . $newlid . "\n ORDER BY language, sortorder, code"; $result2 = db_execute_num($query2) or safe_die("Died querying labelset {$lid}<br />{$query2}<br />" . $connect->ErrorMsg()); while ($row2 = $result2->FetchRow()) { $thisset .= implode('.', $row2); } // while $newcs = dechex(crc32($thisset) * 1); unset($lsmatch); if (isset($csarray)) { foreach ($csarray as $key => $val) { if ($val == $newcs) { $lsmatch = $key; } } } if (isset($lsmatch)) { //There is a matching labelset. So, we will delete this one and refer //to the matched one. $query = "DELETE FROM {$dbprefix}labels WHERE lid={$newlid}"; $result = $connect->Execute($query) or safe_die("Couldn't delete labels<br />{$query}<br />" . $connect->ErrorMsg()); $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}"; $result = $connect->Execute($query) or safe_die("Couldn't delete labelset<br />{$query}<br />" . $connect->ErrorMsg()); $newlid = $lsmatch; } else { //There isn't a matching labelset, add this checksum to the $csarray array $csarray[$newlid] = $newcs; } //END CHECK FOR DUPLICATES $aLIDReplacements[$oldlid] = $newlid; } } // Import questions if (isset($questionarray) && $questionarray) { //Assuming we will only import one question at a time we will now find out the maximum question order in this group //and save it for later $newquestionorder = $connect->GetOne("SELECT MAX(question_order) AS maxqo FROM " . db_table_name('questions') . " WHERE sid={$newsid} AND gid={$newgid}"); if (is_null($newquestionorder)) { $newquestionorder = 0; } else { $newquestionorder++; } foreach ($questionarray as $qa) { $qacfieldcontents = convertCSVRowToArray($qa, ',', '"'); $questionrowdata = array_combine($questionfieldnames, $qacfieldcontents); // Skip not supported languages if (!in_array($questionrowdata['language'], $aLanguagesSupported)) { continue; } // replace the sid $oldqid = $questionrowdata['qid']; $oldsid = $questionrowdata['sid']; $oldgid = $questionrowdata['gid']; // Remove qid field if there is no newqid; and set it to newqid if it's set if (!isset($newqid)) { unset($questionrowdata['qid']); } else { db_switchIDInsert('questions', true); $questionrowdata['qid'] = $newqid; } $questionrowdata["sid"] = $newsid; $questionrowdata["gid"] = $newgid; $questionrowdata["question_order"] = $newquestionorder; // Save the following values - will need them for proper conversion later if ((int)$questionrowdata['lid']>0) if ((int) $questionrowdata['lid'] > 0) { $oldquestion['lid1'] = (int) $questionrowdata['lid']; } if ((int) $questionrowdata['lid1'] > 0) { $oldquestion['lid2'] = (int) $questionrowdata['lid1']; } $oldquestion['oldtype'] = $questionrowdata['type']; // Unset label set IDs and convert question types unset($questionrowdata['lid']); unset($questionrowdata['lid1']); if ($questionrowdata['type'] == 'W') { $questionrowdata['type'] = '!'; } elseif ($questionrowdata['type'] == 'Z') { $questionrowdata['type'] = 'L'; } $oldquestion['newtype'] = $questionrowdata['type']; $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata); // translate internal links $questionrowdata['title'] = translink('survey', $oldsid, $newsid, $questionrowdata['title']); $questionrowdata['question'] = translink('survey', $oldsid, $newsid, $questionrowdata['question']); $questionrowdata['help'] = translink('survey', $oldsid, $newsid, $questionrowdata['help']); $newvalues = array_values($questionrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $qinsert = "INSERT INTO {$dbprefix}questions (" . implode(',', array_keys($questionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $qres = $connect->Execute($qinsert) or safe_die("Error: Failed to insert question<br />\n{$qinsert}<br />\n" . $connect->ErrorMsg()); // set the newqid only if is not set if (!isset($newqid)) { $newqid = $connect->Insert_ID("{$dbprefix}questions", "qid"); } else { db_switchIDInsert('questions', false); } } $qtypes = getqtypelist("", "array"); $results['answers'] = 0; $results['subquestions'] = 0; // Now we will fix up old label sets where they are used as answers if ((isset($oldquestion['lid1']) || isset($oldquestion['lid2'])) && ($qtypes[$oldquestion['newtype']]['answerscales'] > 0 || $qtypes[$oldquestion['newtype']]['subquestions'] > 1)) { $query = "select * from " . db_table_name('labels') . " where lid={$aLIDReplacements[$oldquestion['lid1']]} "; $oldlabelsresult = db_execute_assoc($query); while ($labelrow = $oldlabelsresult->FetchRow()) { if (in_array($labelrow['language'], $aLanguagesSupported)) { if ($qtypes[$oldquestion['newtype']]['subquestions'] < 2) { $qinsert = "insert INTO " . db_table_name('answers') . " (qid,code,answer,sortorder,language,assessment_value,scale_id)\n VALUES ({$newqid}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . "," . db_quoteall($labelrow['assessment_value']) . ",0)"; $qres = $connect->Execute($qinsert) or safe_die("Error: Failed to insert answer <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg()); $results['answers']++; } else { if (isset($aSQIDReplacements[$labelrow['code']])) { $fieldname = 'qid,'; $data = $aSQIDReplacements[$labelrow['code']] . ','; db_switchIDInsert('questions', true); } else { $fieldname = ''; $data = ''; } $qinsert = "insert INTO " . db_table_name('questions') . " ({$fieldname} sid,gid,parent_qid,title,question,question_order,language,scale_id,type)\n VALUES ({$data} {$newsid},{$newgid},{$newqid}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . ",1," . db_quoteall($oldquestion['newtype']) . ")"; $qres = $connect->Execute($qinsert) or safe_die("Error: Failed to insert subquestion <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg()); if ($fieldname == '') { $aSQIDReplacements[$labelrow['code']] = $connect->Insert_ID("{$dbprefix}questions", "qid"); } else { db_switchIDInsert('questions', false); } } } } if (isset($oldquestion['lid2']) && $qtypes[$oldquestion['newtype']]['answerscales'] > 1) { $query = "select * from " . db_table_name('labels') . " where lid={$aLIDReplacements[$oldquestion['lid2']]}"; $oldlabelsresult = db_execute_assoc($query); while ($labelrow = $oldlabelsresult->FetchRow()) { if (in_array($labelrow['language'], $aLanguagesSupported)) { $qinsert = "insert INTO " . db_table_name('answers') . " (qid,code,answer,sortorder,language,assessment_value,scale_id)\n VALUES ({$newqid}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . "," . db_quoteall($labelrow['assessment_value']) . ",1)"; $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert answer <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg()); } } } } //Do answers if (isset($answerarray) && $answerarray) { foreach ($answerarray as $aa) { $answerfieldcontents = convertCSVRowToArray($aa, ',', '"'); $answerrowdata = array_combine($answerfieldnames, $answerfieldcontents); if ($answerrowdata === false) { $importquestion .= '<br />' . $clang->gT("Faulty line in import - fields and data don't match") . ":" . implode(',', $answerfieldcontents); } // Skip not supported languages if (!in_array($answerrowdata['language'], $aLanguagesSupported)) { continue; } $code = $answerrowdata["code"]; $thisqid = $answerrowdata["qid"]; $answerrowdata["qid"] = $newqid; if ($importversion <= 132) { $answerrowdata["assessment_value"] = (int) $answerrowdata["code"]; } // Convert default values for single select questions if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'L' || $oldquestion['newtype'] == 'O' || $oldquestion['newtype'] == '!')) { $insertdata = array(); $insertdata['qid'] = $newqid; $insertdata['language'] = $answerrowdata['language']; $insertdata['defaultvalue'] = $answerrowdata['answer']; $query = $connect->GetInsertSQL($dbprefix . 'defaultvalues', $insertdata); $qres = $connect->Execute($query) or safe_die("Error: Failed to insert defaultvalue <br />{$query}<br />\n" . $connect->ErrorMsg()); } // translate internal links $answerrowdata['answer'] = translink('survey', $oldsid, $newsid, $answerrowdata['answer']); // Everything set - now insert it $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata); if ($qtypes[$oldquestion['newtype']]['subquestions'] > 0) { $questionrowdata = array(); if (isset($aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']])) { $questionrowdata['qid'] = $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']]; db_switchIDInsert('questions', true); } $questionrowdata['parent_qid'] = $answerrowdata['qid']; $questionrowdata['sid'] = $newsid; $questionrowdata['gid'] = $newgid; $questionrowdata['title'] = $answerrowdata['code']; $questionrowdata['question'] = $answerrowdata['answer']; $questionrowdata['question_order'] = $answerrowdata['sortorder']; $questionrowdata['language'] = $answerrowdata['language']; $questionrowdata['type'] = $oldquestion['newtype']; $tablename = $dbprefix . 'questions'; $query = $connect->GetInsertSQL($tablename, $questionrowdata); $qres = $connect->Execute($query) or safe_die("Error: Failed to insert question <br />{$query}<br />\n" . $connect->ErrorMsg()); if (!isset($questionrowdata['qid'])) { $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']] = $connect->Insert_ID("{$dbprefix}questions", "qid"); } else { db_switchIDInsert('questions', false); } $results['subquestions']++; // also convert default values subquestions for multiple choice if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'M' || $oldquestion['newtype'] == 'P')) { $insertdata = array(); $insertdata['qid'] = $newqid; $insertdata['sqid'] = $aSQIDReplacements[$answerrowdata['code']]; $insertdata['language'] = $answerrowdata['language']; $insertdata['defaultvalue'] = 'Y'; $tablename = $dbprefix . 'defaultvalues'; $query = $connect->GetInsertSQL($tablename, $insertdata); $qres = $connect->Execute($query) or safe_die("Error: Failed to insert defaultvalue <br />{$query}<br />\n" . $connect->ErrorMsg()); } } else { unset($answerrowdata['default_value']); $tablename = $dbprefix . 'answers'; $query = $connect->GetInsertSQL($tablename, $answerrowdata); $ares = $connect->Execute($query) or safe_die("Error: Failed to insert answer<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['answers']++; } } } $results['question_attributes'] = 0; // Finally the question attributes - it is called just once and only if there was a question if (isset($question_attributesarray) && $question_attributesarray) { //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES $fieldorders = convertCSVRowToArray($question_attributesarray[0], ',', '"'); unset($question_attributesarray[0]); foreach ($question_attributesarray as $qar) { $fieldcontents = convertCSVRowToArray($qar, ',', '"'); $qarowdata = array_combine($fieldorders, $fieldcontents); $qarowdata["qid"] = $newqid; unset($qarowdata["qaid"]); $tablename = "{$dbprefix}question_attributes"; $qainsert = $connect->GetInsertSQL($tablename, $qarowdata); $result = $connect->Execute($qainsert) or safe_die("Couldn't insert question_attribute<br />{$qainsert}<br />" . $connect->ErrorMsg()); $results['question_attributes']++; } } } LimeExpressionManager::SetDirtyFlag(); // so refreshes syntax highlighting $results['newqid'] = $newqid; $results['questions'] = 1; $results['newqid'] = $newqid; return $results; }
function XMLImportLabelsets($sFullFilepath, $options) { global $connect, $dbprefix, $clang; $xml = simplexml_load_file($sFullFilepath); if ($xml->LimeSurveyDocType != 'Label set') { safe_die('This is not a valid LimeSurvey label set structure XML file.'); } $dbversion = (double) $xml->DBVersion; $csarray = buildLabelSetCheckSumArray(); $aLSIDReplacements = array(); $results['labelsets'] = 0; $results['labels'] = 0; $results['warnings'] = array(); // Import labels table =================================================================================== $tablename = $dbprefix . 'labelsets'; foreach ($xml->labelsets->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $oldlsid = $insertdata['lid']; unset($insertdata['lid']); // save the old qid // Insert the new question $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['labelsets']++; $newlsid = $connect->Insert_ID($tablename, "lid"); // save this for later $aLSIDReplacements[$oldlsid] = $newlsid; // add old and new lsid to the mapping array } // Import labels table =================================================================================== $tablename = $dbprefix . 'labels'; if (isset($xml->labels->rows->row)) { foreach ($xml->labels->rows->row as $row) { $insertdata = array(); foreach ($row as $key => $value) { $insertdata[(string) $key] = (string) $value; } $insertdata['lid'] = $aLSIDReplacements[$insertdata['lid']]; $query = $connect->GetInsertSQL($tablename, $insertdata); $result = $connect->Execute($query) or safe_die($clang->gT("Error") . ": Failed to insert data<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['labels']++; } } //CHECK FOR DUPLICATE LABELSETS if (isset($_POST['checkforduplicates'])) { foreach (array_values($aLSIDReplacements) as $newlid) { $thisset = ""; $query2 = "SELECT code, title, sortorder, language, assessment_value\n FROM " . db_table_name('labels') . "\n WHERE lid=" . $newlid . "\n ORDER BY language, sortorder, code"; $result2 = db_execute_num($query2) or safe_die("Died querying labelset {$lid}<br />{$query2}<br />" . $connect->ErrorMsg()); while ($row2 = $result2->FetchRow()) { $thisset .= implode('.', $row2); } // while $newcs = dechex(crc32($thisset) * 1); unset($lsmatch); if (isset($csarray) && $options['checkforduplicates'] == 'on') { foreach ($csarray as $key => $val) { if ($val == $newcs) { $lsmatch = $key; } } } if (isset($lsmatch)) { //There is a matching labelset. So, we will delete this one and refer //to the matched one. $query = "DELETE FROM {$dbprefix}labels WHERE lid={$newlid}"; $result = $connect->Execute($query) or safe_die("Couldn't delete labels<br />{$query}<br />" . $connect->ErrorMsg()); $results['labels'] = $results['labels'] - $connect->Affected_Rows(); $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}"; $result = $connect->Execute($query) or safe_die("Couldn't delete labelset<br />{$query}<br />" . $connect->ErrorMsg()); $results['labelsets']--; $newlid = $lsmatch; $results['warnings'][] = $clang->gT("Label set was not imported because the same label set already exists.") . " " . sprintf($clang->gT("Existing LID: %s"), $newlid); } } //END CHECK FOR DUPLICATES } return $results; }
/** * Function to activate a survey * @global $dbprefix $dbprefix * @global $connect $connect * @global $clang $clang * @param int $postsid * @param int $surveyid * @return string */ function activateSurvey($postsid, $surveyid, $scriptname = 'admin.php') { global $dbprefix, $connect, $clang, $databasetype, $databasetabletype, $uploaddir; $createsurvey = ''; $activateoutput = ''; $createsurveytimings = ''; $createsurveydirectory = false; //Check for any additional fields for this survey and create necessary fields (token and datestamp) $pquery = "SELECT anonymized, allowregister, datestamp, ipaddr, refurl, savetimings FROM {$dbprefix}surveys WHERE sid={$postsid}"; $presult = db_execute_assoc($pquery); $prow = $presult->FetchRow(); if ($prow['allowregister'] == "Y") { $surveyallowsregistration = "TRUE"; } if ($prow['savetimings'] == "Y") { $savetimings = "TRUE"; } //Get list of questions for the base language $fieldmap = createFieldMap($surveyid, 'full', true, false, GetBaseLanguageFromSurveyID($surveyid)); // createFieldMap($surveyid, $styl, $force_refresh,$questionid, $sQuestionLanguage); foreach ($fieldmap as $arow) { if ($createsurvey != '') { $createsurvey .= ",\n"; } $createsurvey .= ' `' . $arow['fieldname'] . '`'; switch ($arow['type']) { case 'startlanguage': $createsurvey .= " C(20) NOTNULL"; break; case 'id': $createsurvey .= " I NOTNULL AUTO PRIMARY"; $createsurveytimings .= " `{$arow['fieldname']}` I NOTNULL PRIMARY,\n"; break; case "startdate": case "datestamp": $createsurvey .= " T NOTNULL"; break; case "submitdate": $createsurvey .= " T"; break; case "lastpage": $createsurvey .= " I"; break; case "N": //NUMERICAL $createsurvey .= " F"; break; case "S": //SHORT TEXT if ($databasetype == 'mysql' || $databasetype == 'mysqli') { $createsurvey .= " X"; } else { $createsurvey .= " C(255)"; } break; case "L": //LIST (RADIO) //LIST (RADIO) case "!": //LIST (DROPDOWN) //LIST (DROPDOWN) case "M": //Multiple choice //Multiple choice case "P": //Multiple choice with comment //Multiple choice with comment case "O": //DROPDOWN LIST WITH COMMENT if ($arow['aid'] != 'other' && strpos($arow['aid'], 'comment') === false && strpos($arow['aid'], 'othercomment') === false) { $createsurvey .= " C(5)"; } else { $createsurvey .= " X"; } break; case "K": // Multiple Numerical $createsurvey .= " F"; break; case "U": //Huge text //Huge text case "Q": //Multiple short text //Multiple short text case "T": //LONG TEXT //LONG TEXT case ";": //Multi Flexi //Multi Flexi case ":": //Multi Flexi $createsurvey .= " X"; break; case "D": //DATE if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative') { $createsurvey .= " T"; } else { $createsurvey .= " D"; } break; case "5": //5 Point Choice //5 Point Choice case "G": //Gender //Gender case "Y": //YesNo //YesNo case "X": //Boilerplate $createsurvey .= " C(1)"; break; case "I": //Language switch $createsurvey .= " C(20)"; break; case "|": $createsurveydirectory = true; if (strpos($arow['fieldname'], "_")) { $createsurvey .= " I1"; } else { $createsurvey .= " X"; } break; case "ipaddress": if ($prow['ipaddr'] == "Y") { $createsurvey .= " X"; } break; case "url": if ($prow['refurl'] == "Y") { $createsurvey .= " X"; } break; case "token": if ($prow['anonymized'] == "N") { $createsurvey .= " C(36)"; } break; case '*': // Equation $createsurvey .= " X"; // could be anything, from numeric to a long message, so default to text break; default: $createsurvey .= " C(5)"; } } $timingsfieldmap = createTimingsFieldMap($surveyid); $createsurveytimings .= '`' . implode("` F DEFAULT '0',\n`", array_keys($timingsfieldmap)) . "` F DEFAULT '0'"; // If last question is of type MCABCEFHP^QKJR let's get rid of the ending coma in createsurvey $createsurvey = rtrim($createsurvey, ",\n") . "\n"; // Does nothing if not ending with a comma $tabname = "{$dbprefix}survey_{$postsid}"; # not using db_table_name as it quotes the table name (as does CreateTableSQL) $taboptarray = array('mysql' => 'ENGINE=' . $databasetabletype . ' CHARACTER SET utf8 COLLATE utf8_unicode_ci', 'mysqli' => 'ENGINE=' . $databasetabletype . ' CHARACTER SET utf8 COLLATE utf8_unicode_ci'); $dict = NewDataDictionary($connect); $sqlarray = $dict->CreateTableSQL($tabname, $createsurvey, $taboptarray); if (isset($savetimings) && $savetimings == "TRUE") { $tabnametimings = $tabname . '_timings'; $sqlarraytimings = $dict->CreateTableSQL($tabnametimings, $createsurveytimings, $taboptarray); } $execresult = $dict->ExecuteSQLArray($sqlarray, 1); //queXS Addition - add an index on the token $createtokenindex = $dict->CreateIndexSQL("{$tabname}_idx", $tabname, array('token')); $dict->ExecuteSQLArray($createtokenindex, false) or safe_die("Failed to create token index<br />{$createtokenindex}<br /><br />" . $connect->ErrorMsg()); if ($execresult == 0 || $execresult == 1) { $activateoutput .= "<br />\n<div class='messagebox ui-corner-all'>\n" . "<div class='header ui-widget-header'>" . $clang->gT("Activate Survey") . " ({$surveyid})</div>\n" . "<div class='warningheader'>" . $clang->gT("Survey could not be actived.") . "</div>\n" . "<p>" . $clang->gT("Database error:") . "\n <font color='red'>" . $connect->ErrorMsg() . "</font>\n" . "<pre>{$createsurvey}</pre>\n\n <a href='{$scriptname}?sid={$postsid}'>" . $clang->gT("Main Admin Screen") . "</a>\n</div>"; } if ($execresult != 0 && $execresult != 1) { $anquery = "SELECT autonumber_start FROM {$dbprefix}surveys WHERE sid={$postsid}"; if ($anresult = db_execute_assoc($anquery)) { //if there is an autonumber_start field, start auto numbering here while ($row = $anresult->FetchRow()) { if ($row['autonumber_start'] > 0) { if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative') { mssql_drop_primary_index('survey_' . $postsid); mssql_drop_constraint('id', 'survey_' . $postsid); $autonumberquery = "alter table {$dbprefix}survey_{$postsid} drop column id "; $connect->Execute($autonumberquery); $autonumberquery = "alter table {$dbprefix}survey_{$postsid} add [id] int identity({$row['autonumber_start']},1)"; $connect->Execute($autonumberquery); } else { $autonumberquery = "ALTER TABLE {$dbprefix}survey_{$postsid} AUTO_INCREMENT = " . $row['autonumber_start']; $result = @$connect->Execute($autonumberquery); } } } if (isset($savetimings) && $savetimings == "TRUE") { $dict->ExecuteSQLArray($sqlarraytimings, 1); // create a timings table for this survey } } $activateoutput .= "<br />\n<div class='messagebox ui-corner-all'>\n"; $activateoutput .= "<div class='header ui-widget-header'>" . $clang->gT("Activate Survey") . " ({$surveyid})</div>\n"; $activateoutput .= "<div class='successheader'>" . $clang->gT("Survey has been activated. Results table has been successfully created.") . "</div><br /><br />\n"; // create the survey directory where the uploaded files can be saved if ($createsurveydirectory) { if (!file_exists($uploaddir . "/surveys/" . $postsid . "/files")) { if (!mkdir($uploaddir . "/surveys/" . $postsid . "/files", 0777, true)) { $activateoutput .= "<div class='warningheader'>" . $clang->gT("The required directory for saving the uploaded files couldn't be created. Please check file premissions on the limesurvey/upload/surveys directory.") . "</div>"; } else { file_put_contents($uploaddir . "/surveys/" . $postsid . "/files/index.html", '<html><head></head><body></body></html>'); } } } $acquery = "UPDATE {$dbprefix}surveys SET active='Y' WHERE sid=" . $surveyid; $acresult = $connect->Execute($acquery); $query = db_select_tables_like("{$dbprefix}old\\_tokens\\_" . $surveyid . "\\_%"); $result = db_execute_num($query) or safe_die("Couldn't get old table list<br />" . $query . "<br />" . $connect->ErrorMsg()); $tcount = $result->RecordCount(); if ($tcount == 0) { $sTokenActivationLink = "{$scriptname}?action=tokens&sid={$postsid}&createtable=Y"; } else { $sTokenActivationLink = "{$scriptname}?action=tokens&sid={$postsid}"; } if (isset($surveyallowsregistration) && $surveyallowsregistration == "TRUE") { $activateoutput .= $clang->gT("This survey allows public registration. A token table must also be created.") . "<br /><br />\n"; $activateoutput .= "<input type='submit' value='" . $clang->gT("Initialise tokens") . "' onclick=\"" . get2post($sTokenActivationLink) . "\" />\n"; } else { $activateoutput .= $clang->gT("This survey is now active, and responses can be recorded.") . "<br /><br />\n"; //queXS Removal // $activateoutput .= "<strong>".$clang->gT("Open-access mode").":</strong> ".$clang->gT("No invitation code is needed to complete the survey.")."<br />".$clang->gT("You can switch to the closed-access mode by initialising a token table with the button below.")."<br /><br />\n"; // $activateoutput .= "<input type='submit' value='".$clang->gT("Switch to closed-access mode")."' onclick=\"".get2post($sTokenActivationLink)."\" />\n"; // $activateoutput .= "<input type='submit' value='".$clang->gT("No, thanks.")."' onclick=\"".get2post("$scriptname?sid={$postsid}")."\" />\n"; } $activateoutput .= "</div><br /> \n"; $lsrcOutput = true; } if ($scriptname == 'lsrc') { if ($lsrcOutput == true) { return true; } else { return $activateoutput; } } else { return $activateoutput; } }
$sOldTable = "survey_{$iSurveyID}"; $sNewTable = "old_survey_{$iSurveyID}_{$date}"; $deactivatequery = db_rename_table(db_table_name_nq($sOldTable), db_table_name_nq($sNewTable)); $deactivateresult = $connect->Execute($deactivatequery) or die("Couldn't make backup of the survey table. Please try again. The database reported the following error:<br />" . htmlspecialchars($connect->ErrorMsg()) . "<br />"); if ($databasetype == 'postgres') { // If you deactivate a postgres table you have to rename the according sequence too and alter the id field to point to the changed sequence $deactivatequery = db_rename_table($sOldTable . '_id_seq', $sNewTable . '_id_seq'); $deactivateresult = $connect->Execute($deactivatequery) or die("Couldn't make backup of the survey table. Please try again. The database reported the following error:<br />" . htmlspecialchars($connect->ErrorMsg()) . "<br /><br />Survey was not deactivated either.<br /><br /><a href='{$scriptname}?sid={$postsid}'>" . $clang->gT("Main Admin Screen") . "</a>"); $setsequence = "ALTER TABLE {$sNewTable} ALTER COLUMN id SET DEFAULT nextval('{$sNewTable}_id_seq'::regclass);"; $deactivateresult = $connect->Execute($setsequence) or die("Couldn't make backup of the survey table. Please try again. The database reported the following error:<br />" . htmlspecialchars($connect->ErrorMsg()) . "<br /><br />Survey was not deactivated either.<br /><br /><a href='{$scriptname}?sid={$postsid}'>" . $clang->gT("Main Admin Screen") . "</a>"); } } } /***** Check for activate token tables with missing survey entry **/ $sQuery = db_select_tables_like("{$dbprefix}tokens\\_%"); $aResult = db_execute_num($sQuery) or safe_die("Couldn't get list of token tables from database<br />{$query}<br />" . $connect->ErrorMsg()); while ($aRow = $aResult->FetchRow()) { $tablename = substr($aRow[0], strlen($dbprefix)); $iSurveyID = substr($tablename, strpos($tablename, '_') + 1); $qquery = "SELECT sid FROM {$dbprefix}surveys WHERE sid='{$iSurveyID}'"; $qresult = $connect->Execute($qquery) or safe_die("Couldn't check survey table for sid<br />{$qquery}<br />" . $connect->ErrorMsg()); $qcount = $qresult->RecordCount(); if ($qcount == 0) { $date = date('YmdHis') . rand(1, 1000); $sOldTable = "tokens_{$iSurveyID}"; $sNewTable = "old_tokens_{$iSurveyID}_{$date}"; $deactivatequery = db_rename_table(db_table_name_nq($sOldTable), db_table_name_nq($sNewTable)); if ($databasetype == 'postgres') { // If you deactivate a postgres table you have to rename the according sequence too and alter the id field to point to the changed sequence $sOldTableJur = db_table_name_nq($sOldTable); $deactivatequery = db_rename_table(db_table_name_nq($sOldTable), db_table_name_nq($sNewTable) . '_tid_seq');
/** * This function returns an array containing the "question/answer" html display * and a list of the question/answer fieldnames associated. It is called from * question.php, group.php or survey.php * * @param mixed $ia * @param mixed $notanswered * @param mixed $notvalidated * @param mixed $filenotvalidated * @return mixed */ function retrieveAnswers($ia, $notanswered=null, $notvalidated=null, $filenotvalidated=null) { //globalise required config variables global $dbprefix, $clang; //These are from the config-defaults.php file global $thissurvey, $gl; //These are set by index.php global $connect; //DISPLAY $display = $ia[7]; //QUESTION NAME $name = $ia[0]; $qtitle=$ia[3]; //Replace INSERTANS statements with previously provided answers; $qtitle=dTexts::run($qtitle); //GET HELP $hquery="SELECT help FROM {$dbprefix}questions WHERE qid=$ia[0] AND language='".$_SESSION['s_lang']."'"; $hresult=db_execute_num($hquery) or safe_die($connect->ErrorMsg()); //Checked $help=""; while ($hrow=$hresult->FetchRow()) {$help=$hrow[0];} //A bit of housekeeping to stop PHP Notices $answer = ""; if (!isset($_SESSION[$ia[1]])) {$_SESSION[$ia[1]] = "";} $qidattributes=getQuestionAttributes($ia[0],$ia[4]); //echo "<pre>";print_r($qidattributes);echo "</pre>"; //Create the question/answer html // Previously in limesurvey, it was virtually impossible to control how the start of questions were formatted. // this is an attempt to allow users (or rather system admins) some control over how the starting text is formatted. $number = isset($ia[9]) ? $ia[9] : ''; $question_text = array( 'all' => '' // All has been added for backwards compatibility with templates that use question_start.pstpl (now redundant) ,'text' => $qtitle ,'code' => $ia[2] ,'number' => $number ,'help' => '' ,'mandatory' => '' ,'man_message' => '' ,'valid_message' => '' ,'file_valid_message' => '' ,'class' => '' ,'man_class' => '' ,'input_error_class' => ''// provides a class. ,'essentials' => '' ); switch ($ia[4]) { case 'X': //BOILERPLATE QUESTION $values = do_boilerplate($ia); break; case '5': //5 POINT CHOICE radio-buttons $values = do_5pointchoice($ia); break; case 'D': //DATE $values = do_date($ia); break; case 'L': //LIST drop-down/radio-button list $values = do_list_radio($ia); if ($qidattributes['hide_tip']==0) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Choose one of the following answers').'</span>'; $question_text['help'] = $clang->gT('Choose one of the following answers'); } break; case '!': //List - dropdown $values=do_list_dropdown($ia); if ($qidattributes['hide_tip']==0) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Choose one of the following answers').'</span>'; $question_text['help'] = $clang->gT('Choose one of the following answers'); } break; case 'O': //LIST WITH COMMENT drop-down/radio-button list + textarea $values=do_listwithcomment($ia); if (count($values[1]) > 1 && $qidattributes['hide_tip']==0) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Choose one of the following answers').'</span>'; $question_text['help'] = $clang->gT('Choose one of the following answers'); } break; case 'R': //RANKING STYLE $values=do_ranking($ia); if (count($values[1]) > 1 && $qidattributes['hide_tip']==0) { $question_text['help'] = $clang->gT("Click on an item in the list on the left, starting with your highest ranking item, moving through to your lowest ranking item."); if (trim($qidattributes['min_answers'])!='') { $qtitle .= "<br />\n<span class=\"questionhelp\">" . sprintf($clang->ngT("Check at least %d item","Check at least %d items",$qidattributes['min_answers']),$qidattributes['min_answers'])."</span>"; $question_text['help'] .=' '.sprintf($clang->ngT("Check at least %d item","Check at least %d items",$qidattributes['min_answers']),$qidattributes['min_answers']); } } break; case 'M': //Multiple choice checkbox $values=do_multiplechoice($ia); if (count($values[1]) > 1 && $qidattributes['hide_tip']==0) { $maxansw=trim($qidattributes['max_answers']); $minansw=trim($qidattributes['min_answers']); if (!($maxansw || $minansw)) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Check any that apply').'</span>'; $question_text['help'] = $clang->gT('Check any that apply'); } else { if ($maxansw && $minansw) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw)."</span>"; $question_text['help'] = sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw); } elseif ($maxansw) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . sprintf($clang->gT("Check at most %d answers"), $maxansw)."</span>"; $question_text['help'] = sprintf($clang->gT("Check at most %d answers"), $maxansw); } else { $qtitle .= "<br />\n<span class=\"questionhelp\">" . sprintf($clang->ngT("Check at least %d answer","Check at least %d answers",$minansw),$minansw)."</span>"; $question_text['help'] = sprintf($clang->ngT("Check at least %d answer","Check at least %d answers",$minansw),$minansw); } } } break; case 'I': //Language Question $values=do_language($ia); if (count($values[1]) > 1) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Choose your language').'</span>'; $question_text['help'] = $clang->gT('Choose your language'); } break; case 'P': //Multiple choice with comments checkbox + text $values=do_multiplechoice_withcomments($ia); if (count($values[1]) > 1 && $qidattributes['hide_tip']==0) { $maxansw=trim($qidattributes["max_answers"]); $minansw=trim($qidattributes["min_answers"]); if (!($maxansw || $minansw)) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . $clang->gT('Check any that apply').'</span>'; $question_text['help'] = $clang->gT('Check any that apply'); } else { if ($maxansw && $minansw) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw)."</span>"; $question_text['help'] = sprintf($clang->gT("Check between %d and %d answers"), $minansw, $maxansw); } elseif ($maxansw) { $qtitle .= "<br />\n<span class=\"questionhelp\">" . sprintf($clang->gT("Check at most %d answers"), $maxansw)."</span>"; $question_text['help'] = sprintf($clang->gT("Check at most %d answers"), $maxansw); } else { $qtitle .= "<br />\n<span class=\"questionhelp\">" . sprintf($clang->gT("Check at least %d answers"), $minansw)."</span>"; $question_text['help'] = sprintf($clang->gT("Check at least %d answers"), $minansw); } } } break; case '|': //File Upload $values=do_file_upload($ia); if ($qidattributes['min_num_of_files'] != 0) { if (trim($qidattributes['min_num_of_files']) != 0) { $qtitle .= "<br />\n<span class = \"questionhelp\">" .sprintf($clang->gT("At least %d files must be uploaded for this question"), $qidattributes['min_num_of_files'])."<span>"; $question_text['help'] .= ' '.sprintf($clang->gT("At least %d files must be uploaded for this question"), $qidattributes['min_num_of_files']); } } break; case 'Q': //MULTIPLE SHORT TEXT $values=do_multipleshorttext($ia); break; case 'K': //MULTIPLE NUMERICAL QUESTION $values=do_multiplenumeric($ia); break; case 'N': //NUMERICAL QUESTION TYPE $values=do_numerical($ia); break; case 'S': //SHORT FREE TEXT $values=do_shortfreetext($ia); break; case 'T': //LONG FREE TEXT $values=do_longfreetext($ia); break; case 'U': //HUGE FREE TEXT $values=do_hugefreetext($ia); break; case 'Y': //YES/NO radio-buttons $values=do_yesno($ia); break; case 'G': //GENDER drop-down list $values=do_gender($ia); break; case 'A': //ARRAY (5 POINT CHOICE) radio-buttons $values=do_array_5point($ia); break; case 'B': //ARRAY (10 POINT CHOICE) radio-buttons $values=do_array_10point($ia); break; case 'C': //ARRAY (YES/UNCERTAIN/NO) radio-buttons $values=do_array_yesnouncertain($ia); break; case 'E': //ARRAY (Increase/Same/Decrease) radio-buttons $values=do_array_increasesamedecrease($ia); break; case 'F': //ARRAY (Flexible) - Row Format $values=do_array($ia); break; case 'H': //ARRAY (Flexible) - Column Format $values=do_arraycolumns($ia); break; case ':': //ARRAY (Multi Flexi) 1 to 10 $values=do_array_multiflexi($ia); break; case ';': //ARRAY (Multi Flexi) Text $values=do_array_multitext($ia); //It's like the "5th element" movie, come to life break; case '1': //Array (Flexible Labels) dual scale $values=do_array_dual($ia); break; } //End Switch if (isset($values)) //Break apart $values array returned from switch { //$answer is the html code to be printed //$inputnames is an array containing the names of each input field list($answer, $inputnames)=$values; } $answer .= "\n\t<input type='hidden' name='display$ia[1]' id='display$ia[0]' value='"; $answer .= 'on'; //If this is single format, then it must be showing. Needed for checking conditional mandatories $answer .= "' />\n"; //for conditional mandatory questions if ($ia[6] == 'Y') { $qtitle = '<span class="asterisk">'.$clang->gT('*').'</span>'.$qtitle; $question_text['mandatory'] = $clang->gT('*'); } //If this question is mandatory but wasn't answered in the last page //add a message HIGHLIGHTING the question $qtitle .= mandatory_message($ia); $question_text['man_message'] = mandatory_message($ia); $qtitle .= validation_message($ia); $question_text['valid_message'] = validation_message($ia); $qtitle .= $ia[4] == "|" ? file_validation_message($ia) : ""; $question_text['file_valid_message'] = $ia[4] == "|" ? file_validation_message($ia) : ""; if(!empty($question_text['man_message']) || !empty($question_text['valid_message']) || !empty($question_text['file_valid_message'])) { $question_text['input_error_class'] = ' input-error';// provides a class to style question wrapper differently if there is some kind of user input error; } // ===================================================== // START: legacy question_start.pstpl code // The following section adds to the templating system by allowing // templaters to control where the various parts of the question text // are put. if(is_file('templates/'.validate_templatedir($thissurvey['template']).'/question_start.pstpl')) { $qtitle_custom = ''; $replace=array(); foreach($question_text as $key => $value) { $find[] = '{QUESTION_'.strtoupper($key).'}'; // Match key words from template $replace[] = $value; // substitue text }; if(!defined('QUESTION_START')) { define('QUESTION_START' , file_get_contents(sGetTemplatePath($thissurvey['template']).'/question_start.pstpl' , true)); }; $qtitle_custom = str_replace( $find , $replace , QUESTION_START); $c = 1; // START: <EMBED> work-around step 1 $qtitle_custom = preg_replace( '/(<embed[^>]+>)(<\/embed>)/i' , '\1NOT_EMPTY\2' , $qtitle_custom ); // END <EMBED> work-around step 1 while($c > 0) // This recursively strips any empty tags to minimise rendering bugs. { $matches = 0; $oldtitle=$qtitle_custom; $qtitle_custom = preg_replace( '/<([^ >]+)[^>]*>[\r\n\t ]*<\/\1>[\r\n\t ]*/isU' , '' , $qtitle_custom , -1); // I removed the $count param because it is PHP 5.1 only. $c = ($qtitle_custom!=$oldtitle)?1:0; }; // START <EMBED> work-around step 2 $qtitle_custom = preg_replace( '/(<embed[^>]+>)NOT_EMPTY(<\/embed>)/i' , '\1\2' , $qtitle_custom ); // END <EMBED> work-around step 2 while($c > 0) // This recursively strips any empty tags to minimise rendering bugs. { $matches = 0; $oldtitle=$qtitle_custom; $qtitle_custom = preg_replace( '/(<br(?: ?\/)?>(?: |\r\n|\n\r|\r|\n| )*)+$/i' , '' , $qtitle_custom , -1 ); // I removed the $count param because it is PHP 5.1 only. $c = ($qtitle_custom!=$oldtitle)?1:0; }; // $qtitle = $qtitle_custom; $question_text['all'] = $qtitle_custom; } else { $question_text['all'] = $qtitle; }; // END: legacy question_start.pstpl code //=================================================================== // echo '<pre>[qanda.php] line '.__LINE__.": $question_text =\n".htmlspecialchars(print_r($question_text,true)).'</pre>'; $qtitle = $question_text; // ===================================================== $qanda=array($qtitle, $answer, $help, $display, $name, $ia[2], $gl[0], $ia[1] ); //New Return return array($qanda, $inputnames); }
/** * Function rewrites the sortorder for a label set * * @param mixed $lid Label set ID */ function fixorder($lid) { global $dbprefix, $connect, $labelsoutput; $qulabelset = "SELECT * FROM ".db_table_name('labelsets')." WHERE lid=$lid"; $rslabelset = db_execute_assoc($qulabelset) or safe_die($connect->ErrorMsg()); $rwlabelset=$rslabelset->FetchRow(); $lslanguages=explode(" ", trim($rwlabelset['languages'])); foreach ($lslanguages as $lslanguage) { $query = "SELECT lid, code, title, sortorder FROM ".db_table_name('labels')." WHERE lid=? and language=? ORDER BY sortorder, code"; $result = db_execute_num($query, array($lid,$lslanguage)) or safe_die("Can't read labels table: $query // (lid=$lid, language=$lslanguage) ".$connect->ErrorMsg()); $position=0; while ($row=$result->FetchRow()) { $position=sprintf("%05d", $position); $query2="UPDATE ".db_table_name('labels')." SET sortorder='$position' WHERE lid=? AND code=? AND title=? AND language='$lslanguage' "; $result2=$connect->Execute($query2, array ($row[0], $row[1], $row[2])) or safe_die ("Couldn't update sortorder<br />$query2<br />".$connect->ErrorMsg()); $position++; } } }
/** * This function imports an old-school question group file (*.csv,*.sql) * * @param mixed $sFullFilepath Full file patch to the import file * @param mixed $newsid Survey ID to which the question is attached */ function CSVImportGroup($sFullFilepath, $newsid) { global $dbprefix, $connect, $clang; $aLIDReplacements = array(); $aQIDReplacements = array(); // this array will have the "new qid" for the questions, the key will be the "old qid" $aGIDReplacements = array(); $handle = fopen($sFullFilepath, "r"); while (!feof($handle)) { $buffer = fgets($handle); $bigarray[] = $buffer; } fclose($handle); if (substr($bigarray[0], 0, 23) != "# LimeSurvey Group Dump") { $results['fatalerror'] = $clang->gT("This file is not a LimeSurvey question file. Import failed."); $importversion = 0; } else { $importversion = (int) trim(substr($bigarray[1], 12)); } if ((int) $importversion < 112) { $results['fatalerror'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported."); } for ($i = 0; $i < 9; $i++) { unset($bigarray[$i]); } $bigarray = array_values($bigarray); //GROUPS if (array_search("# QUESTIONS TABLE\n", $bigarray)) { $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray); } elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $grouparray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //QUESTIONS if (array_search("# ANSWERS TABLE\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); } elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $questionarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //ANSWERS if (array_search("# CONDITIONS TABLE\n", $bigarray)) { $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray); } elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]); } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //CONDITIONS if (array_search("# LABELSETS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); } elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $conditionsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LABELSETS if (array_search("# LABELS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\n", $bigarray); } elseif (array_search("# LABELS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $labelsetsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LABELS if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); } elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray) - 1; } for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i < $stoppoint - 2) { $labelsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //Question attributes if (!isset($noconditions) || $noconditions != "Y") { // stoppoint is the last line number // this is an empty line after the QA CSV lines $stoppoint = count($bigarray) - 1; for ($i = 0; $i <= $stoppoint + 1; $i++) { if ($i <= $stoppoint - 1) { $question_attributesarray[] = $bigarray[$i]; } unset($bigarray[$i]); } } $bigarray = array_values($bigarray); $countgroups = 0; if (isset($questionarray)) { $questionfieldnames = convertCSVRowToArray($questionarray[0], ',', '"'); unset($questionarray[0]); $countquestions = 0; } if (isset($answerarray)) { $answerfieldnames = convertCSVRowToArray($answerarray[0], ',', '"'); unset($answerarray[0]); $countanswers = count($answerarray); } else { $countanswers = 0; } $aLanguagesSupported = array(); // this array will keep all the languages supported for the survey $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid); $aLanguagesSupported[] = $sBaseLanguage; // adds the base language to the list of supported languages $aLanguagesSupported = array_merge($aLanguagesSupported, GetAdditionalLanguagesFromSurveyID($newsid)); // Let's check that imported objects support at least the survey's baselang $langcode = GetBaseLanguageFromSurveyID($newsid); if (isset($grouparray)) { $groupfieldnames = convertCSVRowToArray($grouparray[0], ',', '"'); $langfieldnum = array_search("language", $groupfieldnames); $gidfieldnum = array_search("gid", $groupfieldnames); $groupssupportbaselang = bDoesImportarraySupportsLanguage($grouparray, array($gidfieldnum), $langfieldnum, $sBaseLanguage, true); if (!$groupssupportbaselang) { $results['fatalerror'] = $clang->gT("You can't import a group which doesn't support at least the survey base language."); return $results; } } if (isset($questionarray)) { $langfieldnum = array_search("language", $questionfieldnames); $qidfieldnum = array_search("qid", $questionfieldnames); $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray, array($qidfieldnum), $langfieldnum, $sBaseLanguage, true); if (!$questionssupportbaselang) { $results['fatalerror'] = $clang->gT("You can't import a question which doesn't support at least the survey base language."); return $results; } } if ($countanswers > 0) { $langfieldnum = array_search("language", $answerfieldnames); $answercodefilednum1 = array_search("qid", $answerfieldnames); $answercodefilednum2 = array_search("code", $answerfieldnames); $answercodekeysarr = array($answercodefilednum1, $answercodefilednum2); $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray, $answercodekeysarr, $langfieldnum, $sBaseLanguage); if (!$answerssupportbaselang) { $results['fatalerror'] = $clang->gT("You can't import answers which doesn't support at least the survey base language."); return $results; } } if (count($labelsetsarray) > 1) { $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0], ',', '"'); $langfieldnum = array_search("languages", $labelsetfieldname); $lidfilednum = array_search("lid", $labelsetfieldname); $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray, array($lidfilednum), $langfieldnum, $sBaseLanguage, true); if (!$labelsetssupportbaselang) { $results['fatalerror'] = $clang->gT("You can't import label sets which don't support the current survey's base language"); return $results; } } // I assume that if a labelset supports the survey's baselang, // then it's labels do support it as well //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS $results['labelsets'] = 0; $qtypes = getqtypelist("", "array"); $results['labels'] = 0; $results['labelsets'] = 0; $results['answers'] = 0; $results['subquestions'] = 0; //Do label sets if (isset($labelsetsarray) && $labelsetsarray) { $csarray = buildLabelSetCheckSumArray(); // build checksums over all existing labelsets $count = 0; foreach ($labelsetsarray as $lsa) { $fieldorders = convertCSVRowToArray($labelsetsarray[0], ',', '"'); $fieldcontents = convertCSVRowToArray($lsa, ',', '"'); if ($count == 0) { $count++; continue; } $labelsetrowdata = array_combine($fieldorders, $fieldcontents); // Save old labelid $oldlid = $labelsetrowdata['lid']; unset($labelsetrowdata['lid']); $newvalues = array_values($labelsetrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $lsainsert = "INSERT INTO {$dbprefix}labelsets (" . implode(',', array_keys($labelsetrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; //handle db prefix $lsiresult = $connect->Execute($lsainsert); $results['labelsets']++; // Get the new insert id for the labels inside this labelset $newlid = $connect->Insert_ID("{$dbprefix}labelsets", 'lid'); if ($labelsarray) { $count = 0; foreach ($labelsarray as $la) { $lfieldorders = convertCSVRowToArray($labelsarray[0], ',', '"'); $lfieldcontents = convertCSVRowToArray($la, ',', '"'); if ($count == 0) { $count++; continue; } // Combine into one array with keys and values since its easier to handle $labelrowdata = array_combine($lfieldorders, $lfieldcontents); $labellid = $labelrowdata['lid']; if ($importversion <= 132) { $labelrowdata["assessment_value"] = (int) $labelrowdata["code"]; } if ($labellid == $oldlid) { $labelrowdata['lid'] = $newlid; // translate internal links $labelrowdata['title'] = translink('label', $oldlid, $newlid, $labelrowdata['title']); $newvalues = array_values($labelrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $lainsert = "INSERT INTO {$dbprefix}labels (" . implode(',', array_keys($labelrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; //handle db prefix $liresult = $connect->Execute($lainsert); if ($liresult !== false) { $results['labels']++; } } } } //CHECK FOR DUPLICATE LABELSETS $thisset = ""; $query2 = "SELECT code, title, sortorder, language, assessment_value\n FROM {$dbprefix}labels\n WHERE lid=" . $newlid . "\n ORDER BY language, sortorder, code"; $result2 = db_execute_num($query2) or safe_die("Died querying labelset {$lid}<br />{$query2}<br />" . $connect->ErrorMsg()); while ($row2 = $result2->FetchRow()) { $thisset .= implode('.', $row2); } // while $newcs = dechex(crc32($thisset) * 1); unset($lsmatch); if (isset($csarray)) { foreach ($csarray as $key => $val) { if ($val == $newcs) { $lsmatch = $key; } } } if (isset($lsmatch) || $_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1) { //There is a matching labelset or the user is not allowed to edit labels - // So, we will delete this one and refer to the matched one. $query = "DELETE FROM {$dbprefix}labels WHERE lid={$newlid}"; $result = $connect->Execute($query) or safe_die("Couldn't delete labels<br />{$query}<br />" . $connect->ErrorMsg()); $results['labels'] = $results['labels'] - $connect->Affected_Rows(); $query = "DELETE FROM {$dbprefix}labelsets WHERE lid={$newlid}"; $result = $connect->Execute($query) or safe_die("Couldn't delete labelset<br />{$query}<br />" . $connect->ErrorMsg()); $results['labelsets'] = $results['labelsets'] - $connect->Affected_Rows(); $newlid = $lsmatch; } else { //There isn't a matching labelset, add this checksum to the $csarray array $csarray[$newlid] = $newcs; } //END CHECK FOR DUPLICATES $aLIDReplacements[$oldlid] = $newlid; } } // Import groups if (isset($grouparray) && $grouparray) { // do GROUPS $gafieldorders = convertCSVRowToArray($grouparray[0], ',', '"'); unset($grouparray[0]); $newgid = 0; $group_order = 0; // just to initialize this variable foreach ($grouparray as $ga) { $gacfieldcontents = convertCSVRowToArray($ga, ',', '"'); $grouprowdata = array_combine($gafieldorders, $gacfieldcontents); // Skip not supported languages if (!in_array($grouprowdata['language'], $aLanguagesSupported)) { $skippedlanguages[] = $grouprowdata['language']; // this is for the message in the end. continue; } // replace the sid $oldsid = $grouprowdata['sid']; $grouprowdata['sid'] = $newsid; // replace the gid or remove it if needed (it also will calculate the group order if is a new group) $oldgid = $grouprowdata['gid']; if ($newgid == 0) { unset($grouprowdata['gid']); // find the maximum group order and use this grouporder+1 to assign it to the new group $qmaxgo = "select max(group_order) as maxgo from " . db_table_name('groups') . " where sid={$newsid}"; $gres = db_execute_assoc($qmaxgo) or safe_die($clang->gT("Error") . " Failed to find out maximum group order value<br />\n{$qmaxqo}<br />\n" . $connect->ErrorMsg()); $grow = $gres->FetchRow(); $group_order = $grow['maxgo'] + 1; } else { $grouprowdata['gid'] = $newgid; } $grouprowdata["group_order"] = $group_order; // Everything set - now insert it $grouprowdata = array_map('convertCsvreturn2return', $grouprowdata); // translate internal links $grouprowdata['group_name'] = translink('survey', $oldsid, $newsid, $grouprowdata['group_name']); $grouprowdata['description'] = translink('survey', $oldsid, $newsid, $grouprowdata['description']); db_switchIDInsert('groups', true); $tablename = $dbprefix . 'groups'; $ginsert = $connect->GetinsertSQL($tablename, $grouprowdata); $gres = $connect->Execute($ginsert) or safe_die($clang->gT('Error') . ": Failed to insert group<br />\n{$ginsert}<br />\n" . $connect->ErrorMsg()); db_switchIDInsert('groups', false); //GET NEW GID .... if is not done before and we count a group if a new gid is required if ($newgid == 0) { $newgid = $connect->Insert_ID("{$dbprefix}groups", 'gid'); $countgroups++; } } // GROUPS is DONE // Import questions if (isset($questionarray) && $questionarray) { foreach ($questionarray as $qa) { $qacfieldcontents = convertCSVRowToArray($qa, ',', '"'); $questionrowdata = array_combine($questionfieldnames, $qacfieldcontents); $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata); $questionrowdata["type"] = strtoupper($questionrowdata["type"]); // Skip not supported languages if (!in_array($questionrowdata['language'], $aLanguagesSupported)) { continue; } // replace the sid $questionrowdata["sid"] = $newsid; // replace the gid (if the gid is not in the oldgid it means there is a problem with the exported record, so skip it) if ($questionrowdata['gid'] == $oldgid) { $questionrowdata['gid'] = $newgid; } else { continue; } // a problem with this question record -> don't consider if (isset($aQIDReplacements[$questionrowdata['qid']])) { $questionrowdata['qid'] = $aQIDReplacements[$questionrowdata['qid']]; } else { $oldqid = $questionrowdata['qid']; unset($questionrowdata['qid']); } // Save the following values - will need them for proper conversion later if ((int)$questionrowdata['lid']>0) unset($oldlid1); unset($oldlid2); if (isset($questionrowdata['lid']) && $questionrowdata['lid'] > 0) { $oldlid1 = $questionrowdata['lid']; } if (isset($questionrowdata['lid1']) && $questionrowdata['lid1'] > 0) { $oldlid2 = $questionrowdata['lid1']; } unset($questionrowdata['lid']); unset($questionrowdata['lid1']); if ($questionrowdata['type'] == 'W') { $questionrowdata['type'] = '!'; } elseif ($questionrowdata['type'] == 'Z') { $questionrowdata['type'] = 'L'; } if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"] == '') { $questionrowdata["question_order"] = 0; } $questionrowdata = array_map('convertCsvreturn2return', $questionrowdata); // translate internal links $questionrowdata['title'] = translink('survey', $oldsid, $newsid, $questionrowdata['title']); $questionrowdata['question'] = translink('survey', $oldsid, $newsid, $questionrowdata['question']); $questionrowdata['help'] = translink('survey', $oldsid, $newsid, $questionrowdata['help']); $newvalues = array_values($questionrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly if (isset($questionrowdata['qid'])) { db_switchIDInsert('questions', true); } $tablename = $dbprefix . 'questions'; $qinsert = $connect->GetInsertSQL($tablename, $questionrowdata); $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert question<br />\n{$qinsert}<br />\n" . $connect->ErrorMsg()); $results['questions']++; //GET NEW QID .... if is not done before and we count a question if a new qid is required if (isset($questionrowdata['qid'])) { $saveqid = $questionrowdata['qid']; } else { $aQIDReplacements[$oldqid] = $connect->Insert_ID("{$dbprefix}questions", 'qid'); $saveqid = $aQIDReplacements[$oldqid]; } $qtypes = getqtypelist("", "array"); $aSQIDReplacements = array(); db_switchIDInsert('questions', false); // Now we will fix up old label sets where they are used as answers if ((isset($oldlid1) || isset($oldlid2)) && ($qtypes[$questionrowdata['type']]['answerscales'] > 0 || $qtypes[$questionrowdata['type']]['subquestions'] > 1)) { $query = "select * from " . db_table_name('labels') . " where lid={$aLIDReplacements[$oldlid1]} and language='{$questionrowdata['language']}'"; $oldlabelsresult = db_execute_assoc($query); while ($labelrow = $oldlabelsresult->FetchRow()) { if (in_array($labelrow['language'], $aLanguagesSupported)) { if ($qtypes[$questionrowdata['type']]['subquestions'] < 2) { $qinsert = "insert INTO " . db_table_name('answers') . " (qid,code,answer,sortorder,language,assessment_value)\n VALUES ({$aQIDReplacements[$oldqid]}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . "," . db_quoteall($labelrow['assessment_value']) . ")"; $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert answer (lid1) <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg()); } else { if (isset($aSQIDReplacements[$labelrow['code'] . '_' . $saveqid])) { $fieldname = 'qid,'; $data = $aSQIDReplacements[$labelrow['code'] . '_' . $saveqid] . ','; } else { $fieldname = ''; $data = ''; } $qinsert = "insert INTO " . db_table_name('questions') . " ({$fieldname} parent_qid,title,question,question_order,language,scale_id,type, sid, gid)\n VALUES ({$data}{$aQIDReplacements[$oldqid]}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . ",1,'{$questionrowdata['type']}',{$questionrowdata['sid']},{$questionrowdata['gid']})"; $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert question <br />\n{$qinsert}<br />\n" . $connect->ErrorMsg()); if ($fieldname == '') { $aSQIDReplacements[$labelrow['code'] . '_' . $saveqid] = $connect->Insert_ID("{$dbprefix}questions", "qid"); } } } } if (isset($oldlid2) && $qtypes[$questionrowdata['type']]['answerscales'] > 1) { $query = "select * from " . db_table_name('labels') . " where lid={$aLIDReplacements[$oldlid2]} and language='{$questionrowdata['language']}'"; $oldlabelsresult = db_execute_assoc($query); while ($labelrow = $oldlabelsresult->FetchRow()) { $qinsert = "insert INTO " . db_table_name('answers') . " (qid,code,answer,sortorder,language,assessment_value,scale_id)\n VALUES ({$aQIDReplacements[$oldqid]}," . db_quoteall($labelrow['code']) . "," . db_quoteall($labelrow['title']) . "," . db_quoteall($labelrow['sortorder']) . "," . db_quoteall($labelrow['language']) . "," . db_quoteall($labelrow['assessment_value']) . ",1)"; $qres = $connect->Execute($qinsert) or safe_die($clang->gT("Error") . ": Failed to insert answer (lid2)<br />\n{$qinsert}<br />\n" . $connect->ErrorMsg()); } } } } } //Do answers $results['subquestions'] = 0; if (isset($answerarray) && $answerarray) { foreach ($answerarray as $aa) { $answerfieldcontents = convertCSVRowToArray($aa, ',', '"'); $answerrowdata = array_combine($answerfieldnames, $answerfieldcontents); if ($answerrowdata === false) { $importquestion .= '<br />' . $clang->gT("Faulty line in import - fields and data don't match") . ":" . implode(',', $answerfieldcontents); } // Skip not supported languages if (!in_array($answerrowdata['language'], $aLanguagesSupported)) { continue; } // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this answer is orphan -> error, skip this record) if (isset($aQIDReplacements[$answerrowdata["qid"]])) { $answerrowdata["qid"] = $aQIDReplacements[$answerrowdata["qid"]]; } else { continue; } // a problem with this answer record -> don't consider if ($importversion <= 132) { $answerrowdata["assessment_value"] = (int) $answerrowdata["code"]; } // Convert default values for single select questions $questiontemp = $connect->GetRow('select type,gid from ' . db_table_name('questions') . ' where qid=' . $answerrowdata["qid"]); $oldquestion['newtype'] = $questiontemp['type']; $oldquestion['gid'] = $questiontemp['gid']; if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'L' || $oldquestion['newtype'] == 'O' || $oldquestion['newtype'] == '!')) { $insertdata = array(); $insertdata['qid'] = $newqid; $insertdata['language'] = $answerrowdata['language']; $insertdata['defaultvalue'] = $answerrowdata['answer']; $query = $connect->GetInsertSQL($dbprefix . 'defaultvalues', $insertdata); $qres = $connect->Execute($query) or safe_die("Error: Failed to insert defaultvalue <br />{$query}<br />\n" . $connect->ErrorMsg()); } // translate internal links $answerrowdata['answer'] = translink('survey', $oldsid, $newsid, $answerrowdata['answer']); // Everything set - now insert it $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata); if ($qtypes[$oldquestion['newtype']]['subquestions'] > 0) { $questionrowdata = array(); if (isset($aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']])) { $questionrowdata['qid'] = $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']]; } $questionrowdata['parent_qid'] = $answerrowdata['qid']; $questionrowdata['sid'] = $newsid; $questionrowdata['gid'] = $oldquestion['gid']; $questionrowdata['title'] = $answerrowdata['code']; $questionrowdata['question'] = $answerrowdata['answer']; $questionrowdata['question_order'] = $answerrowdata['sortorder']; $questionrowdata['language'] = $answerrowdata['language']; $questionrowdata['type'] = $oldquestion['newtype']; $tablename = $dbprefix . 'questions'; $query = $connect->GetInsertSQL($tablename, $questionrowdata); if (isset($questionrowdata['qid'])) { db_switchIDInsert('questions', true); } $qres = $connect->Execute($query) or safe_die("Error: Failed to insert subquestion <br />{$query}<br />" . $connect->ErrorMsg()); if (!isset($questionrowdata['qid'])) { $aSQIDReplacements[$answerrowdata['code'] . $answerrowdata['qid']] = $connect->Insert_ID("{$dbprefix}questions", "qid"); } else { db_switchIDInsert('questions', false); } $results['subquestions']++; // also convert default values subquestions for multiple choice if ($answerrowdata['default_value'] == 'Y' && ($oldquestion['newtype'] == 'M' || $oldquestion['newtype'] == 'P')) { $insertdata = array(); $insertdata['qid'] = $newqid; $insertdata['sqid'] = $aSQIDReplacements[$answerrowdata['code']]; $insertdata['language'] = $answerrowdata['language']; $insertdata['defaultvalue'] = 'Y'; $tablename = $dbprefix . 'defaultvalues'; $query = $connect->GetInsertSQL($tablename, $insertdata); $qres = $connect->Execute($query) or safe_die("Error: Failed to insert defaultvalue <br />{$query}<br />\n" . $connect->ErrorMsg()); } } else { unset($answerrowdata['default_value']); $tablename = $dbprefix . 'answers'; $query = $connect->GetInsertSQL($tablename, $answerrowdata); $ares = $connect->Execute($query) or safe_die("Error: Failed to insert answer<br />{$query}<br />\n" . $connect->ErrorMsg()); $results['answers']++; } } } // ANSWERS is DONE // Fix sortorder of the groups - if users removed groups manually from the csv file there would be gaps fixSortOrderGroups($surveyid); //... and for the questions inside the groups // get all group ids and fix questions inside each group $gquery = "SELECT gid FROM {$dbprefix}groups where sid={$newsid} group by gid ORDER BY gid"; //Get last question added (finds new qid) $gres = db_execute_assoc($gquery); while ($grow = $gres->FetchRow()) { fixsortorderQuestions($grow['gid'], $newsid); } } $results['question_attributes'] = 0; // Finally the question attributes - it is called just once and only if there was a question if (isset($question_attributesarray) && $question_attributesarray) { //ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES $fieldorders = convertCSVRowToArray($question_attributesarray[0], ',', '"'); unset($question_attributesarray[0]); foreach ($question_attributesarray as $qar) { $fieldcontents = convertCSVRowToArray($qar, ',', '"'); $qarowdata = array_combine($fieldorders, $fieldcontents); // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this attribute is orphan -> error, skip this record) if (isset($aQIDReplacements[$qarowdata["qid"]])) { $qarowdata["qid"] = $aQIDReplacements[$qarowdata["qid"]]; } else { continue; } // a problem with this answer record -> don't consider unset($qarowdata["qaid"]); $tablename = "{$dbprefix}question_attributes"; $qainsert = $connect->GetInsertSQL($tablename, $qarowdata); $result = $connect->Execute($qainsert); if ($result !== false) { $results['question_attributes']++; } } } // ATTRIBUTES is DONE // do CONDITIONS $results['conditions'] = 0; if (isset($conditionsarray) && $conditionsarray) { $fieldorders = convertCSVRowToArray($conditionsarray[0], ',', '"'); unset($conditionsarray[0]); foreach ($conditionsarray as $car) { $fieldcontents = convertCSVRowToArray($car, ',', '"'); $conditionrowdata = array_combine($fieldorders, $fieldcontents); $oldqid = $conditionrowdata["qid"]; $oldcqid = $conditionrowdata["cqid"]; // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record) if (isset($aQIDReplacements[$oldqid])) { $conditionrowdata["qid"] = $aQIDReplacements[$oldqid]; } else { continue; } // a problem with this answer record -> don't consider // replace the cqid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this condition is orphan -> error, skip this record) if (isset($aQIDReplacements[$oldcqid])) { $conditionrowdata["cqid"] = $aQIDReplacements[$oldcqid]; } else { continue; } // a problem with this answer record -> don't consider list($oldcsid, $oldcgid, $oldqidanscode) = explode("X", $conditionrowdata["cfieldname"], 3); if ($oldcgid != $oldgid) { // this means that the condition is in another group (so it should not have to be been exported -> skip it continue; } unset($conditionrowdata["cid"]); // recreate the cfieldname with the new IDs if (preg_match("/^\\+/", $oldcsid)) { $newcfieldname = '+' . $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] . substr($oldqidanscode, strlen($oldqid)); } else { $newcfieldname = $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] . substr($oldqidanscode, strlen($oldqid)); } $conditionrowdata["cfieldname"] = $newcfieldname; if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"]) == '') { $conditionrowdata["method"] = '=='; } $newvalues = array_values($conditionrowdata); $newvalues = array_map(array(&$connect, "qstr"), $newvalues); // quote everything accordingly $conditioninsert = "insert INTO {$dbprefix}conditions (" . implode(',', array_keys($conditionrowdata)) . ") VALUES (" . implode(',', $newvalues) . ")"; $result = $connect->Execute($conditioninsert) or safe_die("Couldn't insert condition<br />{$conditioninsert}<br />" . $connect->ErrorMsg()); $results['conditions']++; } } LimeExpressionManager::RevertUpgradeConditionsToRelevance($newsid); LimeExpressionManager::UpgradeConditionsToRelevance($newsid); $results['groups'] = 1; $results['newgid'] = $newgid; return $results; }
function upgrade_survey_tables139() { global $modifyoutput, $dbprefix; $surveyidquery = db_select_tables_like($dbprefix . "survey\\_%"); $surveyidresult = db_execute_num($surveyidquery); if (!$surveyidresult) { return "Database Error"; } else { while ($sv = $surveyidresult->FetchRow()) { modify_database("", "ALTER TABLE " . $sv[0] . " ADD [lastpage] int"); echo $modifyoutput; flush(); ob_flush(); } } }
/** * Retrieves the token attribute value from the related token table * * @param mixed $surveyid The survey ID * @param mixed $attrName The token-attribute field name * @param mixed $token The token code * @return string The token attribute value (or null on error) */ function GetAttributeValue($surveyid, $attrName, $token) { global $dbprefix, $connect; $attrName = strtolower($attrName); if (!tableExists('tokens_' . $surveyid) || !in_array($attrName, GetTokenConditionsFieldNames($surveyid))) { return null; } $sanitized_token = $connect->qstr($token, get_magic_quotes_gpc()); $surveyid = sanitize_int($surveyid); $query = "SELECT {$attrName} FROM {$dbprefix}tokens_{$surveyid} WHERE token={$sanitized_token}"; $result = db_execute_num($query); $count = $result->RecordCount(); if ($count != 1) { return null; } else { $row = $result->FetchRow(); return $row[0]; } }
echo ""; } $na = ""; spss_export_data($na); exit; } if ($subaction == 'dlstructure') { header("Content-Disposition: attachment; filename=survey_" . $surveyid . "_SPSS_syntax_file.sps"); header("Content-type: application/download; charset=UTF-8"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: public"); // Build array that has to be returned $fields = spss_fieldmap(); //Now get the query string with all fields to export $query = spss_getquery(); $result = db_execute_num($query) or safe_die("Couldn't get results<br />{$query}<br />" . $connect->ErrorMsg()); //Checked $num_fields = $result->FieldCount(); //Now we check if we need to adjust the size of the field or the type of the field while ($row = $result->FetchRow()) { $fieldno = 0; while ($fieldno < $num_fields) { //Performance improvement, don't recheck fields that have valuelabels if (!isset($fields[$fieldno]['answers'])) { $strTmp = mb_substr(strip_tags_full($row[$fieldno]), 0, $length_data); $len = mb_strlen($strTmp); if ($len > $fields[$fieldno]['size']) { $fields[$fieldno]['size'] = $len; } if (trim($strTmp) != '') { if ($fields[$fieldno]['SPSStype'] == 'F' && (my_is_numeric($strTmp) === false || $fields[$fieldno]['size'] > 16)) {
/** * This function imports the old CSV data from 1.50 to 1.87 or older. Starting with 1.90 (DBVersion 143) there is an XML format instead * * @param array $sFullFilepath * @returns array Information of imported questions/answers/etc. */ function CSVImportSurvey($sFullFilepath,$iDesiredSurveyId=NULL) { global $dbprefix, $connect, $timeadjust, $clang; $handle = fopen($sFullFilepath, "r"); while (!feof($handle)) { $buffer = fgets($handle); $bigarray[] = $buffer; } fclose($handle); $aIgnoredAnswers=array(); $aSQIDReplacements=array(); $aLIDReplacements=array(); $aGIDReplacements=array(); $substitutions=array(); $aQuotaReplacements=array(); $importresults['error']=false; $importresults['importwarnings']=array(); $importresults['question_attributes']=0; if (isset($bigarray[0])) $bigarray[0]=removeBOM($bigarray[0]); // Now we try to determine the dataformat of the survey file. $importversion=0; if (isset($bigarray[1]) && isset($bigarray[4])&& (substr($bigarray[1], 0, 22) == "# SURVEYOR SURVEY DUMP")) { $importversion = 100; // Version 0.99 or 1.0 file } elseif (substr($bigarray[0], 0, 24) == "# LimeSurvey Survey Dump" || substr($bigarray[0], 0, 25) == "# PHPSurveyor Survey Dump") { // Seems to be a >1.0 version file - these files carry the version information to read in line two $importversion=substr($bigarray[1], 12, 3); } else // unknown file - show error message { $importresults['error'] = $clang->gT("This file is not a LimeSurvey survey file. Import failed.")."\n"; return $importresults; } if ((int)$importversion<112) { $importresults['error'] = $clang->gT("This file is too old. Only files from LimeSurvey version 1.50 (DBVersion 112) and newer are supported."); return $importresults; } // okay.. now lets drop the first 9 lines and get to the data // This works for all versions for ($i=0; $i<9; $i++) { unset($bigarray[$i]); } $bigarray = array_values($bigarray); //SURVEYS if (array_search("# GROUPS TABLE\n", $bigarray)) { $stoppoint = array_search("# GROUPS TABLE\n", $bigarray); } elseif (array_search("# GROUPS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# GROUPS TABLE\r\n", $bigarray); } for ($i=0; $i<=$stoppoint+1; $i++) { if ($i<$stoppoint-2) {$surveyarray[] = $bigarray[$i];} unset($bigarray[$i]); } $bigarray = array_values($bigarray); //GROUPS if (array_search("# QUESTIONS TABLE\n", $bigarray)) { $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray); } elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];} unset($bigarray[$i]); } $bigarray = array_values($bigarray); //QUESTIONS if (array_search("# ANSWERS TABLE\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray); } elseif (array_search("# ANSWERS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { if ($i<$stoppoint-2) { $questionarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //ANSWERS if (array_search("# CONDITIONS TABLE\n", $bigarray)) { $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray); } elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { if ($i<$stoppoint-2) { $answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]); } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //CONDITIONS if (array_search("# LABELSETS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray); } elseif (array_search("# LABELSETS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray); } for ($i=0; $i<=$stoppoint+1; $i++) { if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];} unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LABELSETS if (array_search("# LABELS TABLE\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\n", $bigarray); } elseif (array_search("# LABELS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];} unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LABELS if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray); } elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];} unset($bigarray[$i]); } $bigarray = array_values($bigarray); //Question attributes if (array_search("# ASSESSMENTS TABLE\n", $bigarray)) { $stoppoint = array_search("# ASSESSMENTS TABLE\n", $bigarray); } elseif (array_search("# ASSESSMENTS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# ASSESSMENTS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { if ($i<$stoppoint-2) {$question_attributesarray[] = $bigarray[$i];} unset($bigarray[$i]); } $bigarray = array_values($bigarray); //ASSESSMENTS if (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray)) { $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\n", $bigarray); } elseif (array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# SURVEYS_LANGUAGESETTINGS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { // if ($i<$stoppoint-2 || $i==count($bigarray)-1) if ($i<$stoppoint-2) { $assessmentsarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //LANGAUGE SETTINGS if (array_search("# QUOTA TABLE\n", $bigarray)) { $stoppoint = array_search("# QUOTA TABLE\n", $bigarray); } elseif (array_search("# QUOTA TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUOTA TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { // if ($i<$stoppoint-2 || $i==count($bigarray)-1) //$bigarray[$i]= trim($bigarray[$i]); if (isset($bigarray[$i]) && (trim($bigarray[$i])!='')) { if (strpos($bigarray[$i],"#")===0) { unset($bigarray[$i]); unset($bigarray[$i+1]); unset($bigarray[$i+2]); break ; } else { $surveylsarray[] = $bigarray[$i]; } } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //QUOTA if (array_search("# QUOTA_MEMBERS TABLE\n", $bigarray)) { $stoppoint = array_search("# QUOTA_MEMBERS TABLE\n", $bigarray); } elseif (array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUOTA_MEMBERS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { // if ($i<$stoppoint-2 || $i==count($bigarray)-1) if ($i<$stoppoint-2) { $quotaarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //QUOTA MEMBERS if (array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray)) { $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\n", $bigarray); } elseif (array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray)) { $stoppoint = array_search("# QUOTA_LANGUAGESETTINGS TABLE\r\n", $bigarray); } else { $stoppoint = count($bigarray)-1; } for ($i=0; $i<=$stoppoint+1; $i++) { // if ($i<$stoppoint-2 || $i==count($bigarray)-1) if ($i<$stoppoint-2) { $quotamembersarray[] = $bigarray[$i]; } unset($bigarray[$i]); } $bigarray = array_values($bigarray); //Whatever is the last table - currently //QUOTA LANGUAGE SETTINGS $stoppoint = count($bigarray)-1; for ($i=0; $i<$stoppoint-1; $i++) { if ($i<=$stoppoint) {$quotalsarray[] = $bigarray[$i];} unset($bigarray[$i]); } $bigarray = array_values($bigarray); if (isset($surveyarray)) {$importresults['surveys'] = count($surveyarray);} else {$importresults['surveys'] = 0;} if (isset($surveylsarray)) {$importresults['languages'] = count($surveylsarray)-1;} else {$importresults['languages'] = 1;} if (isset($grouparray)) {$importresults['groups'] = count($grouparray)-1;} else {$importresults['groups'] = 0;} if (isset($questionarray)) {$importresults['questions'] = count($questionarray);} else {$importresults['questions']=0;} if (isset($answerarray)) {$importresults['answers'] = count($answerarray);} else {$importresults['answers']=0;} if (isset($conditionsarray)) {$importresults['conditions'] = count($conditionsarray);} else {$importresults['conditions']=0;} if (isset($labelsetsarray)) {$importresults['labelsets'] = count($labelsetsarray);} else {$importresults['labelsets']=0;} if (isset($assessmentsarray)) {$importresults['assessments']=count($assessmentsarray);} else {$importresults['assessments']=0;} if (isset($quotaarray)) {$importresults['quota']=count($quotaarray);} else {$importresults['quota']=0;} if (isset($quotamembersarray)) {$importresults['quotamembers']=count($quotamembersarray);} else {$importresults['quotamembers']=0;} if (isset($quotalsarray)) {$importresults['quotals']=count($quotalsarray);} else {$importresults['quotals']=0;} // CREATE SURVEY if ($importresults['surveys']>0){$importresults['surveys']--;}; if ($importresults['answers']>0){$importresults['answers']=($importresults['answers']-1)/$importresults['languages'];}; if ($importresults['groups']>0){$countgroups=($importresults['groups']-1)/$importresults['languages'];}; if ($importresults['questions']>0){$importresults['questions']=($importresults['questions']-1)/$importresults['languages'];}; if ($importresults['assessments']>0){$importresults['assessments']--;}; if ($importresults['conditions']>0){$importresults['conditions']--;}; if ($importresults['labelsets']>0){$importresults['labelsets']--;}; if ($importresults['quota']>0){$importresults['quota']--;}; $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"'); $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"'); $surveyrowdata=array_combine($sfieldorders,$sfieldcontents); $oldsid=$surveyrowdata["sid"]; if($iDesiredSurveyId!=NULL) $oldsid = $iDesiredSurveyId; if (!$oldsid) { if ($importingfrom == "http") { $importsurvey .= "<br /><div class='warningheader'>".$clang->gT("Error")."</div><br />\n"; $importsurvey .= $clang->gT("Import of this survey file failed")."<br />\n"; $importsurvey .= $clang->gT("File does not contain LimeSurvey data in the correct format.")."<br /><br />\n"; //Couldn't find the SID - cannot continue $importsurvey .= "<input type='submit' value='".$clang->gT("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\" />\n"; $importsurvey .= "</div>\n"; unlink($sFullFilepath); //Delete the uploaded file return; } else { echo $clang->gT("Import of this survey file failed")."\n".$clang->gT("File does not contain LimeSurvey data in the correct format.")."\n"; return; } } $newsid = GetNewSurveyID($oldsid); $insert=$surveyarray[0]; $sfieldorders =convertCSVRowToArray($surveyarray[0],',','"'); $sfieldcontents=convertCSVRowToArray($surveyarray[1],',','"'); $surveyrowdata=array_combine($sfieldorders,$sfieldcontents); // Set new owner ID $surveyrowdata['owner_id']=$_SESSION['loginID']; // Set new survey ID $surveyrowdata['sid']=$newsid; $surveyrowdata['active']='N'; if (validate_templatedir($surveyrowdata['template'])!==$surveyrowdata['template']) $importresults['importwarnings'][] = sprintf($clang->gT('Template %s not found, please review when activating.'),$surveyrowdata['template']); if (isset($surveyrowdata['datecreated'])) {$surveyrowdata['datecreated']=$connect->BindTimeStamp($surveyrowdata['datecreated']);} unset($surveyrowdata['expires']); unset($surveyrowdata['attribute1']); unset($surveyrowdata['attribute2']); unset($surveyrowdata['usestartdate']); unset($surveyrowdata['notification']); unset($surveyrowdata['useexpiry']); unset($surveyrowdata['url']); unset($surveyrowdata['lastpage']); if (isset($surveyrowdata['private'])){ $surveyrowdata['anonymized']=$surveyrowdata['private']; unset($surveyrowdata['private']); } if (isset($surveyrowdata['startdate'])) {unset($surveyrowdata['startdate']);} $surveyrowdata['bounce_email']=$surveyrowdata['adminemail']; if (!isset($surveyrowdata['datecreated']) || $surveyrowdata['datecreated']=='' || $surveyrowdata['datecreated']=='null') {$surveyrowdata['datecreated']=$connect->BindTimeStamp(date_shift(date("Y-m-d H:i:s"), "Y-m-d", $timeadjust));} $values=array_values($surveyrowdata); $values=array_map(array(&$connect, "qstr"),$values); // quote everything accordingly $insert = "INSERT INTO {$dbprefix}surveys (".implode(',',array_keys($surveyrowdata)).") VALUES (".implode(',',$values).")"; //handle db prefix $iresult = $connect->Execute($insert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$insert]<br />{$surveyarray[0]}<br /><br />\n" . $connect->ErrorMsg()); // Now import the survey language settings $fieldorders=convertCSVRowToArray($surveylsarray[0],',','"'); unset($surveylsarray[0]); foreach ($surveylsarray as $slsrow) { $fieldcontents=convertCSVRowToArray($slsrow,',','"'); $surveylsrowdata=array_combine($fieldorders,$fieldcontents); // convert back the '\'.'n' char from the CSV file to true return char "\n" $surveylsrowdata=array_map('convertCsvreturn2return', $surveylsrowdata); // Convert the \n return char from welcometext to <br /> // translate internal links $surveylsrowdata['surveyls_title']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_title']); $surveylsrowdata['surveyls_description']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_description']); $surveylsrowdata['surveyls_welcometext']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_welcometext']); $surveylsrowdata['surveyls_urldescription']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_urldescription']); $surveylsrowdata['surveyls_email_invite']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_invite']); $surveylsrowdata['surveyls_email_remind']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_remind']); $surveylsrowdata['surveyls_email_register']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_register']); $surveylsrowdata['surveyls_email_confirm']=translink('survey', $oldsid, $newsid, $surveylsrowdata['surveyls_email_confirm']); unset($surveylsrowdata['lastpage']); $surveylsrowdata['surveyls_survey_id']=$newsid; $newvalues=array_values($surveylsrowdata); $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $lsainsert = "INSERT INTO {$dbprefix}surveys_languagesettings (".implode(',',array_keys($surveylsrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix $lsiresult=$connect->Execute($lsainsert) or safe_die("<br />".$clang->gT("Import of this survey file failed")."<br />\n[$lsainsert]<br />\n" . $connect->ErrorMsg() ); } // The survey languagesettings are imported now $aLanguagesSupported = array(); // this array will keep all the languages supported for the survey $sBaseLanguage = GetBaseLanguageFromSurveyID($newsid); $aLanguagesSupported[]=$sBaseLanguage; // adds the base language to the list of supported languages $aLanguagesSupported=array_merge($aLanguagesSupported,GetAdditionalLanguagesFromSurveyID($newsid)); // DO SURVEY_RIGHTS GiveAllSurveyPermissions($_SESSION['loginID'],$newsid); $importresults['deniedcountls'] =0; $qtypes = getqtypelist("" ,"array"); $results['labels']=0; $results['labelsets']=0; $results['answers']=0; $results['subquestions']=0; //Do label sets if (isset($labelsetsarray) && $labelsetsarray) { $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets $count=0; foreach ($labelsetsarray as $lsa) { $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"'); $fieldcontents=convertCSVRowToArray($lsa,',','"'); if ($count==0) {$count++; continue;} $labelsetrowdata=array_combine($fieldorders,$fieldcontents); // Save old labelid $oldlid=$labelsetrowdata['lid']; unset($labelsetrowdata['lid']); $newvalues=array_values($labelsetrowdata); $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix $lsiresult=$connect->Execute($lsainsert); $results['labelsets']++; // Get the new insert id for the labels inside this labelset $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid'); if ($labelsarray) { $count=0; foreach ($labelsarray as $la) { $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"'); $lfieldcontents=convertCSVRowToArray($la,',','"'); if ($count==0) {$count++; continue;} // Combine into one array with keys and values since its easier to handle $labelrowdata=array_combine($lfieldorders,$lfieldcontents); $labellid=$labelrowdata['lid']; if ($importversion<=132) { $labelrowdata["assessment_value"]=(int)$labelrowdata["code"]; } if ($labellid == $oldlid) { $labelrowdata['lid']=$newlid; // translate internal links $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']); $newvalues=array_values($labelrowdata); $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix $liresult=$connect->Execute($lainsert); if ($liresult!==false) $results['labels']++; } } } //CHECK FOR DUPLICATE LABELSETS $thisset=""; $query2 = "SELECT code, title, sortorder, language, assessment_value FROM {$dbprefix}labels WHERE lid=".$newlid." ORDER BY language, sortorder, code"; $result2 = db_execute_num($query2) or safe_die("Died querying labelset $lid<br />$query2<br />".$connect->ErrorMsg()); while($row2=$result2->FetchRow()) { $thisset .= implode('.', $row2); } // while $newcs=dechex(crc32($thisset)*1); unset($lsmatch); if (isset($csarray)) { foreach($csarray as $key=>$val) { if ($val == $newcs) { $lsmatch=$key; } } } if (isset($lsmatch) || ($_SESSION['USER_RIGHT_MANAGE_LABEL'] != 1)) { //There is a matching labelset or the user is not allowed to edit labels - // So, we will delete this one and refer to the matched one. $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid"; $result=$connect->Execute($query) or safe_die("Couldn't delete labels<br />$query<br />".$connect->ErrorMsg()); $results['labels']=$results['labels']-$connect->Affected_Rows(); $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid"; $result=$connect->Execute($query) or safe_die("Couldn't delete labelset<br />$query<br />".$connect->ErrorMsg()); $results['labelsets']=$results['labelsets']-$connect->Affected_Rows(); $newlid=$lsmatch; } else { //There isn't a matching labelset, add this checksum to the $csarray array $csarray[$newlid]=$newcs; } //END CHECK FOR DUPLICATES $aLIDReplacements[$oldlid]=$newlid; } } // Import groups if (isset($grouparray) && $grouparray) { // do GROUPS $gafieldorders=convertCSVRowToArray($grouparray[0],',','"'); unset($grouparray[0]); foreach ($grouparray as $ga) { $gacfieldcontents=convertCSVRowToArray($ga,',','"'); $grouprowdata=array_combine($gafieldorders,$gacfieldcontents); //Now an additional integrity check if there are any groups not belonging into this survey if ($grouprowdata['sid'] != $oldsid) { $results['fatalerror'] = $clang->gT("A group in the CSV/SQL file is not part of the same survey. The import of the survey was stopped.")."<br />\n"; return $results; } $grouprowdata['sid']=$newsid; // remember group id $oldgid=$grouprowdata['gid']; //update/remove the old group id if (isset($aGIDReplacements[$oldgid])) $grouprowdata['gid'] = $aGIDReplacements[$oldgid]; else unset($grouprowdata['gid']); // Everything set - now insert it $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata); // translate internal links $grouprowdata['group_name']=translink('survey', $oldsid, $newsid, $grouprowdata['group_name']); $grouprowdata['description']=translink('survey', $oldsid, $newsid, $grouprowdata['description']); if (isset($grouprowdata['gid'])) db_switchIDInsert('groups',true); $tablename=$dbprefix.'groups'; $ginsert = $connect->GetinsertSQL($tablename,$grouprowdata); $gres = $connect->Execute($ginsert) or safe_die($clang->gT('Error').": Failed to insert group<br />\n$ginsert<br />\n".$connect->ErrorMsg()); if (isset($grouprowdata['gid'])) db_switchIDInsert('groups',false); //GET NEW GID if (!isset($grouprowdata['gid'])) {$aGIDReplacements[$oldgid]=$connect->Insert_ID("{$dbprefix}groups","gid");} } // Fix sortorder of the groups - if users removed groups manually from the csv file there would be gaps fixSortOrderGroups($newsid); } // GROUPS is DONE // Import questions if (isset($questionarray) && $questionarray) { $qafieldorders=convertCSVRowToArray($questionarray[0],',','"'); unset($questionarray[0]); foreach ($questionarray as $qa) { $qacfieldcontents=convertCSVRowToArray($qa,',','"'); $questionrowdata=array_combine($qafieldorders,$qacfieldcontents); $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata); $questionrowdata["type"]=strtoupper($questionrowdata["type"]); // Skip not supported languages if (!in_array($questionrowdata['language'],$aLanguagesSupported)) continue; // replace the sid $questionrowdata["sid"] = $newsid; // Skip if gid is invalid if (!isset($aGIDReplacements[$questionrowdata['gid']])) continue; $questionrowdata["gid"] = $aGIDReplacements[$questionrowdata['gid']]; if (isset($aQIDReplacements[$questionrowdata['qid']])) { $questionrowdata['qid']=$aQIDReplacements[$questionrowdata['qid']]; } else { $oldqid=$questionrowdata['qid']; unset($questionrowdata['qid']); } unset($oldlid1); unset($oldlid2); if ((isset($questionrowdata['lid']) && $questionrowdata['lid']>0)) { $oldlid1=$questionrowdata['lid']; } if ((isset($questionrowdata['lid1']) && $questionrowdata['lid1']>0)) { $oldlid2=$questionrowdata['lid1']; } unset($questionrowdata['lid']); unset($questionrowdata['lid1']); if ($questionrowdata['type']=='W') { $questionrowdata['type']='!'; } elseif ($questionrowdata['type']=='Z') { $questionrowdata['type']='L'; $aIgnoredAnswers[]=$oldqid; } if (!isset($questionrowdata["question_order"]) || $questionrowdata["question_order"]=='') {$questionrowdata["question_order"]=0;} // translate internal links $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']); $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']); $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']); if (isset($questionrowdata['qid'])) { db_switchIDInsert('questions',true); } $tablename=$dbprefix.'questions'; $qinsert = $connect->GetInsertSQL($tablename,$questionrowdata); $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question<br />\n$qinsert<br />\n".$connect->ErrorMsg()); if (isset($questionrowdata['qid'])) { db_switchIDInsert('questions',false); $saveqid=$questionrowdata['qid']; } else { $aQIDReplacements[$oldqid]=$connect->Insert_ID("{$dbprefix}questions",'qid'); $saveqid=$aQIDReplacements[$oldqid]; } // Now we will fix up old label sets where they are used as answers if (((isset($oldlid1) && isset($aLIDReplacements[$oldlid1])) || (isset($oldlid2) && isset($aLIDReplacements[$oldlid2]))) && ($qtypes[$questionrowdata['type']]['answerscales']>0 || $qtypes[$questionrowdata['type']]['subquestions']>1)) { $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid1]} and language='{$questionrowdata['language']}'"; $oldlabelsresult=db_execute_assoc($query); while($labelrow=$oldlabelsresult->FetchRow()) { if (in_array($labelrow['language'],$aLanguagesSupported)) { if ($qtypes[$questionrowdata['type']]['subquestions']<2) { $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value) VALUES ({$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",".db_quoteall($labelrow['assessment_value']).")"; $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid1) <br />\n$qinsert<br />\n".$connect->ErrorMsg()); } else { if (isset($aSQIDReplacements[$labelrow['code'].'_'.$saveqid])){ $fieldname='qid,'; $data=$aSQIDReplacements[$labelrow['code'].'_'.$saveqid].','; } else{ $fieldname='' ; $data=''; } $qinsert = "insert INTO ".db_table_name('questions')." ($fieldname parent_qid,title,question,question_order,language,scale_id,type, sid, gid) VALUES ($data{$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",1,'{$questionrowdata['type']}',{$questionrowdata['sid']},{$questionrowdata['gid']})"; $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert question <br />\n$qinsert<br />\n".$connect->ErrorMsg()); if ($fieldname=='') { $aSQIDReplacements[$labelrow['code'].'_'.$saveqid]=$connect->Insert_ID("{$dbprefix}questions","qid"); } } } } if (isset($oldlid2) && $qtypes[$questionrowdata['type']]['answerscales']>1) { $query="select * from ".db_table_name('labels')." where lid={$aLIDReplacements[$oldlid2]} and language='{$questionrowdata['language']}'"; $oldlabelsresult=db_execute_assoc($query); while($labelrow=$oldlabelsresult->FetchRow()) { $qinsert = "insert INTO ".db_table_name('answers')." (qid,code,answer,sortorder,language,assessment_value,scale_id) VALUES ({$aQIDReplacements[$oldqid]},".db_quoteall($labelrow['code']).",".db_quoteall($labelrow['title']).",".db_quoteall($labelrow['sortorder']).",".db_quoteall($labelrow['language']).",".db_quoteall($labelrow['assessment_value']).",1)"; $qres = $connect->Execute($qinsert) or safe_die ($clang->gT("Error").": Failed to insert answer (lid2)<br />\n$qinsert<br />\n".$connect->ErrorMsg()); } } } } } //Do answers if (isset($answerarray) && $answerarray) { $answerfieldnames = convertCSVRowToArray($answerarray[0],',','"'); unset($answerarray[0]); foreach ($answerarray as $aa) { $answerfieldcontents = convertCSVRowToArray($aa,',','"'); $answerrowdata = array_combine($answerfieldnames,$answerfieldcontents); if (in_array($answerrowdata['qid'],$aIgnoredAnswers)) { // Due to a bug in previous LS versions there may be orphaned answers with question type Z (which is now L) // this way they are ignored continue; } if ($answerrowdata===false) { $importquestion.='<br />'.$clang->gT("Faulty line in import - fields and data don't match").":".implode(',',$answerfieldcontents); } // Skip not supported languages if (!in_array($answerrowdata['language'],$aLanguagesSupported)) continue; // replace the qid for the new one (if there is no new qid in the $aQIDReplacements array it mean that this answer is orphan -> error, skip this record) if (isset($aQIDReplacements[$answerrowdata["qid"]])) $answerrowdata["qid"] = $aQIDReplacements[$answerrowdata["qid"]]; else continue; // a problem with this answer record -> don't consider if ($importversion<=132) { $answerrowdata["assessment_value"]=(int)$answerrowdata["code"]; } // Convert default values for single select questions $questiontemp=$connect->GetRow('select type,gid from '.db_table_name('questions').' where qid='.$answerrowdata["qid"]); $oldquestion['newtype']=$questiontemp['type']; $oldquestion['gid']=$questiontemp['gid']; if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='L' || $oldquestion['newtype']=='O' || $oldquestion['newtype']=='!')) { $insertdata=array(); $insertdata['qid']=$newqid; $insertdata['language']=$answerrowdata['language']; $insertdata['defaultvalue']=$answerrowdata['answer']; $query=$connect->GetInsertSQL($dbprefix.'defaultvalues',$insertdata); $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg()); } // translate internal links $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']); // Everything set - now insert it $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata); if ($qtypes[$oldquestion['newtype']]['subquestions']>0) //hmmm.. this is really a subquestion { $questionrowdata=array(); if (isset($aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']])){ $questionrowdata['qid']=$aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]; } $questionrowdata['parent_qid']=$answerrowdata['qid'];; $questionrowdata['sid']=$newsid; $questionrowdata['gid']=$oldquestion['gid']; $questionrowdata['title']=$answerrowdata['code']; $questionrowdata['question']=$answerrowdata['answer']; $questionrowdata['question_order']=$answerrowdata['sortorder']; $questionrowdata['language']=$answerrowdata['language']; $questionrowdata['type']=$oldquestion['newtype']; $tablename=$dbprefix.'questions'; $query=$connect->GetInsertSQL($tablename,$questionrowdata); if (isset($questionrowdata['qid'])) db_switchIDInsert('questions',true); $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert subquestion <br />{$query}<br />".$connect->ErrorMsg()); if (!isset($questionrowdata['qid'])) { $aSQIDReplacements[$answerrowdata['code'].$answerrowdata['qid']]=$connect->Insert_ID("{$dbprefix}questions","qid"); } else { db_switchIDInsert('questions',false); } $results['subquestions']++; // also convert default values subquestions for multiple choice if ($answerrowdata['default_value']=='Y' && ($oldquestion['newtype']=='M' || $oldquestion['newtype']=='P')) { $insertdata=array(); $insertdata['qid']=$newqid; $insertdata['sqid']=$aSQIDReplacements[$answerrowdata['code']]; $insertdata['language']=$answerrowdata['language']; $insertdata['defaultvalue']='Y'; $tablename=$dbprefix.'defaultvalues'; $query=$connect->GetInsertSQL($tablename,$insertdata); $qres = $connect->Execute($query) or safe_die ("Error: Failed to insert defaultvalue <br />{$query}<br />\n".$connect->ErrorMsg()); } } else // insert answers { unset($answerrowdata['default_value']); $tablename=$dbprefix.'answers'; $query=$connect->GetInsertSQL($tablename,$answerrowdata); $ares = $connect->Execute($query) or safe_die ("Error: Failed to insert answer<br />{$query}<br />\n".$connect->ErrorMsg()); $results['answers']++; } } } // get all group ids and fix questions inside each group $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid) $gres = db_execute_assoc($gquery); while ($grow = $gres->FetchRow()) { fixsortorderQuestions($grow['gid'], $newsid); } //We've built two arrays along the way - one containing the old SID, GID and QIDs - and their NEW equivalents //and one containing the old 'extended fieldname' and its new equivalent. These are needed to import conditions and question_attributes. if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"'); unset($question_attributesarray[0]); foreach ($question_attributesarray as $qar) { $fieldcontents=convertCSVRowToArray($qar,',','"'); $qarowdata=array_combine($fieldorders,$fieldcontents); $newqid=""; $qarowdata["qid"]=$aQIDReplacements[$qarowdata["qid"]]; unset($qarowdata["qaid"]); $newvalues=array_values($qarowdata); $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")"; $result=$connect->Execute($qainsert); // no safe_die since some LimeSurvey version export duplicate question attributes - these are just ignored if ($connect->Affected_Rows()>0) {$importresults['question_attributes']++;} } } if (isset($assessmentsarray) && $assessmentsarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUTES $fieldorders=convertCSVRowToArray($assessmentsarray[0],',','"'); unset($assessmentsarray[0]); foreach ($assessmentsarray as $qar) { $fieldcontents=convertCSVRowToArray($qar,',','"'); $asrowdata=array_combine($fieldorders,$fieldcontents); if (isset($asrowdata['link'])) { if (trim($asrowdata['link'])!='') $asrowdata['message']=$asrowdata['message'].'<br /><a href="'.$asrowdata['link'].'">'.$asrowdata['link'].'</a>'; unset($asrowdata['link']); } if ($asrowdata["gid"]>0) { $asrowdata["gid"]=$aGIDReplacements[$asrowdata["gid"]]; } $asrowdata["sid"]=$newsid; unset($asrowdata["id"]); $tablename=$dbprefix.'assessments'; $asinsert = $connect->GetInsertSQL($tablename,$asrowdata); $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert assessment<br />$asinsert<br />".$connect->ErrorMsg()); unset($newgid); } } if (isset($quotaarray) && $quotaarray) {//ONLY DO THIS IF THERE ARE QUOTAS $fieldorders=convertCSVRowToArray($quotaarray[0],',','"'); unset($quotaarray[0]); foreach ($quotaarray as $qar) { $fieldcontents=convertCSVRowToArray($qar,',','"'); $asrowdata=array_combine($fieldorders,$fieldcontents); $oldsid=$asrowdata["sid"]; foreach ($substitutions as $subs) { if ($oldsid==$subs[0]) {$newsid=$subs[3];} } $asrowdata["sid"]=$newsid; $oldid = $asrowdata["id"]; unset($asrowdata["id"]); $quotadata[]=$asrowdata; //For use later if needed $tablename=$dbprefix.'quota'; $asinsert = $connect->getInsertSQL($tablename,$asrowdata); $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg()); $aQuotaReplacements[$oldid] = $connect->Insert_ID(db_table_name_nq('quota'),"id"); } } if (isset($quotamembersarray) && $quotamembersarray) {//ONLY DO THIS IF THERE ARE QUOTA MEMBERS $count=0; foreach ($quotamembersarray as $qar) { $fieldorders =convertCSVRowToArray($quotamembersarray[0],',','"'); $fieldcontents=convertCSVRowToArray($qar,',','"'); if ($count==0) {$count++; continue;} $asrowdata=array_combine($fieldorders,$fieldcontents); $oldsid=$asrowdata["sid"]; $newqid=""; $newquotaid=""; $oldqid=$asrowdata['qid']; $oldquotaid=$asrowdata['quota_id']; foreach ($substitutions as $subs) { if ($oldsid==$subs[0]) {$newsid=$subs[3];} if ($oldqid==$subs[2]) {$newqid=$subs[5];} } $newquotaid=$aQuotaReplacements[$oldquotaid]; $asrowdata["sid"]=$newsid; $asrowdata["qid"]=$newqid; $asrowdata["quota_id"]=$newquotaid; unset($asrowdata["id"]); $tablename=$dbprefix.'quota_members'; $asinsert = $connect->getInsertSQL($tablename,$asrowdata); $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg()); } } if (isset($quotalsarray) && $quotalsarray) {//ONLY DO THIS IF THERE ARE QUOTA LANGUAGE SETTINGS $count=0; foreach ($quotalsarray as $qar) { $fieldorders =convertCSVRowToArray($quotalsarray[0],',','"'); $fieldcontents=convertCSVRowToArray($qar,',','"'); if ($count==0) {$count++; continue;} $asrowdata=array_combine($fieldorders,$fieldcontents); $newquotaid=""; $oldquotaid=$asrowdata['quotals_quota_id']; $newquotaid=$aQuotaReplacements[$oldquotaid]; $asrowdata["quotals_quota_id"]=$newquotaid; unset($asrowdata["quotals_id"]); $tablename=$dbprefix.'quota_languagesettings'; $asinsert = $connect->getInsertSQL($tablename,$asrowdata); $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg()); } } //if there are quotas, but no quotals, then we need to create default dummy for each quota (this handles exports from pre-language quota surveys) if ($importresults['quota'] > 0 && (!isset($importresults['quotals']) || $importresults['quotals'] == 0)) { $i=0; $defaultsurveylanguage=isset($defaultsurveylanguage) ? $defaultsurveylanguage : "en"; foreach($aQuotaReplacements as $oldquotaid=>$newquotaid) { $asrowdata=array("quotals_quota_id" => $newquotaid, "quotals_language" => $defaultsurveylanguage, "quotals_name" => $quotadata[$i]["name"], "quotals_message" => $clang->gT("Sorry your responses have exceeded a quota on this survey."), "quotals_url" => "", "quotals_urldescrip" => ""); $i++; } $tablename=$dbprefix.'quota_languagesettings'; $asinsert = $connect->getInsertSQL($tablename,$asrowdata); $result=$connect->Execute($asinsert) or safe_die ("Couldn't insert quota<br />$asinsert<br />".$connect->ErrorMsg()); $countquotals=$i; } // Do conditions if (isset($conditionsarray) && $conditionsarray) {//ONLY DO THIS IF THERE ARE CONDITIONS! $fieldorders =convertCSVRowToArray($conditionsarray[0],',','"'); unset($conditionsarray[0]); // Exception for conditions based on attributes $aQIDReplacements[0]=0; foreach ($conditionsarray as $car) { $fieldcontents=convertCSVRowToArray($car,',','"'); $conditionrowdata=array_combine($fieldorders,$fieldcontents); unset($conditionrowdata["cid"]); if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='') { $conditionrowdata["method"]='=='; } if (!isset($conditionrowdata["scenario"]) || trim($conditionrowdata["scenario"])=='') { $conditionrowdata["scenario"]=1; } $oldcqid=$conditionrowdata["cqid"]; $oldgid=array_search($connect->GetOne('select gid from '.db_table_name('questions').' where qid='.$aQIDReplacements[$conditionrowdata["cqid"]]),$aGIDReplacements); $conditionrowdata["qid"]=$aQIDReplacements[$conditionrowdata["qid"]]; $conditionrowdata["cqid"]=$aQIDReplacements[$conditionrowdata["cqid"]]; $oldcfieldname=$conditionrowdata["cfieldname"]; $conditionrowdata["cfieldname"]=str_replace($oldsid.'X'.$oldgid.'X'.$oldcqid,$newsid.'X'.$aGIDReplacements[$oldgid].'X'.$conditionrowdata["cqid"],$conditionrowdata["cfieldname"]); $tablename=$dbprefix.'conditions'; $conditioninsert = $connect->getInsertSQL($tablename,$conditionrowdata); $result=$connect->Execute($conditioninsert) or safe_die ("Couldn't insert condition<br />$conditioninsert<br />".$connect->ErrorMsg()); } } $importresults['importversion']=$importversion; $importresults['newsid']=$newsid; $importresults['oldsid']=$oldsid; return $importresults; }
$oldtable = returnglobal('oldtable'); } if (!isset($surveyid)) { $surveyid = returnglobal('sid'); } if (!$subaction == "import") { // show UI for choosing old table $query = db_select_tables_like("{$dbprefix}old\\_survey\\_%"); $result = db_execute_num($query) or safe_die("Error:<br />{$query}<br />" . $connect->ErrorMsg()); $optionElements = ''; $queryCheckColumnsActive = "SELECT * FROM {$dbprefix}survey_{$surveyid} "; $resultActive = db_execute_num($queryCheckColumnsActive) or safe_die("Error:<br />{$query}<br />" . $connect->ErrorMsg()); $countActive = $resultActive->FieldCount(); while ($row = $result->FetchRow()) { $queryCheckColumnsOld = "SELECT * FROM {$row[0]} "; $resultOld = db_execute_num($queryCheckColumnsOld) or safe_die("Error:<br />{$query}<br />" . $connect->ErrorMsg()); if ($countActive == $resultOld->FieldCount()) { $optionElements .= "\t\t\t<option value='{$row[0]}'>{$row[0]}</option>\n"; } } //Get the menubar $importoldresponsesoutput = browsemenubar($clang->gT("Quick Statistics")); $importoldresponsesoutput .= "\n\t\t<div class='header'>\n\t\t\t" . $clang->gT("Import responses from an deactivated survey table") . "\n\t\t</div>\n <form id='personalsettings' method='post'> \n\t\t<ul>\n\t\t <li><label for='spansurveyid'>" . $clang->gT("Target survey ID:") . "</label>\n\t\t <span id='spansurveyid'> {$surveyid}<input type='hidden' value='{$surveyid}' name='sid'></span>\n\t\t</li>\n <li>\n\t\t <label for='oldtable'>\n\t\t " . $clang->gT("Source table:") . "\n\t\t </label>\n\t\t <select name='oldtable' >\n\t\t {$optionElements}\n\t\t </select>\n\t\t</li>\n </ul>\n\t\t <p><input type='submit' value='" . $clang->gT("Import Responses") . "' onclick='return confirm(\"" . $clang->gT("Are you sure?", "js") . ")'> \n \t \t <input type='hidden' name='subaction' value='import'><br /><br />\n\t\t\t<div class='messagebox'><div class='warningheader'>" . $clang->gT("Warning") . '</div>' . $clang->gT("You can import all old responses with the same amount of columns as in your active survey. YOU have to make sure, that this responses corresponds to the questions in your active survey.") . "</div>\n\t\t</form>\n </div>\n\t\t<br />"; } elseif (isset($surveyid) && $surveyid && isset($oldtable)) { /* * TODO: * - mysql fit machen * -- quotes für mysql beachten --> ` * - warnmeldung mehrsprachig * - testen */
} else { $listsurveys .= "<td> </td>"; $listsurveys .= "<td> </td>"; $listsurveys .= "<td> </td>"; } if ($rows['active'] == "Y" && tableExists("tokens_" . $rows['sid'])) { //get the number of tokens for each survey $tokencountquery = "SELECT count(tid) FROM " . db_table_name("tokens_" . $rows['sid']); $tokencountresult = db_execute_num($tokencountquery); //Checked while ($tokenrow = $tokencountresult->FetchRow()) { $tokencount = $tokenrow[0]; } //get the number of COMLETED tokens for each survey $tokencompletedquery = "SELECT count(tid) FROM " . db_table_name("tokens_" . $rows['sid']) . " WHERE completed!='N'"; $tokencompletedresult = db_execute_num($tokencompletedquery); //Checked while ($tokencompletedrow = $tokencompletedresult->FetchRow()) { $tokencompleted = $tokencompletedrow[0]; } //calculate percentage //prevent division by zero problems if ($tokencompleted != 0 && $tokencount != 0) { $tokenpercentage = round($tokencompleted / $tokencount * 100, 1); } else { $tokenpercentage = 0; } $listsurveys .= "<td>" . $tokencount . "</td>"; $listsurveys .= "<td>" . $tokenpercentage . "%</td>"; } else { $listsurveys .= "<td> </td>";