die("No QID provided."); } if (!isset($_GET['lang']) || $_GET['lang'] == "") { $language = GetBaseLanguageFromSurveyID($surveyid); } else { $language = $_GET['lang']; } $_SESSION['s_lang'] = $language; $_SESSION['fieldmap'] = createFieldMap($surveyid, 'full', true, $qid); // Prefill question/answer from defaultvalues foreach ($_SESSION['fieldmap'] as $field) { if (isset($field['defaultvalue'])) { $_SESSION[$field['fieldname']] = $field['defaultvalue']; } } $clang = new limesurvey_lang($language); $thissurvey = getSurveyInfo($surveyid); $_SESSION['dateformats'] = getDateFormatData($thissurvey['surveyls_dateformat']); $qquery = 'SELECT * FROM ' . db_table_name('questions') . " WHERE sid='{$surveyid}' AND qid='{$qid}' AND language='{$language}'"; $qresult = db_execute_assoc($qquery); $qrows = $qresult->FetchRow(); $ia = array(0 => $qid, 1 => $surveyid . 'X' . $qrows['gid'] . 'X' . $qid, 2 => $qrows['title'], 3 => $qrows['question'], 4 => $qrows['type'], 5 => $qrows['gid'], 6 => $qrows['mandatory'], 7 => 'N', 8 => 'N'); // ia[8] is usedinconditions $answers = retrieveAnswers($ia); if (!$thissurvey['template']) { $thistpl = sGetTemplatePath($defaulttemplate); } else { $thistpl = sGetTemplatePath(validate_templatedir($thissurvey['template'])); } doHeader(); $dummy_js = '
/** * 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; } }
if (isset($_POST['printableexport'])) { $pdf = new PDF($pdforientation, 'mm', 'A4'); $pdf->SetFont($pdfdefaultfont, '', $pdffontsize); $pdf->AddPage(); } // Set the language of the survey, either from GET parameter of session var if (isset($_GET['lang'])) { $_GET['lang'] = preg_replace("/[^a-zA-Z0-9-]/", "", $_GET['lang']); if ($_GET['lang']) { $surveyprintlang = $_GET['lang']; } } else { $surveyprintlang = GetbaseLanguageFromSurveyid($surveyid); } // Setting the selected language for printout $clang = new limesurvey_lang($surveyprintlang); $desquery = "SELECT * FROM " . db_table_name('surveys') . " inner join " . db_table_name('surveys_languagesettings') . " on (surveyls_survey_id=sid) WHERE sid={$surveyid} and surveyls_language=" . $connect->qstr($surveyprintlang); //Getting data for this survey $desrow = $connect->GetRow($desquery); if ($desrow == false || count($desrow) == 0) { safe_die('Invalid survey ID'); } //echo '<pre>'.print_r($desrow,true).'</pre>'; $template = $desrow['template']; $welcome = $desrow['surveyls_welcometext']; $end = $desrow['surveyls_endtext']; $surveyname = $desrow['surveyls_title']; $surveydesc = $desrow['surveyls_description']; $surveyactive = $desrow['active']; $surveytable = db_table_name("survey_" . $desrow['sid']); $surveyexpirydate = $desrow['expires'];
break; default: header("Content-Disposition: attachment; filename=results-survey" . $surveyid . ".csv"); header("Content-type: text/comma-separated-values; charset=UTF-8"); $separator = ","; break; } header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: public"); // Export Language is set by default to surveybaselang // * the explang language code is used in SQL queries // * the alang object is used to translate headers and hardcoded answers // In the future it might be possible to 'post' the 'export language' from // the exportresults form $explang = $surveybaselang; $elang = new limesurvey_lang($explang); //STEP 1: First line is column headings $fieldmap = createFieldMap($surveyid); //Get the fieldnames from the survey table for column headings $surveytable = "{$dbprefix}survey_{$surveyid}"; if (isset($_POST['colselect'])) { $selectfields = ""; foreach ($_POST['colselect'] as $cs) { if (!isset($fieldmap[$cs]) && !isset($aTokenFieldNames[$cs]) && $cs != 'completed') { continue; } // skip invalid field names to prevent SQL injection if ($tokenTableExists && $cs == 'token') { // We shouldnt include the token field when we are joining with the token field } elseif ($cs != 'completed') { $selectfields .= db_quote_id($cs) . ", ";
require_once $homedir . "/classes/core/sha256.php"; $adminoutput = ""; // just to avoid notices include "database.php"; $query = "SELECT uid, password, lang FROM " . db_table_name('users') . " WHERE users_name=" . $connect->qstr($username); $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; $result = $connect->SelectLimit($query, 1) or die($query . "\n" . $connect->ErrorMsg()); if ($result->RecordCount() < 1) { // wrong or unknown username and/or email echo "\n" . $clang->gT("User name invalid!") . "\n"; exit; } else { $fields = $result->FetchRow(); if (SHA256::hashing($userpass) == $fields['password']) { $_SESSION['loginID'] = intval($fields['uid']); $clang = new limesurvey_lang($fields['lang']); GetSessionUserRights($_SESSION['loginID']); if (!$_SESSION['USER_RIGHT_CREATE_SURVEY']) { // no permission to create survey! echo "\n" . $clang->gT("You are not allowed to import a survey!") . "\n"; exit; } } else { // password don't match username echo "\n" . $clang->gT("User name and password do not match!") . "\n"; exit; } } echo "\n"; $importsurvey = ""; $importingfrom = "cmdline";
require_once $rootdir . '/classes/core/language.php'; $surveyid = returnglobal('sid'); $postlang = returnglobal('lang'); $token = returnglobal('token'); //Check that there is a SID if (!isset($surveyid)) { //You must have an SID to use this include "index.php"; exit; } // Get passed language from form, so that we dont loose this! if (!isset($postlang) || $postlang == "") { $baselang = GetBaseLanguageFromSurveyID($surveyid); $clang = new limesurvey_lang($baselang); } else { $clang = new limesurvey_lang($postlang); $baselang = $postlang; } $thissurvey = getSurveyInfo($surveyid, $baselang); $html = '<div id="wrapper"><p id="optoutmessage">'; if ($thissurvey == false || !tableExists("tokens_{$surveyid}")) { $html .= $clang->gT('This survey does not seem to exist.'); } else { $usquery = "SELECT emailstatus from " . db_table_name("tokens_{$surveyid}") . " where token=" . db_quoteall($token, true); $usresult = $connect->GetOne($usquery); if ($usresult == false) { $html .= $clang->gT('You are not a participant in this survey.'); } elseif ($usresult == 'OK') { $usquery = "Update " . db_table_name("tokens_{$surveyid}") . " set emailstatus='OptOut', usesleft=0 where token=" . db_quoteall($token, true); $usresult = $connect->Execute($usquery); $html .= $clang->gT('You have been successfully removed from this survey.');
} else { session_name("LimeSurveyRuntime-$surveyid"); } session_set_cookie_params(0,$relativeurl.'/'); session_start(); // Get passed language from form, so that we dont loose this! if (!isset($postlang) || $postlang == "") { $baselang = GetBaseLanguageFromSurveyID($surveyid); $clang = new limesurvey_lang($baselang); } else { $clang = new limesurvey_lang($postlang); $baselang = $postlang; } $thissurvey=getSurveyInfo($surveyid,$baselang); $register_errormsg = ""; // Check the security question's answer if (function_exists("ImageCreate") && captcha_enabled('registrationscreen',$thissurvey['usecaptcha']) ) { if (!isset($_POST['loadsecurity']) || !isset($_SESSION['secanswer']) || $_POST['loadsecurity'] != $_SESSION['secanswer']) { $register_errormsg .= $clang->gT("The answer to the security question is incorrect.")."<br />\n";
/** * Show printable survey */ function index($surveyid, $lang = null) { $surveyid = sanitize_int($surveyid); if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) { $clang = $this->getController()->lang; $aData['surveyid'] = $surveyid; App()->getClientScript()->registerPackage('jquery-superfish'); $message['title'] = $clang->gT('Access denied!'); $message['message'] = $clang->gT('You do not have sufficient rights to access this page.'); $message['class'] = "error"; $this->_renderWrappedTemplate('survey', array("message" => $message), $aData); } else { $aSurveyInfo = getSurveyInfo($surveyid, $lang); if (!$aSurveyInfo) { $this->getController()->error('Invalid survey ID'); } // Be sure to have a valid language $surveyprintlang = $aSurveyInfo['surveyls_language']; // Setting the selected language for printout $clang = new limesurvey_lang($surveyprintlang); $templatename = validateTemplateDir($aSurveyInfo['templatedir']); $welcome = $aSurveyInfo['surveyls_welcometext']; $end = $aSurveyInfo['surveyls_endtext']; $surveyname = $aSurveyInfo['surveyls_title']; $surveydesc = $aSurveyInfo['surveyls_description']; $surveyactive = $aSurveyInfo['active']; $surveytable = "{{survey_" . $aSurveyInfo['sid'] . "}}"; $surveyexpirydate = $aSurveyInfo['expires']; $surveyfaxto = $aSurveyInfo['faxto']; $dateformattype = $aSurveyInfo['surveyls_dateformat']; Yii::app()->loadHelper('surveytranslator'); if (!is_null($surveyexpirydate)) { $dformat = getDateFormatData($dateformattype); $dformat = $dformat['phpdate']; $expirytimestamp = strtotime($surveyexpirydate); $expirytimeofday_h = date('H', $expirytimestamp); $expirytimeofday_m = date('i', $expirytimestamp); $surveyexpirydate = date($dformat, $expirytimestamp); if (!empty($expirytimeofday_h) || !empty($expirytimeofday_m)) { $surveyexpirydate .= ' – ' . $expirytimeofday_h . ':' . $expirytimeofday_m; } sprintf($clang->gT("Please submit by %s"), $surveyexpirydate); } else { $surveyexpirydate = ''; } //Fix $templatename : control if print_survey.pstpl exist if (is_file(getTemplatePath($templatename) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) { $templatename = $templatename; // Change nothing } elseif (is_file(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) { $templatename = Yii::app()->getConfig("defaulttemplate"); } else { $templatename = "default"; } $sFullTemplatePath = getTemplatePath($templatename) . DIRECTORY_SEPARATOR; $sFullTemplateUrl = getTemplateURL($templatename) . "/"; define('PRINT_TEMPLATE_DIR', $sFullTemplatePath, true); define('PRINT_TEMPLATE_URL', $sFullTemplateUrl, true); LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX); $moveResult = LimeExpressionManager::NavigateForwards(); $condition = "sid = '{$surveyid}' AND language = '{$surveyprintlang}'"; $degresult = QuestionGroup::model()->getAllGroups($condition, array('group_order')); //xiao, if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) { $surveyfaxto = $surveyfaxnumber; //Use system fax number if none is set in survey. } $headelements = getPrintableHeader(); //if $showsgqacode is enabled at config.php show table name for reference $showsgqacode = Yii::app()->getConfig("showsgqacode"); if (isset($showsgqacode) && $showsgqacode == true) { $surveyname = $surveyname . "<br />[" . $clang->gT('Database') . " " . $clang->gT('table') . ": {$surveytable}]"; } else { $surveyname = $surveyname; } $survey_output = array('SITENAME' => Yii::app()->getConfig("sitename"), 'SURVEYNAME' => $surveyname, 'SURVEYDESCRIPTION' => $surveydesc, 'WELCOME' => $welcome, 'END' => $end, 'THEREAREXQUESTIONS' => 0, 'SUBMIT_TEXT' => $clang->gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => $clang->gT("Thank you for completing this survey."), 'HEADELEMENTS' => $headelements, 'TEMPLATEURL' => PRINT_TEMPLATE_URL, 'FAXTO' => $surveyfaxto, 'PRIVACY' => '', 'GROUPS' => ''); $survey_output['FAX_TO'] = ''; if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') { $survey_output['FAX_TO'] = $clang->gT("Please fax your completed survey to:") . " {$surveyfaxto}"; } $total_questions = 0; $mapquestionsNumbers = array(); $answertext = ''; // otherwise can throw an error on line 1617 $fieldmap = createFieldMap($surveyid, 'full', false, false, $surveyprintlang); // ========================================================= // START doin the business: foreach ($degresult->readAll() as $degrow) { // --------------------------------------------------- // START doing groups $deqresult = Question::model()->getQuestions($surveyid, $degrow['gid'], $surveyprintlang, 0, '"I"'); $deqrows = array(); //Create an empty array in case FetchRow does not return any rows foreach ($deqresult->readAll() as $deqrow) { $deqrows[] = $deqrow; } // Get table output into array // Perform a case insensitive natural sort on group name then question title of a multidimensional array usort($deqrows, 'groupOrderThenQuestionOrder'); if ($degrow['description']) { $group_desc = $degrow['description']; } else { $group_desc = ''; } $group = array('GROUPNAME' => $degrow['group_name'], 'GROUPDESCRIPTION' => $group_desc, 'QUESTIONS' => ''); // A group can have only hidden questions. In that case you don't want to see the group's header/description either. $bGroupHasVisibleQuestions = false; $gid = $degrow['gid']; //Alternate bgcolor for different groups if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') { $group['ODD_EVEN'] = ' g-row-odd'; } else { $group['ODD_EVEN'] = ' g-row-even'; } //Loop through questions foreach ($deqrows as $deqrow) { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // START doing questions $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']); if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') { continue; } $bGroupHasVisibleQuestions = true; //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION $printablesurveyoutput = ''; $sExplanation = ''; //reset conditions explanation $s = 0; // TMSW Condition->Relevance: show relevance instead of this whole section to create $explanation $scenarioresult = Condition::model()->getScenarios($deqrow['qid']); $scenarioresult = $scenarioresult->readAll(); //Loop through distinct scenarios, thus grouping them together. foreach ($scenarioresult as $scenariorow) { if ($s == 0 && count($scenarioresult) > 1) { $sExplanation .= '<p class="scenario">' . " -------- Scenario {$scenariorow['scenario']} --------</p>\n\n"; } if ($s > 0) { $sExplanation .= '<p class="scenario">' . ' -------- ' . $clang->gT("or") . " Scenario {$scenariorow['scenario']} --------</p>\n\n"; } $x = 0; $conditions1 = "qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}"; $distinctresult = Condition::model()->getSomeConditions(array('cqid', 'method', 'cfieldname'), $conditions1, array('cqid'), array('cqid', 'method', 'cfieldname')); //Loop through each condition for a particular scenario. foreach ($distinctresult->readAll() as $distinctrow) { $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$surveyprintlang}'"; $subresult = Question::model()->find($condition); if ($x > 0) { $sExplanation .= ' <em class="scenario-and-separator">' . $clang->gT('and') . '</em> '; } if (trim($distinctrow['method']) == '') { $distinctrow['method'] = '=='; } if ($distinctrow['cqid']) { // cqid != 0 ==> previous answer match if ($distinctrow['method'] == '==') { $sExplanation .= $clang->gT("Answer was") . " "; } elseif ($distinctrow['method'] == '!=') { $sExplanation .= $clang->gT("Answer was NOT") . " "; } elseif ($distinctrow['method'] == '<') { $sExplanation .= $clang->gT("Answer was less than") . " "; } elseif ($distinctrow['method'] == '<=') { $sExplanation .= $clang->gT("Answer was less than or equal to") . " "; } elseif ($distinctrow['method'] == '>=') { $sExplanation .= $clang->gT("Answer was greater than or equal to") . " "; } elseif ($distinctrow['method'] == '>') { $sExplanation .= $clang->gT("Answer was greater than") . " "; } elseif ($distinctrow['method'] == 'RX') { $sExplanation .= $clang->gT("Answer matched (regexp)") . " "; } else { $sExplanation .= $clang->gT("Answer was") . " "; } } if (!$distinctrow['cqid']) { // cqid == 0 ==> token attribute match $tokenData = getTokenFieldsAndNames($surveyid); preg_match('/^{TOKEN:([^}]*)}$/', $distinctrow['cfieldname'], $extractedTokenAttr); $sExplanation .= "Your " . $tokenData[strtolower($extractedTokenAttr[1])]['description'] . " "; if ($distinctrow['method'] == '==') { $sExplanation .= $clang->gT("is") . " "; } elseif ($distinctrow['method'] == '!=') { $sExplanation .= $clang->gT("is NOT") . " "; } elseif ($distinctrow['method'] == '<') { $sExplanation .= $clang->gT("is less than") . " "; } elseif ($distinctrow['method'] == '<=') { $sExplanation .= $clang->gT("is less than or equal to") . " "; } elseif ($distinctrow['method'] == '>=') { $sExplanation .= $clang->gT("is greater than or equal to") . " "; } elseif ($distinctrow['method'] == '>') { $sExplanation .= $clang->gT("is greater than") . " "; } elseif ($distinctrow['method'] == 'RX') { $sExplanation .= $clang->gT("is matched (regexp)") . " "; } else { $sExplanation .= $clang->gT("is") . " "; } $answer_section = ' ' . $distinctrow['value'] . ' '; } $conresult = Condition::model()->getConditionsQuestions($distinctrow['cqid'], $deqrow['qid'], $scenariorow['scenario'], $surveyprintlang); $conditions = array(); foreach ($conresult->readAll() as $conrow) { $postans = ""; $value = $conrow['value']; switch ($conrow['type']) { case "Y": switch ($conrow['value']) { case "Y": $conditions[] = $clang->gT("Yes"); break; case "N": $conditions[] = $clang->gT("No"); break; } break; case "G": switch ($conrow['value']) { case "M": $conditions[] = $clang->gT("Male"); break; case "F": $conditions[] = $clang->gT("Female"); break; } // switch break; case "A": case "B": case ":": case ";": case "5": $conditions[] = $conrow['value']; break; case "C": switch ($conrow['value']) { case "Y": $conditions[] = $clang->gT("Yes"); break; case "U": $conditions[] = $clang->gT("Uncertain"); break; case "N": $conditions[] = $clang->gT("No"); break; } // switch break; case "E": switch ($conrow['value']) { case "I": $conditions[] = $clang->gT("Increase"); break; case "D": $conditions[] = $clang->gT("Decrease"); break; case "S": $conditions[] = $clang->gT("Same"); break; } case "1": $labelIndex = preg_match("/^[^#]+#([01]{1})\$/", $conrow['cfieldname']); if ($labelIndex == 0) { // TIBO $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=0 AND language='{$surveyprintlang}'"; $fresult = Answer::model()->getAllRecords($condition); foreach ($fresult->readAll() as $frow) { $postans = $frow['answer']; $conditions[] = $frow['answer']; } // while } elseif ($labelIndex == 1) { $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=1 AND language='{$surveyprintlang}'"; $fresult = Answer::model()->getAllRecords($condition); foreach ($fresult->readAll() as $frow) { $postans = $frow['answer']; $conditions[] = $frow['answer']; } // while } break; case "L": case "!": case "O": case "R": $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; $ansresult = Answer::model()->findAll($condition); foreach ($ansresult as $ansrow) { $conditions[] = $ansrow['answer']; } if ($conrow['value'] == "-oth-") { $conditions[] = $clang->gT("Other"); } $conditions = array_unique($conditions); break; case "M": case "P": $condition = " parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$surveyprintlang}'"; $ansresult = Question::model()->findAll($condition); foreach ($ansresult as $ansrow) { $conditions[] = $ansrow['question']; } $conditions = array_unique($conditions); break; case "N": case "K": $conditions[] = $value; break; case "F": case "H": default: $value = substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X" . $conrow['cqid']) + strlen("X" . $conrow['cqid']), strlen($conrow['cfieldname'])); $condition = " qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$surveyprintlang}'"; $fresult = Answer::model()->getAllRecords($condition); foreach ($fresult->readAll() as $frow) { $postans = $frow['answer']; $conditions[] = $frow['answer']; } // while break; } // switch // Now let's complete the answer text with the answer_section $answer_section = ""; switch ($conrow['type']) { case "A": case "B": case "C": case "E": case "F": case "H": case "K": $thiscquestion = $fieldmap[$conrow['cfieldname']]; $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'"; $ansresult = Question::model()->findAll($condition); foreach ($ansresult as $ansrow) { $answer_section = " (" . $ansrow['question'] . ")"; } break; case "1": // dual: (Label 1), (Label 2) $labelIndex = substr($conrow['cfieldname'], -1); $thiscquestion = $fieldmap[$conrow['cfieldname']]; $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'"; $ansresult = Question::model()->findAll($condition); $cqidattributes = getQuestionAttributeValues($conrow['cqid'], $conrow['type']); if ($labelIndex == 0) { if (trim($cqidattributes['dualscale_headerA'][$surveyprintlang]) != '') { $header = $clang->gT($cqidattributes['dualscale_headerA'][$surveyprintlang]); } else { $header = '1'; } } elseif ($labelIndex == 1) { if (trim($cqidattributes['dualscale_headerB'][$surveyprintlang]) != '') { $header = $clang->gT($cqidattributes['dualscale_headerB'][$surveyprintlang]); } else { $header = '2'; } } foreach ($ansresult as $ansrow) { $answer_section = " (" . $ansrow->question . " " . sprintf($clang->gT("Label %s"), $header) . ")"; } break; case ":": case ";": //multi flexi: ( answer [label] ) $thiscquestion = $fieldmap[$conrow['cfieldname']]; $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$surveyprintlang}'"; $ansresult = Question::model()->findAll($condition); foreach ($ansresult as $ansrow) { $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$surveyprintlang}'"; $fresult = Answer::model()->findAll($condition); foreach ($fresult as $frow) { //$conditions[]=$frow['title']; $answer_section = " (" . $ansrow->question . "[" . $frow['answer'] . "])"; } // while } break; case "R": // (Rank 1), (Rank 2)... TIBO $thiscquestion = $fieldmap[$conrow['cfieldname']]; $rankid = $thiscquestion['aid']; $answer_section = " (" . $clang->gT("RANK") . " {$rankid})"; break; default: // nothing to add break; } } if (count($conditions) > 1) { $sExplanation .= "'" . implode("' <em class='scenario-or-separator'>" . $clang->gT("or") . "</em> '", $conditions) . "'"; } elseif (count($conditions) == 1) { $sExplanation .= "'" . $conditions[0] . "'"; } unset($conditions); // Following line commented out because answer_section was lost, but is required for some question types //$explanation .= " ".$clang->gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section "; if ($distinctrow['cqid']) { $sExplanation .= " <span class='scenario-at-separator'>" . $clang->gT("at question") . "</span> '" . $mapquestionsNumbers[$distinctrow['cqid']] . " [" . $subresult['title'] . "]' (" . strip_tags($subresult['question']) . "{$answer_section})"; } else { $sExplanation .= " " . $distinctrow['value']; } //$distinctrow $x++; } $s++; } $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']); $relevance = trim($qinfo['info']['relevance']); $sEquation = $qinfo['relEqn']; if (trim($relevance) != '' && trim($relevance) != '1') { if (isset($qidattributes['printable_help'][$surveyprintlang]) && $qidattributes['printable_help'][$surveyprintlang] != '') { $sExplanation = $qidattributes['printable_help'][$surveyprintlang]; } elseif ($sExplanation == '') { $sExplanation = $sEquation; $sEquation = ' '; // No need to show it twice } $sExplanation = "<b>" . $clang->gT('Only answer this question if the following conditions are met:') . "</b><br/> " . $sExplanation; if (Yii::app()->getConfig('showrelevance')) { $sExplanation .= "<span class='printable_equation'><br>" . $sEquation . "</span>"; } } else { $sExplanation = ''; } ++$total_questions; //TIBO map question qid to their q number $mapquestionsNumbers[$deqrow['qid']] = $total_questions; //END OF GETTING CONDITIONS $qid = $deqrow['qid']; $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}"; if (isset($showsgqacode) && $showsgqacode == true) { $deqrow['question'] = $deqrow['question'] . "<br />" . $clang->gT("ID:") . " {$fieldname} <br />" . $clang->gT("Question code:") . " " . $deqrow['title']; } $question = array('QUESTION_NUMBER' => $total_questions, 'QUESTION_CODE' => $deqrow['title'], 'QUESTION_TEXT' => preg_replace('/(?:<br ?\\/?>|<\\/(?:p|h[1-6])>)$/is', '', $deqrow['question']), 'QUESTION_SCENARIO' => $sExplanation, 'QUESTION_MANDATORY' => '', 'QUESTION_ID' => $deqrow['qid'], 'QUESTION_CLASS' => getQuestionClass($deqrow['type']), 'QUESTION_TYPE_HELP' => $qinfo['validTip'], 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTIONHELP' => '', 'ANSWER' => ''); $showqnumcode = Yii::app()->getConfig('showqnumcode'); if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'N' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'number' || $showqnumcode == 'none') { $question['QUESTION_CODE'] = ''; } if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'C' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'code' || $showqnumcode == 'none') { $question['QUESTION_NUMBER'] = ''; } if ($question['QUESTION_TYPE_HELP'] != "") { $question['QUESTION_TYPE_HELP'] .= "<br />\n"; } if ($deqrow['mandatory'] == 'Y') { $question['QUESTION_MANDATORY'] = $clang->gT('*'); $question['QUESTION_CLASS'] .= ' mandatory'; } //DIFFERENT TYPES OF DATA FIELD HERE if ($deqrow['help']) { $question['QUESTIONHELP'] = $deqrow['help']; } if (!empty($qidattributes['page_break'])) { $question['QUESTION_CLASS'] .= ' breakbefore '; } if (isset($qidattributes['maximum_chars']) && $qidattributes['maximum_chars'] != '') { $question['QUESTION_CLASS'] = "max-chars-{$qidattributes['maximum_chars']} " . $question['QUESTION_CLASS']; } switch ($deqrow['type']) { // ================================================================== case "5": //5 POINT CHOICE $question['QUESTION_TYPE_HELP'] .= $clang->gT('Please choose *only one* of the following:'); $question['ANSWER'] .= "\n\t<ul>\n"; for ($i = 1; $i <= 5; $i++) { $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $i) . "\n\t\t\t{$i} " . self::_addsgqacode("({$i})") . "\n\t\t</li>\n"; } $question['ANSWER'] .= "\t</ul>\n"; break; // ================================================================== // ================================================================== case "D": //DATE $question['QUESTION_TYPE_HELP'] .= $clang->gT('Please enter a date:'); $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1); break; // ================================================================== // ================================================================== case "G": //GENDER $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:"); $question['ANSWER'] .= "\n\t<ul>\n"; $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $clang->gT("Female")) . "\n\t\t\t" . $clang->gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n"; $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $clang->gT("Male")) . "\n\t\t\t" . $clang->gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n"; $question['ANSWER'] .= "\t</ul>\n"; break; // ================================================================== // ================================================================== case "L": //LIST drop-down/radio-button list // ================================================================== //LIST drop-down/radio-button list // ================================================================== case "!": //List - dropdown if (isset($qidattributes['display_columns']) && trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') { $optCategorySeparator = $qidattributes['category_separator']; } else { unset($optCategorySeparator); } $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('sortorder', 'answer')); $dearesult = $dearesult->readAll(); $deacount = count($dearesult); if ($deqrow['other'] == "Y") { $deacount++; } $wrapper = setupColumns(0, $deacount); $question['ANSWER'] = $wrapper['whole-start']; $rowcounter = 0; $colcounter = 1; foreach ($dearesult as $dearow) { if (isset($optCategorySeparator)) { list($category, $answer) = explode($optCategorySeparator, $dearow['answer']); if ($category != '') { $dearow['answer'] = "({$category}) {$answer} " . self::_addsgqacode("(" . $dearow['code'] . ")"); } else { $dearow['answer'] = $answer . self::_addsgqacode(" (" . $dearow['code'] . ")"); } $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . "\n" . $wrapper['item-end']; } else { $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n" . $wrapper['item-end']; } ++$rowcounter; if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols'] - 1) { $question['ANSWER'] .= $wrapper['col-devide-last']; } else { $question['ANSWER'] .= $wrapper['col-devide']; } $rowcounter = 0; ++$colcounter; } } if ($deqrow['other'] == 'Y') { if (trim($qidattributes["other_replace_text"][$surveyprintlang]) == '') { $qidattributes["other_replace_text"][$surveyprintlang] = "Other"; } // $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , $clang->gT("Other"))."\n\t\t\t".$clang->gT("Other")."\n\t\t\t<input type='text' size='30' readonly='readonly' />\n".$wrapper['item-end']; $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('radio', $clang->gT($qidattributes["other_replace_text"][$surveyprintlang])) . ' ' . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . self::_addsgqacode(" (-oth-)") . "\n\t\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "other)") . "\n" . $wrapper['item-end']; } $question['ANSWER'] .= $wrapper['whole-end']; //Let's break the presentation into columns. break; // ================================================================== // ================================================================== case "O": //LIST WITH COMMENT $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:"); $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'answer')); $question['ANSWER'] = "\t<ul>\n"; foreach ($dearesult->readAll() as $dearow) { $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n\t\t</li>\n"; } $question['ANSWER'] .= "\t</ul>\n"; $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . $clang->gT("Make a comment on your choice here:") . "\n"; $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', $clang->gT("Make a comment on your choice here:"), 50, 8) . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "comment)") . "\n\t</p>\n"; break; // ================================================================== // ================================================================== case "R": //RANKING Type Question $rearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'answer')); $rearesult = $rearesult->readAll(); $reacount = count($rearesult); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please number each box in order of preference from 1 to") . " {$reacount}"; $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] = "\n<ul>\n"; foreach ($rearesult as $rearow) { $question['ANSWER'] .= "\t<li>\n\t" . self::_input_type_image('rank', '', 4, 1) . "\n\t\t " . $rearow['answer'] . self::_addsgqacode(" (" . $fieldname . $rearow['code'] . ")") . "\n\t</li>\n"; } $question['ANSWER'] .= "\n</ul>\n"; break; // ================================================================== // ================================================================== case "M": //Multiple choice (Quite tricky really!) if (trim($qidattributes['display_columns']) != '') { $dcols = $qidattributes['display_columns']; } else { $dcols = 0; } $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *all* that apply:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); $mearesult = $mearesult->readAll(); $meacount = count($mearesult); if ($deqrow['other'] == 'Y') { $meacount++; } $wrapper = setupColumns($dcols, $meacount); $question['ANSWER'] = $wrapper['whole-start']; $rowcounter = 0; $colcounter = 1; foreach ($mearesult as $mearow) { $question['ANSWER'] .= $wrapper['item-start'] . self::_input_type_image('checkbox', $mearow['question']) . "\n\t\t" . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . $wrapper['item-end']; ++$rowcounter; if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) { if ($colcounter == $wrapper['cols'] - 1) { $question['ANSWER'] .= $wrapper['col-devide-last']; } else { $question['ANSWER'] .= $wrapper['col-devide']; } $rowcounter = 0; ++$colcounter; } } if ($deqrow['other'] == "Y") { if (trim($qidattributes['other_replace_text'][$surveyprintlang]) == '') { $qidattributes["other_replace_text"][$surveyprintlang] = "Other"; } if (!isset($mearow['answer'])) { $mearow['answer'] = ""; } $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . $clang->gT($qidattributes["other_replace_text"][$surveyprintlang]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end']; } $question['ANSWER'] .= $wrapper['whole-end']; // } break; // ================================================================== // ================================================================== case "P": //Multiple choice with comments $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose all that apply and provide a comment:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('question_order')); // $printablesurveyoutput .="\t\t\t<u>".$clang->gT("Please choose all that apply and provide a comment:")."</u><br />\n"; $j = 0; $longest_string = 0; foreach ($mearesult->readAll() as $mearow) { $longest_string = longestString($mearow['question'], $longest_string); $question['ANSWER'] .= "\t<li><span>\n\t\t" . self::_input_type_image('checkbox', $mearow['question']) . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "</span>\n\t\t" . self::_input_type_image('text', 'comment box', 60) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "comment) ") . "\n\t</li>\n"; $j++; } if ($deqrow['other'] == "Y") { $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . $clang->gT('Other:') . self::_input_type_image('other', '', 1) . "</div>" . self::_input_type_image('othercomment', 'comment box', 50) . self::_addsgqacode(" (" . $fieldname . "other) ") . "\n\t</li>\n"; $j++; } $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n"; break; // ================================================================== // ================================================================== case "Q": //MULTIPLE SHORT TEXT $width = 60; // ================================================================== // ================================================================== case "K": //MULTIPLE NUMERICAL $question['QUESTION_TYPE_HELP'] = ""; $width = isset($width) ? $width : 16; // if (!empty($qidattributes['equals_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= "* ".sprintf($clang->gT('Total of all entries must equal %d'),$qidattributes['equals_num_value'])."<br />\n"; // } // if (!empty($qidattributes['max_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= sprintf($clang->gT('Total of all entries must not exceed %d'), $qidattributes['max_num_value'])."<br />\n"; // } // if (!empty($qidattributes['min_num_value'])) // { // $question['QUESTION_TYPE_HELP'] .= sprintf($clang->gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n"; // } $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer(s) here:"); $longest_string = 0; $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $longest_string = longestString($mearow['question'], $longest_string); if (isset($qidattributes['slider_layout']) && $qidattributes['slider_layout'] == 1) { $mearow['question'] = explode(':', $mearow['question']); $mearow['question'] = $mearow['question'][0]; } $question['ANSWER'] .= "\t<li>\n\t\t<span>" . $mearow['question'] . "</span>\n\t\t" . self::_input_type_image('text', $mearow['question'], $width) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "\n\t</li>\n"; } $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n"; break; // ================================================================== // ================================================================== case "S": //SHORT TEXT $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50); break; // ================================================================== // ================================================================== case "T": //LONG TEXT $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8); break; // ================================================================== // ================================================================== case "U": //HUGE TEXT $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:"); $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30); break; // ================================================================== // ================================================================== case "N": //NUMERICAL $prefix = ""; $suffix = ""; if ($qidattributes['prefix'][$surveyprintlang] != "") { $prefix = $qidattributes['prefix'][$surveyprintlang]; } if ($qidattributes['suffix'][$surveyprintlang] != "") { $suffix = $qidattributes['suffix'][$surveyprintlang]; } $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please write your answer here:"); $question['ANSWER'] = "<ul>\n\t<li>\n\t\t<span>{$prefix}</span>\n\t\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 20) . "\n\t\t<span>{$suffix}</span>\n\t\t</li>\n\t</ul>"; break; // ================================================================== // ================================================================== case "Y": //YES/NO $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose *only one* of the following:"); $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', $clang->gT('Yes')) . "\n\t\t" . $clang->gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n"; $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', $clang->gT('No')) . "\n\t\t" . $clang->gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n"; break; // ================================================================== // ================================================================== case "A": //ARRAY (5 POINT CHOICE) $condition = "parent_qid = '{$deqrow['qid']}' AND language= '{$surveyprintlang}'"; $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] = "\n <table>\n <thead>\n <tr>\n <td> </td>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>1 " . self::_addsgqacode(" (1)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>2 " . self::_addsgqacode(" (2)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>3 " . self::_addsgqacode(" (3)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>4 " . self::_addsgqacode(" (4)") . "</th>\n <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>5" . self::_addsgqacode(" (5)") . "</th>\n </tr>\n </thead>\n <tbody>"; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords($condition, array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " "; } else { $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")"); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= 5; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n"; } $answertext .= $mearow['question']; //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</td>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $j++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "B": //ARRAY (10 POINT CHOICE) $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; for ($i = 1; $i <= 10; $i++) { $question['ANSWER'] .= "\t\t\t<th>{$i}" . self::_addsgqacode(" ({$i})") . "</th>\n"; } $question['ANSWER'] .= "\t</thead>\n\n\t<tbody>\n"; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $rowclass = alternation($rowclass, 'row'); for ($i = 1; $i <= 10; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $j++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "C": //ARRAY (YES/UNCERTAIN/NO) $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] = ' <table> <thead> <tr> <td> </td> <th>' . $clang->gT("Yes") . self::_addsgqacode(" (Y)") . '</th> <th>' . $clang->gT("Uncertain") . self::_addsgqacode(" (U)") . '</th> <th>' . $clang->gT("No") . self::_addsgqacode(" (N)") . '</th> </tr> </thead> <tbody> '; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Yes")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Uncertain")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("No")) . "</td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $j++; $rowclass = alternation($rowclass, 'row'); } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; case "E": //ARRAY (Increase/Same/Decrease) $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] = ' <table> <thead> <tr> <td> </td> <th>' . $clang->gT("Increase") . self::_addsgqacode(" (I)") . '</th> <th>' . $clang->gT("Same") . self::_addsgqacode(" (S)") . '</th> <th>' . $clang->gT("Decrease") . self::_addsgqacode(" (D)") . '</th> </tr> </thead> <tbody> '; $j = 0; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Increase")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Same")) . "</td>\n"; $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $clang->gT("Decrease")) . "</td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $j++; $rowclass = alternation($rowclass, 'row'); } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case ":": //ARRAY (Multi Flexible) (Numbers) $headstyle = "style='padding-left: 20px; padding-right: 7px'"; if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') { $maxvalue = $qidattributes['multiflexible_max']; $minvalue = 1; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_min'] + 10; } if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') { $minvalue = 1; $maxvalue = 10; } if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') { if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) { $minvalue = $qidattributes['multiflexible_min']; $maxvalue = $qidattributes['multiflexible_max']; } } if (trim($qidattributes['multiflexible_step']) != '') { $stepvalue = $qidattributes['multiflexible_step']; } else { $stepvalue = 1; } if ($qidattributes['multiflexible_checkbox'] != 0) { $checkboxlayout = true; } else { $checkboxlayout = false; } $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$surveyprintlang}' ", array('question_order')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 0; //array to temporary store X axis question codes $xaxisarray = array(); foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n"; $i++; //add current question code $xaxisarray[$i] = $frow['title']; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $a = 1; //Counter for pdfoutput $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$surveyprintlang}' ", array('question_order')); $result = $mearesult->readAll(); foreach ($result as $frow) { $question['ANSWER'] .= "\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $frow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; //$printablesurveyoutput .="\t\t\t\t\t<td>"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>\n"; if ($checkboxlayout === false) { $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 4) . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; } else { $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; } $question['ANSWER'] .= "\t\t\t</td>\n"; } $answertext = $frow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case ";": //ARRAY (Multi Flexible) (text) $headstyle = "style='padding-left: 20px; padding-right: 7px'"; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$surveyprintlang}' ", array('question_order')); $mearesult = $mearesult->readAll(); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=1 AND language='{$surveyprintlang}' ", array('question_order')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 0; //array to temporary store X axis question codes $xaxisarray = array(); foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n"; $i++; //add current question code $xaxisarray[$i] = $frow['title']; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n<tbody>\n"; $a = 1; $rowclass = 'array1'; foreach ($mearesult as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>\n"; $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 23) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n"; $question['ANSWER'] .= "\t\t\t</td>\n"; } $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "F": //ARRAY (Flexible Labels) $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $fresult = Answer::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}' AND language='{$surveyprintlang}'", array('sortorder', 'code')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $i = 1; $column_headings = array(); foreach ($fresult as $frow) { $column_headings[] = $frow['answer'] . self::_addsgqacode(" (" . $frow['code'] . ")"); } if (trim($qidattributes['answer_width']) != '') { $iAnswerWidth = 100 - $qidattributes['answer_width']; } else { $iAnswerWidth = 80; } if (count($column_headings) > 0) { $col_width = round($iAnswerWidth / count($column_headings)); } else { $heading = ''; } $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n"; $question['ANSWER'] .= "\t\t\t<td> </td>\n"; foreach ($column_headings as $heading) { $question['ANSWER'] .= "\t\t\t<th style=\"width:{$col_width}%;\">{$heading}</th>\n"; } $i++; $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $counter = 1; $rowclass = 'array1'; $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); if (trim($answertext) == '') { $answertext = ' '; } //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " "; } else { $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")"); } if (trim($qidattributes['answer_width']) != '') { $sInsertStyle = ' style="width:' . $qidattributes['answer_width'] . '%" '; } else { $sInsertStyle = ''; } $question['ANSWER'] .= "\t\t\t<th {$sInsertStyle} class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $counter++; $answertext = $mearow['question']; //semantic differential question type? if (strpos($mearow['question'], '|')) { $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "1": //ARRAY (Flexible Labels) multi scale $leftheader = $qidattributes['dualscale_headerA'][$surveyprintlang]; $rightheader = $qidattributes['dualscale_headerB'][$surveyprintlang]; $headstyle = 'style="padding-left: 20px; padding-right: 7px"'; $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $surveyprintlang, $surveyid); $question['ANSWER'] .= "\n<table>\n\t<thead>\n"; $condition = "qid= '{$deqrow['qid']}' AND language= '{$surveyprintlang}' AND scale_id=0"; $fresult = Answer::model()->getAllRecords($condition, array('sortorder', 'code')); $fresult = $fresult->readAll(); $fcount = count($fresult); $fwidth = "120"; $l1 = 0; $printablesurveyoutput2 = "\t\t\t<td> </td>\n"; $myheader2 = ''; foreach ($fresult as $frow) { $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n"; $myheader2 .= "<td></td>"; $l1++; } // second scale $printablesurveyoutput2 .= "\t\t\t<td> </td>\n"; //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' AND scale_id=1 ORDER BY sortorder, code"; // $fresult1 = Yii::app()->db->createCommand($fquery1)->query(); $fresult1 = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$surveyprintlang}' AND scale_id=1 ", array('sortorder', 'code')); $fresult1 = $fresult1->readAll(); $fcount1 = count($fresult1); $fwidth = "120"; $l2 = 0; //array to temporary store second scale question codes $scale2array = array(); foreach ($fresult1 as $frow1) { $printablesurveyoutput2 .= "\t\t\t<th>{$frow1['answer']}" . self::_addsgqacode(" (" . $frow1['code'] . ")") . "</th>\n"; //add current question code $scale2array[$l2] = $frow1['code']; $l2++; } // build header if needed if ($leftheader != '' || $rightheader != '') { $myheader = "\t\t\t<td> </td>"; $myheader .= "\t\t\t<th colspan=\"" . $l1 . "\">{$leftheader}</th>\n"; if ($rightheader != '') { // $myheader .= "\t\t\t\t\t" .$myheader2; $myheader .= "\t\t\t<td> </td>"; $myheader .= "\t\t\t<th colspan=\"" . $l2 . "\">{$rightheader}</td>\n"; } $myheader .= "\t\t\t\t</tr>\n"; } else { $myheader = ''; } $question['ANSWER'] .= $myheader . "\t\t</tr>\n\n\t\t<tr>\n"; $question['ANSWER'] .= $printablesurveyoutput2; $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $rowclass = 'array1'; //counter for each subquestion $sqcounter = 0; $mearesult = Question::model()->getAllRecords(" parent_qid={$deqrow['qid']} AND language='{$surveyprintlang}' ", array('question_order')); foreach ($mearesult->readAll() as $mearow) { $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "#0) / (" . $fieldname . $mearow['title'] . "#1)"); if (strpos($answertext, '|')) { $answertext = substr($answertext, 0, strpos($answertext, '|')); } $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $question['ANSWER'] .= "\t\t\t<td> </td>\n"; for ($i = 1; $i <= $fcount1; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } $answertext = $mearow['question']; if (strpos($answertext, '|')) { $answertext = substr($answertext, strpos($answertext, '|') + 1); $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n"; } $question['ANSWER'] .= "\t\t</tr>\n"; //increase subquestion counter $sqcounter++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; // ================================================================== // ================================================================== case "H": //ARRAY (Flexible Labels) by Column //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'"; $headstyle = "style='padding-left: 20px; padding-right: 7px'"; $condition = "parent_qid= '{$deqrow['qid']}' AND language= '{$surveyprintlang}'"; $fresult = Question::model()->getAllRecords($condition, array('question_order', 'title')); $fresult = $fresult->readAll(); $question['QUESTION_TYPE_HELP'] .= $clang->gT("Please choose the appropriate response for each item:"); $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td> </td>\n"; $fcount = count($fresult); $fwidth = "120"; $i = 0; foreach ($fresult as $frow) { $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n"; $i++; } $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n"; $a = 1; $rowclass = 'array1'; $mearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$surveyprintlang}' ", array('sortorder', 'code')); foreach ($mearesult->readAll() as $mearow) { //$_POST['type']=$type; $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n"; $rowclass = alternation($rowclass, 'row'); $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['answer']}" . self::_addsgqacode(" (" . $mearow['code'] . ")") . "</th>\n"; //$printablesurveyoutput .="\t\t\t\t\t<td>"; for ($i = 1; $i <= $fcount; $i++) { $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n"; } //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n"; $question['ANSWER'] .= "\t\t</tr>\n"; $a++; } $question['ANSWER'] .= "\t</tbody>\n</table>\n"; break; case "|": // File Upload $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey"; break; // === END SWITCH =================================================== } $question['QUESTION_TYPE_HELP'] = self::_star_replace($question['QUESTION_TYPE_HELP']); $group['QUESTIONS'] .= self::_populate_template('question', $question); } if ($bGroupHasVisibleQuestions) { $survey_output['GROUPS'] .= self::_populate_template('group', $group); } } $survey_output['THEREAREXQUESTIONS'] = str_replace('{NUMBEROFQUESTIONS}', $total_questions, $clang->gT('There are {NUMBEROFQUESTIONS} questions in this survey')); // START recursive tag stripping. // PHP 5.1.0 introduced the count parameter for preg_replace() and thus allows this procedure to run with only one regular expression. // Previous version of PHP needs two regular expressions to do the same thing and thus will run a bit slower. $server_is_newer = version_compare(PHP_VERSION, '5.1.0', '>'); $rounds = 0; while ($rounds < 1) { $replace_count = 0; if ($server_is_newer) { $survey_output['GROUPS'] = preg_replace(array('/<td>(?: | | )?<\\/td>/isU', '/<th[^>]*>(?: | | )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS'], -1, $replace_count); } else { $survey_output['GROUPS'] = preg_replace(array('/<td>(?: | | )?<\\/td>/isU', '/<th[^>]*>(?: | | )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS']); $replace_count = preg_match('/<([^ >]+)[^>]*>(?: | |\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU', $survey_output['GROUPS']); } if ($replace_count == 0) { ++$rounds; $survey_output['GROUPS'] = preg_replace(array('/\\[\\[EMPTY-TABLE-CELL\\]\\]/', '/\\[\\[EMPTY-TABLE-CELL-HEADER\\]\\]/', '/\\n(?:\\t*\\n)+/'), array('<td> </td>', '<th> </th>', "\n"), $survey_output['GROUPS']); } } $survey_output['GROUPS'] = preg_replace('/(<div[^>]*>){NOTEMPTY}(<\\/div>)/', '\\1 \\2', $survey_output['GROUPS']); // END recursive empty tag stripping. echo self::_populate_template('survey', $survey_output); } // End print }
$baselang = $defaultlang; } if (isset($_REQUEST['embedded_inc'])) { safe_die('You cannot start this script directly'); } if ($embedded_inc != '') { require_once $embedded_inc; } //CHECK FOR REQUIRED INFORMATION (sid) if (!$surveyid) { if (isset($_GET['lang'])) { $baselang = sanitize_languagecode($_GET['lang']); } elseif (!isset($baselang)) { $baselang = $defaultlang; } $clang = new limesurvey_lang($baselang); if (!isset($defaulttemplate)) { $defaulttemplate = "default"; } $languagechanger = makelanguagechanger(); //Find out if there are any publicly available surveys $query = "SELECT a.sid, b.surveyls_title, a.publicstatistics\n\t FROM " . db_table_name('surveys') . " AS a\n\t\t\t INNER JOIN " . db_table_name('surveys_languagesettings') . " AS b\n\t\t\t ON ( surveyls_survey_id = a.sid AND surveyls_language = a.language )\n\t\t\t WHERE surveyls_survey_id=a.sid\n\t\t\t AND surveyls_language=a.language\n\t\t\t AND a.active='Y'\n\t\t\t AND a.listpublic='Y'\n\t\t\t AND ((a.expires >= '" . date("Y-m-d H:i") . "') OR (a.expires is null))\n AND ((a.startdate <= '" . date("Y-m-d H:i") . "') OR (a.startdate is null))\n\t\t\t ORDER BY surveyls_title"; $result = db_execute_assoc($query, false, true) or die("Could not connect to database. If you try to install LimeSurvey please refer to the <a href='http://docs.limesurvey.org'>installation docs</a> and/or contact the system administrator of this webpage."); //Checked $list = array(); if ($result->RecordCount() > 0) { while ($rows = $result->FetchRow()) { $result2 = db_execute_assoc("Select surveyls_title from " . db_table_name('surveys_languagesettings') . " where surveyls_survey_id={$rows['sid']} and surveyls_language='{$baselang}'"); if ($result2->RecordCount()) { $languagedetails = $result2->FetchRow(); $rows['surveyls_title'] = $languagedetails['surveyls_title'];
public function init(SurveyObj $survey, $sLanguageCode, FormattingOptions $oOptions) { parent::init($survey, $sLanguageCode, $oOptions); $pdfdefaultfont = Yii::app()->getConfig('pdfdefaultfont'); $pdffontsize = Yii::app()->getConfig('pdffontsize'); $pdforientation = Yii::app()->getConfig('pdforientation'); $clang = new limesurvey_lang($sLanguageCode); if ($oOptions->output == 'file') { $this->pdfDestination = 'F'; } else { $this->pdfDestination = 'D'; } Yii::import('application.libraries.admin.pdf', true); if ($pdfdefaultfont == 'auto') { $pdfdefaultfont = PDF_FONT_NAME_DATA; } // Array of PDF core fonts: are replaced by according fonts according to the alternatepdffontfile array.Maybe just courier,helvetica and times but if a user want symbol: why not .... $pdfcorefont = array("courier", "helvetica", "symbol", "times", "zapfdingbats"); $pdffontsize = Yii::app()->getConfig('pdffontsize'); // create new PDF document $this->pdf = new pdf(); if (in_array($pdfdefaultfont, $pdfcorefont)) { $alternatepdffontfile = Yii::app()->getConfig('alternatepdffontfile'); if (array_key_exists($sLanguageCode, $alternatepdffontfile)) { $pdfdefaultfont = $alternatepdffontfile[$sLanguageCode]; // Actually use only core font } } if ($pdffontsize == 'auto') { $pdffontsize = PDF_FONT_SIZE_MAIN; } $this->pdf = new pdf(); $this->pdf->SetFont($pdfdefaultfont, '', $pdffontsize); $this->pdf->AddPage(); $this->pdf->intopdf("PDF export " . date("Y.m.d-H:i", time())); //Set some pdf metadata Yii::app()->loadHelper('surveytranslator'); $lg = array(); $lg['a_meta_charset'] = 'UTF-8'; if (getLanguageRTL($sLanguageCode)) { $lg['a_meta_dir'] = 'rtl'; } else { $lg['a_meta_dir'] = 'ltr'; } $lg['a_meta_language'] = $sLanguageCode; $lg['w_page'] = $clang->gT("page"); $this->pdf->setLanguageArray($lg); $this->separator = "\t"; $this->rowCounter = 0; $this->surveyName = $survey->languageSettings[0]['surveyls_title']; $this->pdf->titleintopdf($this->surveyName, $survey->languageSettings[0]['surveyls_description']); }
/** * This function generates an array containing the fieldcode, and matching data in the same order as the activate script * * @param string $surveyid The Survey ID * @param mixed $style 'short' (default) or 'full' - full creates extra information like default values * @param mixed $force_refresh - Forces to really refresh the array, not just take the session copy * @param int $questionid Limit to a certain qid only (for question preview) - default is false * @return array */ function createFieldMap($surveyid, $style = 'full', $force_refresh = false, $questionid = false, $sQuestionLanguage = null) { global $dbprefix, $connect, $clang, $aDuplicateQIDs; $surveyid = sanitize_int($surveyid); //Get list of questions if (is_null($sQuestionLanguage)) { if (isset($_SESSION['s_lang']) && in_array($_SESSION['s_lang'], GetAdditionalLanguagesFromSurveyID($surveyid))) { $sQuestionLanguage = $_SESSION['s_lang']; } else { $sQuestionLanguage = GetBaseLanguageFromSurveyID($surveyid); } } $sQuestionLanguage = sanitize_languagecode($sQuestionLanguage); if ($clang->langcode != $sQuestionLanguage) { SetSurveyLanguage($surveyid, $sQuestionLanguage); } $s_lang = $clang->langcode; //checks to see if fieldmap has already been built for this page. if (isset($_SESSION['fieldmap-' . $surveyid . $s_lang]) && !$force_refresh && $questionid == false) { if (isset($_SESSION['adminlang']) && $clang->langcode != $_SESSION['adminlang']) { $clang = new limesurvey_lang($_SESSION['adminlang']); } return $_SESSION['fieldmap-' . $surveyid . $s_lang]; } $fieldmap["id"] = array("fieldname" => "id", 'sid' => $surveyid, 'type' => "id", "gid" => "", "qid" => "", "aid" => ""); if ($style == "full") { $fieldmap["id"]['title'] = ""; $fieldmap["id"]['question'] = $clang->gT("Response ID"); $fieldmap["id"]['group_name'] = ""; } $fieldmap["submitdate"] = array("fieldname" => "submitdate", 'type' => "submitdate", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => ""); if ($style == "full") { $fieldmap["submitdate"]['title'] = ""; $fieldmap["submitdate"]['question'] = $clang->gT("Date submitted"); $fieldmap["submitdate"]['group_name'] = ""; } $fieldmap["lastpage"] = array("fieldname" => "lastpage", 'sid' => $surveyid, 'type' => "lastpage", "gid" => "", "qid" => "", "aid" => ""); if ($style == "full") { $fieldmap["lastpage"]['title'] = ""; $fieldmap["lastpage"]['question'] = $clang->gT("Last page"); $fieldmap["lastpage"]['group_name'] = ""; } $fieldmap["startlanguage"] = array("fieldname" => "startlanguage", 'sid' => $surveyid, 'type' => "startlanguage", "gid" => "", "qid" => "", "aid" => ""); if ($style == "full") { $fieldmap["startlanguage"]['title'] = ""; $fieldmap["startlanguage"]['question'] = $clang->gT("Start language"); $fieldmap["startlanguage"]['group_name'] = ""; } //Check for any additional fields for this survey and create necessary fields (token and datestamp and ipaddr) $pquery = "SELECT anonymized, datestamp, ipaddr, refurl FROM " . db_table_name('surveys') . " WHERE sid={$surveyid}"; $presult = db_execute_assoc($pquery); //Checked while ($prow = $presult->FetchRow()) { if ($prow['anonymized'] == "N") { $fieldmap["token"] = array("fieldname" => "token", 'sid' => $surveyid, 'type' => "token", "gid" => "", "qid" => "", "aid" => ""); if ($style == "full") { $fieldmap["token"]['title'] = ""; $fieldmap["token"]['question'] = $clang->gT("Token"); $fieldmap["token"]['group_name'] = ""; } } if ($prow['datestamp'] == "Y") { $fieldmap["datestamp"] = array("fieldname" => "datestamp", 'type' => "datestamp", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => ""); if ($style == "full") { $fieldmap["datestamp"]['title'] = ""; $fieldmap["datestamp"]['question'] = $clang->gT("Date last action"); $fieldmap["datestamp"]['group_name'] = ""; } $fieldmap["startdate"] = array("fieldname" => "startdate", 'type' => "startdate", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => ""); if ($style == "full") { $fieldmap["startdate"]['title'] = ""; $fieldmap["startdate"]['question'] = $clang->gT("Date started"); $fieldmap["startdate"]['group_name'] = ""; } } if ($prow['ipaddr'] == "Y") { $fieldmap["ipaddr"] = array("fieldname" => "ipaddr", 'type' => "ipaddress", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => ""); if ($style == "full") { $fieldmap["ipaddr"]['title'] = ""; $fieldmap["ipaddr"]['question'] = $clang->gT("IP address"); $fieldmap["ipaddr"]['group_name'] = ""; } } // Add 'refurl' to fieldmap. if ($prow['refurl'] == "Y") { $fieldmap["refurl"] = array("fieldname" => "refurl", 'type' => "url", 'sid' => $surveyid, "gid" => "", "qid" => "", "aid" => ""); if ($style == "full") { $fieldmap["refurl"]['title'] = ""; $fieldmap["refurl"]['question'] = $clang->gT("Referrer URL"); $fieldmap["refurl"]['group_name'] = ""; } } } // Collect all default values once so don't need separate query for each question with defaults // First collect language specific defaults $defaultsQuery = "SELECT a.qid, a.sqid, a.scale_id, a.specialtype, a.defaultvalue" . " FROM " . db_table_name('defaultvalues') . " as a, " . db_table_name('questions') . " as b" . " WHERE a.qid = b.qid" . " AND a.language = b.language" . " AND a.language = '{$s_lang}'" . " AND b.same_default=0" . " AND b.sid = " . $surveyid; $defaultResults = db_execute_assoc($defaultsQuery) or safe_die("Couldn't get list of default values in createFieldMap.<br/>{$defaultsQuery}<br/>" . $conect->ErrorMsg()); $defaultValues = array(); // indexed by question then subquestion foreach ($defaultResults as $dv) { if ($dv['specialtype'] != '') { $sq = $dv['specialtype']; } else { $sq = $dv['sqid']; } $defaultValues[$dv['qid'] . '~' . $sq] = $dv['defaultvalue']; } // Now overwrite language-specific defaults (if any) base language values for each question that uses same_defaults=1 $baseLanguage = GetBaseLanguageFromSurveyID($surveyid); $defaultsQuery = "SELECT a.qid, a.sqid, a.scale_id, a.specialtype, a.defaultvalue" . " FROM " . db_table_name('defaultvalues') . " as a, " . db_table_name('questions') . " as b" . " WHERE a.qid = b.qid" . " AND a.language = b.language" . " AND a.language = '{$baseLanguage}'" . " AND b.same_default=1" . " AND b.sid = " . $surveyid; $defaultResults = db_execute_assoc($defaultsQuery) or safe_die("Couldn't get list of default values in createFieldMap.<br/>{$defaultsQuery}<br/>" . $conect->ErrorMsg()); foreach ($defaultResults as $dv) { if ($dv['specialtype'] != '') { $sq = $dv['specialtype']; } else { $sq = $dv['sqid']; } $defaultValues[$dv['qid'] . '~' . $sq] = $dv['defaultvalue']; } $qtypes = getqtypelist('', 'array'); $aquery = "SELECT * " . " FROM " . db_table_name('questions') . " as questions, " . db_table_name('groups') . " as groups" . " WHERE questions.gid=groups.gid AND " . " questions.sid={$surveyid} AND " . " questions.language='{$s_lang}' AND " . " questions.parent_qid=0 AND " . " groups.language='{$s_lang}' "; if ($questionid !== false) { $aquery .= " and questions.qid={$questionid} "; } $aquery .= " ORDER BY group_order, question_order"; $aresult = db_execute_assoc($aquery) or safe_die("Couldn't get list of questions in createFieldMap function.<br />{$query}<br />" . $connect->ErrorMsg()); //Checked $questionSeq = -1; // this is incremental question sequence across all groups $groupSeq = -1; $_groupOrder = -1; while ($arow = $aresult->FetchRow()) { ++$questionSeq; // fix fact taht group_order may have gaps if ($_groupOrder != $arow['group_order']) { $_groupOrder = $arow['group_order']; ++$groupSeq; } // Conditions indicators are obsolete with EM. However, they are so tightly coupled into LS code that easider to just set values to 'N' for now and refactor later. $conditions = 'N'; $usedinconditions = 'N'; // Field identifier // GXQXSXA // G=Group Q=Question S=Subquestion A=Answer Option // If S or A don't exist then set it to 0 // Implicit (subqestion intermal to a question type ) or explicit qubquestions/answer count starts at 1 // Types "L", "!" , "O", "D", "G", "N", "X", "Y", "5","S","T","U","*" $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}"; if ($qtypes[$arow['type']]['subquestions'] == 0 && $arow['type'] != "R" && $arow['type'] != "|") { if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => "{$arow['type']}", 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => ""); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; if (isset($defaultValues[$arow['qid'] . '~0'])) { $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~0']; } } switch ($arow['type']) { case "L": //RADIO LIST //RADIO LIST case "!": //DROPDOWN LIST $fieldmap[$fieldname]['other'] = $arow['other']; // so that base variable knows whether has other value if ($arow['other'] == "Y") { $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "other"); // dgk bug fix line above. aid should be set to "other" for export to append to the field name in the header line. if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion'] = $clang->gT("Other"); $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; $fieldmap[$fieldname]['other'] = $arow['other']; if (isset($defaultValues[$arow['qid'] . '~other'])) { $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~other']; } } } break; case "O": //DROPDOWN LIST WITH COMMENT $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}comment"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "comment"); // dgk bug fix line below. aid should be set to "comment" for export to append to the field name in the header line. Also needed set the type element correctly. if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion'] = $clang->gT("Comment"); $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; } break; } } elseif ($qtypes[$arow['type']]['subquestions'] == 2 && $qtypes[$arow['type']]['answerscales'] == 0) { //MULTI FLEXI $abrows = getSubQuestions($surveyid, $arow['qid'], $s_lang); //Now first process scale=1 $answerset = array(); $answerList = array(); foreach ($abrows as $key => $abrow) { if ($abrow['scale_id'] == 1) { $answerset[] = $abrow; $answerList[] = array('code' => $abrow['title'], 'answer' => $abrow['question']); unset($abrows[$key]); } } reset($abrows); foreach ($abrows as $abrow) { foreach ($answerset as $answer) { $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}_{$answer['title']}"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'] . "_" . $answer['title'], "sqid" => $abrow['qid']); if ($abrow['other'] == "Y") { $alsoother = "Y"; } if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion1'] = $abrow['question']; $fieldmap[$fieldname]['subquestion2'] = $answer['question']; $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; $fieldmap[$fieldname]['preg'] = $arow['preg']; $fieldmap[$fieldname]['answerList'] = $answerList; } } } unset($answerset); } elseif ($arow['type'] == "1") { $abrows = getSubQuestions($surveyid, $arow['qid'], $s_lang); foreach ($abrows as $abrow) { $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}#0"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'], "scale_id" => 0); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion'] = $abrow['question']; $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['scale'] = $clang->gT('Scale 1'); $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; } $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}#1"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'], "scale_id" => 1); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion'] = $abrow['question']; $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['scale'] = $clang->gT('Scale 2'); $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; } } } elseif ($arow['type'] == "R") { //MULTI ENTRY $slots = $connect->GetOne("select count(code) from " . db_table_name('answers') . " where qid={$arow['qid']} and language='{$s_lang}'"); for ($i = 1; $i <= $slots; $i++) { $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$i}"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $i); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion'] = sprintf($clang->gT('Rank %s'), $i); $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; } } } elseif ($arow['type'] == "|") { $abquery = "SELECT value FROM " . db_table_name('question_attributes') . " WHERE attribute='max_num_of_files' AND qid=" . $arow['qid']; $abresult = db_execute_assoc($abquery) or safe_die("Couldn't get maximum\n number of files that can be uploaded <br />{$abquery}<br />" . $connect->ErrorMsg()); $abrow = $abresult->FetchRow(); $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}"; $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => ''); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['max_files'] = $abrow['value']; $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; } $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}" . "_filecount"; $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "filecount"); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = "filecount - " . $arow['question']; //$fieldmap[$fieldname]['subquestion']=$clang->gT("Comment"); $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; } } else { //MULTI ENTRY $abrows = getSubQuestions($surveyid, $arow['qid'], $s_lang); foreach ($abrows as $abrow) { $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, 'gid' => $arow['gid'], 'qid' => $arow['qid'], 'aid' => $abrow['title'], 'sqid' => $abrow['qid']); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion'] = $abrow['question']; $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; $fieldmap[$fieldname]['preg'] = $arow['preg']; if (isset($defaultValues[$arow['qid'] . '~' . $abrow['qid']])) { $fieldmap[$fieldname]['defaultvalue'] = $defaultValues[$arow['qid'] . '~' . $abrow['qid']]; } } if ($arow['type'] == "P") { $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}{$abrow['title']}comment"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => $abrow['title'] . "comment"); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion'] = $clang->gT('Comment'); $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; } } } if ($arow['other'] == "Y" && ($arow['type'] == "M" || $arow['type'] == "P")) { $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}other"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "other"); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion'] = $clang->gT('Other'); $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; $fieldmap[$fieldname]['other'] = $arow['other']; } if ($arow['type'] == "P") { $fieldname = "{$arow['sid']}X{$arow['gid']}X{$arow['qid']}othercomment"; if (isset($fieldmap[$fieldname])) { $aDuplicateQIDs[$arow['qid']] = array('fieldname' => $fieldname, 'question' => $arow['question'], 'gid' => $arow['gid']); } $fieldmap[$fieldname] = array("fieldname" => $fieldname, 'type' => $arow['type'], 'sid' => $surveyid, "gid" => $arow['gid'], "qid" => $arow['qid'], "aid" => "othercomment"); if ($style == "full") { $fieldmap[$fieldname]['title'] = $arow['title']; $fieldmap[$fieldname]['question'] = $arow['question']; $fieldmap[$fieldname]['subquestion'] = $clang->gT('Other comment'); $fieldmap[$fieldname]['group_name'] = $arow['group_name']; $fieldmap[$fieldname]['mandatory'] = $arow['mandatory']; $fieldmap[$fieldname]['hasconditions'] = $conditions; $fieldmap[$fieldname]['usedinconditions'] = $usedinconditions; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; $fieldmap[$fieldname]['other'] = $arow['other']; } } } } if (isset($fieldmap[$fieldname])) { $fieldmap[$fieldname]['relevance'] = $arow['relevance']; $fieldmap[$fieldname]['grelevance'] = $arow['grelevance']; $fieldmap[$fieldname]['questionSeq'] = $questionSeq; $fieldmap[$fieldname]['groupSeq'] = $groupSeq; $fieldmap[$fieldname]['preg'] = $arow['preg']; $fieldmap[$fieldname]['other'] = $arow['other']; $fieldmap[$fieldname]['help'] = $arow['help']; } else { --$questionSeq; // didn't generate a valid $fieldmap entry, so decrement the question counter to ensure they are sequential } } if (isset($fieldmap)) { if ($questionid == false) { // If the fieldmap was randomized, the master will contain the proper order. Copy that fieldmap with the new language settings. if (isset($_SESSION['fieldmap-' . $surveyid . '-randMaster'])) { $masterFieldmap = $_SESSION['fieldmap-' . $surveyid . '-randMaster']; $mfieldmap = $_SESSION[$masterFieldmap]; foreach ($mfieldmap as $fieldname => $mf) { if (isset($fieldmap[$fieldname])) { $f = $fieldmap[$fieldname]; if (isset($f['question'])) { $mf['question'] = $f['question']; } if (isset($f['subquestion'])) { $mf['subquestion'] = $f['subquestion']; } if (isset($f['subquestion1'])) { $mf['subquestion1'] = $f['subquestion1']; } if (isset($f['subquestion2'])) { $mf['subquestion2'] = $f['subquestion2']; } if (isset($f['group_name'])) { $mf['group_name'] = $f['group_name']; } if (isset($f['answerList'])) { $mf['answerList'] = $f['answerList']; } if (isset($f['defaultvalue'])) { $mf['defaultvalue'] = $f['defaultvalue']; } if (isset($f['help'])) { $mf['help'] = $f['help']; } } $mfieldmap[$fieldname] = $mf; } $fieldmap = $mfieldmap; } $_SESSION['fieldmap-' . $surveyid . $clang->langcode] = $fieldmap; } if (isset($_SESSION['adminlang']) && $clang->langcode != $_SESSION['adminlang']) { $clang = new limesurvey_lang($_SESSION['adminlang']); } return $fieldmap; } }
* LimeSurvey is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * * $Id: htmleditor-popup.php 8987 2010-07-27 12:59:34Z c_schmitz $ */ //Ensure script is not run directly, avoid path disclosure //include_once("login_check.php"); require_once dirname(__FILE__) . '/../config-defaults.php'; require_once dirname(__FILE__) . '/../common.php'; if (!isset($_GET['lang'])) { $clang = new limesurvey_lang("en"); } else { $clang = new limesurvey_lang($_GET['lang']); } if (!isset($_GET['fieldname']) || !isset($_GET['fieldtext'])) { $output = ' <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <html> <head> <title>LimeSurvey ' . $clang->gT("HTML Editor") . '</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> </head>' . ' <body> <div class="maintitle"> LimeSurvey ' . $clang->gT("HTML Editor") . ' </div> <hr />
* to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * * $Id: createdb.php 9622 2010-12-10 21:38:02Z c_schmitz $ */ //Ensure script is not run directly, avoid path disclosure if (isset($_REQUEST['rootdir'])) { die('You cannot start this script directly'); } require_once dirname(__FILE__) . '/../../config-defaults.php'; require_once dirname(__FILE__) . '/../../common.php'; require_once $rootdir . '/classes/core/language.php'; require_once dirname(__FILE__) . '/../admin_functions.php'; $clang = new limesurvey_lang("en"); $dbname = $databasename; sendcacheheaders(); echo getAdminHeader(); echo "<div class='messagebox ui-corner-all'><div class='header ui-widget-header' >" . $clang->gT("Create Database") . "</div><p>\n"; echo $clang->gT("Creating tables. This might take a moment...") . "<p> \n"; // In Step2 fill the database with data if (returnglobal('createdbstep2') == $clang->gT("Populate Database")) { $createdbtype = $databasetype; if ($databasetype == 'mysql' || $databasetype == 'mysqli') { @$connect->Execute("ALTER DATABASE `{$dbname}` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); $createdbtype = 'mysql'; } if ($createdbtype == 'mssql_n' || $createdbtype == 'odbc_mssql' || $createdbtype == 'odbtp') { $createdbtype = 'mssql'; }
} } else { // User already exists $isAuthenticated = true; } if ($isAuthenticated === true) { // user exists and was authenticated by webserver $fields = $result->FetchRow(); $_SESSION['loginID'] = intval($fields['uid']); $_SESSION['user'] = $fields['users_name']; $_SESSION['adminlang'] = $fields['lang']; $_SESSION['htmleditormode'] = $fields['htmleditormode']; $_SESSION['dateformat'] = $fields['dateformat']; $_SESSION['checksessionpost'] = sRandomChars(10); $_SESSION['pw_notify'] = false; $clang = new limesurvey_lang($_SESSION['adminlang']); $login = true; $loginsummary .= "<br /><span style='font-weight:bold;'>" . sprintf($clang->gT("Welcome %s!"), $_SESSION['user']) . "</span><br />"; $loginsummary .= $clang->gT("You logged in successfully."); if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] && strpos($_SERVER['QUERY_STRING'], "action=logout") === FALSE) { $_SESSION['metaHeader'] = "<meta http-equiv=\"refresh\"" . " content=\"1;URL={$scriptname}?" . $_SERVER['QUERY_STRING'] . "\" />"; $loginsummary .= "<p><font size='1'><i>" . $clang->gT("Reloading screen. Please wait.") . "</i></font>\n"; } $loginsummary .= "<br /><br />\n"; GetSessionUserRights($_SESSION['loginID']); } } } elseif ($action == "logout") { killSession(); $logoutsummary = '<p>' . $clang->gT("Logout successful."); } elseif ($action == "adduser" && $_SESSION['USER_RIGHT_CREATE_USER']) {
} } else { session_name("LimeSurveyRuntime-{$surveyid}"); } session_set_cookie_params(0, $relativeurl . '/'); @session_start(); if (isset($_SESSION['sid'])) { $surveyid = $_SESSION['sid']; } else { die('Invalid survey/session'); } //Debut session time out if (!isset($_SESSION['finished']) || !isset($_SESSION['srid'])) { require_once $rootdir . '/classes/core/language.php'; $baselang = GetBaseLanguageFromSurveyID($surveyid); $clang = new limesurvey_lang($baselang); //A nice exit sendcacheheaders(); doHeader(); echo templatereplace(file_get_contents(sGetTemplatePath(validate_templatedir("default")) . "/startpage.pstpl")); echo "<center><br />\n" . "\t<font color='RED'><strong>" . $clang->gT("ERROR") . "</strong></font><br />\n" . "\t" . $clang->gT("We are sorry but your session has expired.") . "<br />" . $clang->gT("Either you have been inactive for too long, you have cookies disabled for your browser, or there were problems with your connection.") . "<br />\n" . "\t" . sprintf($clang->gT("Please contact %s ( %s ) for further assistance."), $siteadminname, $siteadminemail) . "\n" . "</center><br />\n"; echo templatereplace(file_get_contents(sGetTemplatePath(validate_templatedir("default")) . "/endpage.pstpl")); doFooter(); exit; } //Fin session time out $id = $_SESSION['srid']; //I want to see the answers with this id $clang = $_SESSION['s_lang']; //A little bit of debug to see in the noodles plate /*if ($debug==2)
$dataentryoutput .= "<div class='successheader'>".$clang->gT("Record Deleted")." (ID: $id)</div><br /><br />\n" ."<input type='submit' value='".$clang->gT("Browse Responses")."' onclick=\"window.open('$scriptname?action=browse&sid=$surveyid&subaction=all', '_top')\" /><br /><br />\n" ."</div>\n"; } else { $slangs = GetAdditionalLanguagesFromSurveyID($surveyid); $baselang = GetBaseLanguageFromSurveyID($surveyid); array_unshift($slangs,$baselang); if(!isset($_GET['language']) || !in_array($_GET['language'],$slangs)) { $sDataEntryLanguage = $baselang; $blang = $clang; } else { $blang = new limesurvey_lang($_GET['language']); $sDataEntryLanguage = $_GET['language']; } $langlistbox = languageDropdown($surveyid,$sDataEntryLanguage); $thissurvey=getSurveyInfo($surveyid); //This is the default, presenting a blank dataentry form $fieldmap=createFieldMap($surveyid); // PRESENT SURVEY DATAENTRY SCREEN $dataentryoutput .= $surveyoptions; $dataentryoutput .= "<div class='header ui-widget-header'>".$clang->gT("Data entry")."</div>\n"; $dataentryoutput .= "<form action='$scriptname?action=dataentry' enctype='multipart/form-data' name='addsurvey' method='post' id='addsurvey'>\n" ."<table class='data-entry-tbl' cellspacing='0'>\n" ."\t<tr>\n"
} else { @session_name($stg_SessionName . '-runtime-' . $surveyid); } } else { @session_name($stg_SessionName . '-runtime-publicportal'); } } else { session_name("LimeSurveyRuntime-{$surveyid}"); } session_set_cookie_params(0, $relativeurl . '/admin/'); @session_start(); if (empty($_SESSION) || !isset($_SESSION['fieldname'])) { die("You don't have a valid session !"); } $baselang = GetBaseLanguageFromSurveyID($surveyid); $clang = new limesurvey_lang($baselang); $randfilename = 'futmp_' . sRandomChars(15); $sTempUploadDir = $tempdir . '/upload/'; $randfileloc = $sTempUploadDir . $randfilename; $filename = $_FILES['uploadfile']['name']; $size = 0.001 * $_FILES['uploadfile']['size']; $valid_extensions = strtolower($_POST['valid_extensions']); $maxfilesize = (int) $_POST['max_filesize']; $preview = $_POST['preview']; $fieldname = $_POST['fieldname']; $aFieldMap = createFieldMap($surveyid); if (!isset($aFieldMap[$fieldname])) { die; } $aAttributes = getQuestionAttributes($aFieldMap[$fieldname]['qid'], $aFieldMap[$fieldname]['type']); $valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']);
/** * Export quexml survey. */ function quexml_export($surveyi, $quexmllan) { global $dom, $quexmllang, $iSurveyID; $quexmllang = $quexmllan; $iSurveyID = $surveyi; $qlang = new limesurvey_lang($quexmllang); $dom = new DOMDocument('1.0', 'UTF-8'); //Title and survey id $questionnaire = $dom->createElement("questionnaire"); $Query = "SELECT * FROM {{surveys}},{{surveys_languagesettings}} WHERE sid={$iSurveyID} and surveyls_survey_id=sid and surveyls_language='" . $quexmllang . "'"; $QueryResult = Yii::app()->db->createCommand($Query)->query(); $Row = $QueryResult->read(); $questionnaire->setAttribute("id", $Row['sid']); $title = $dom->createElement("title", QueXMLCleanup($Row['surveyls_title'])); $questionnaire->appendChild($title); //investigator and datacollector $investigator = $dom->createElement("investigator"); $name = $dom->createElement("name"); $name = $dom->createElement("firstName"); $name = $dom->createElement("lastName"); $dataCollector = $dom->createElement("dataCollector"); $questionnaire->appendChild($investigator); $questionnaire->appendChild($dataCollector); //questionnaireInfo == welcome if (!empty($Row['surveyls_welcometext'])) { $questionnaireInfo = $dom->createElement("questionnaireInfo"); $position = $dom->createElement("position", "before"); $text = $dom->createElement("text", QueXMLCleanup($Row['surveyls_welcometext'])); $administration = $dom->createElement("administration", "self"); $questionnaireInfo->appendChild($position); $questionnaireInfo->appendChild($text); $questionnaireInfo->appendChild($administration); $questionnaire->appendChild($questionnaireInfo); } if (!empty($Row['surveyls_endtext'])) { $questionnaireInfo = $dom->createElement("questionnaireInfo"); $position = $dom->createElement("position", "after"); $text = $dom->createElement("text", QueXMLCleanup($Row['surveyls_endtext'])); $administration = $dom->createElement("administration", "self"); $questionnaireInfo->appendChild($position); $questionnaireInfo->appendChild($text); $questionnaireInfo->appendChild($administration); $questionnaire->appendChild($questionnaireInfo); } //section == group $Query = "SELECT * FROM {{groups}} WHERE sid={$iSurveyID} AND language='{$quexmllang}' order by group_order ASC"; $QueryResult = Yii::app()->db->createCommand($Query)->query(); //for each section foreach ($QueryResult->readAll() as $Row) { $gid = $Row['gid']; $section = $dom->createElement("section"); if (!empty($Row['group_name'])) { $sectionInfo = $dom->createElement("sectionInfo"); $position = $dom->createElement("position", "title"); $text = $dom->createElement("text", QueXMLCleanup($Row['group_name'])); $administration = $dom->createElement("administration", "self"); $sectionInfo->appendChild($position); $sectionInfo->appendChild($text); $sectionInfo->appendChild($administration); $section->appendChild($sectionInfo); } if (!empty($Row['description'])) { $sectionInfo = $dom->createElement("sectionInfo"); $position = $dom->createElement("position", "before"); $text = $dom->createElement("text", QueXMLCleanup($Row['description'])); $administration = $dom->createElement("administration", "self"); $sectionInfo->appendChild($position); $sectionInfo->appendChild($text); $sectionInfo->appendChild($administration); $section->appendChild($sectionInfo); } $section->setAttribute("id", $gid); //boilerplate questions convert to sectionInfo elements $Query = "SELECT * FROM {{questions}} WHERE sid={$iSurveyID} AND gid = {$gid} AND type LIKE 'X' AND language='{$quexmllang}' ORDER BY question_order ASC"; $QR = Yii::app()->db->createCommand($Query)->query(); foreach ($QR->readAll() as $RowQ) { $sectionInfo = $dom->createElement("sectionInfo"); $position = $dom->createElement("position", "before"); $text = $dom->createElement("text", QueXMLCleanup($RowQ['question'])); $administration = $dom->createElement("administration", "self"); $sectionInfo->appendChild($position); $sectionInfo->appendChild($text); $sectionInfo->appendChild($administration); $section->appendChild($sectionInfo); } //foreach question $Query = "SELECT * FROM {{questions}} WHERE sid={$iSurveyID} AND gid = {$gid} AND parent_qid=0 AND language='{$quexmllang}' AND type NOT LIKE 'X' ORDER BY question_order ASC"; $QR = Yii::app()->db->createCommand($Query)->query(); foreach ($QR->readAll() as $RowQ) { $question = $dom->createElement("question"); $type = $RowQ['type']; $qid = $RowQ['qid']; $other = false; if ($RowQ['other'] == 'Y') { $other = true; } //create a new text element for each new line $questiontext = explode('<br />', $RowQ['question']); foreach ($questiontext as $qt) { $txt = QueXMLCleanup($qt); if (!empty($txt)) { $text = $dom->createElement("text", $txt); $question->appendChild($text); } } //directive if (!empty($RowQ['help'])) { $directive = $dom->createElement("directive"); $position = $dom->createElement("position", "during"); $text = $dom->createElement("text", QueXMLCleanup($RowQ['help'])); $administration = $dom->createElement("administration", "self"); $directive->appendChild($position); $directive->appendChild($text); $directive->appendChild($administration); $question->appendChild($directive); } if (Yii::app()->getConfig('quexmlshowprintablehelp') == true) { $RowQ['printable_help'] = quexml_get_lengthth($qid, "printable_help", "", $quexmllang); if (!empty($RowQ['printable_help'])) { $directive = $dom->createElement("directive"); $position = $dom->createElement("position", "before"); $text = $dom->createElement("text", '[' . $qlang->gT('Only answer the following question if:') . " " . QueXMLCleanup($RowQ['printable_help']) . "]"); $administration = $dom->createElement("administration", "self"); $directive->appendChild($position); $directive->appendChild($text); $directive->appendChild($administration); $question->appendChild($directive); } } $response = $dom->createElement("response"); $sgq = $RowQ['title']; $response->setAttribute("varName", $sgq); switch ($type) { case "X": //BOILERPLATE QUESTION - none should appear break; case "5": //5 POINT CHOICE radio-buttons $response->appendChild(QueXMLFixedArray(array("1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5))); $question->appendChild($response); break; case "D": //DATE $response->appendChild(QueXMLCreateFree("date", "8", "")); $question->appendChild($response); break; case "L": //LIST drop-down/radio-button list $response->appendChild(QueXMLCreateFixed($qid, false, false, 0, $other, $sgq)); $question->appendChild($response); break; case "!": //List - dropdown $response->appendChild(QueXMLCreateFixed($qid, false, false, 0, $other, $sgq)); $question->appendChild($response); break; case "O": //LIST WITH COMMENT drop-down/radio-button list + textarea quexml_create_subQuestions($question, $qid, $sgq); $response = $dom->createElement("response"); $response->setAttribute("varName", QueXMLCleanup($sgq)); $response->appendChild(QueXMLCreateFixed($qid, false, false, 0, $other, $sgq)); $response2 = $dom->createElement("response"); $response2->setAttribute("varName", QueXMLCleanup($sgq) . "_comment"); $response2->appendChild(QueXMLCreateFree("longtext", "40", "")); $question->appendChild($response); $question->appendChild($response2); break; case "R": //RANKING STYLE quexml_create_subQuestions($question, $qid, $sgq, true); $Query = "SELECT COUNT(*) as sc FROM {{answers}} WHERE qid = {$qid} AND language='{$quexmllang}' "; $QRE = Yii::app()->db->createCommand($Query)->query(); //$QRE = mysql_query($Query) or die ("ERROR: $QRE<br />".mysql_error()); //$QROW = mysql_fetch_assoc($QRE); $QROW = $QRE->read(); $response->appendChild(QueXMLCreateFree("integer", strlen($QROW['sc']), "")); $question->appendChild($response); break; case "M": //Multiple choice checkbox quexml_create_multi($question, $qid, $sgq, false, false, $other); break; case "P": //Multiple choice with comments checkbox + text //Not yet implemented quexml_create_multi($question, $qid, $sgq, false, false, $other); //no comments added break; case "Q": //MULTIPLE SHORT TEXT quexml_create_subQuestions($question, $qid, $sgq); $response->appendChild(QueXMLCreateFree("text", quexml_get_lengthth($qid, "maximum_chars", "10"), "")); $question->appendChild($response); break; case "K": //MULTIPLE NUMERICAL quexml_create_subQuestions($question, $qid, $sgq); $response->appendChild(QueXMLCreateFree("integer", quexml_get_lengthth($qid, "maximum_chars", "10"), "")); $question->appendChild($response); break; case "N": //NUMERICAL QUESTION TYPE $response->appendChild(QueXMLCreateFree("integer", quexml_get_lengthth($qid, "maximum_chars", "10"), "")); $question->appendChild($response); break; case "S": //SHORT FREE TEXT // default is fieldlength of 24 characters. $response->appendChild(QueXMLCreateFree("text", quexml_get_lengthth($qid, "maximum_chars", "24"), "")); $question->appendChild($response); break; case "T": //LONG FREE TEXT $response->appendChild(QueXMLCreateFree("longtext", quexml_get_lengthth($qid, "display_rows", "40"), "")); $question->appendChild($response); break; case "U": //HUGE FREE TEXT $response->appendChild(QueXMLCreateFree("longtext", quexml_get_lengthth($qid, "display_rows", "80"), "")); $question->appendChild($response); break; case "Y": //YES/NO radio-buttons $response->appendChild(QueXMLFixedArray(array($qlang->gT("Yes") => 'Y', $qlang->gT("No") => 'N'))); $question->appendChild($response); break; case "G": //GENDER drop-down list $response->appendChild(QueXMLFixedArray(array($qlang->gT("Female") => 'F', $qlang->gT("Male") => 'M'))); $question->appendChild($response); break; case "A": //ARRAY (5 POINT CHOICE) radio-buttons quexml_create_subQuestions($question, $qid, $sgq); $response->appendChild(QueXMLFixedArray(array("1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5))); $question->appendChild($response); break; case "B": //ARRAY (10 POINT CHOICE) radio-buttons quexml_create_subQuestions($question, $qid, $sgq); $response->appendChild(QueXMLFixedArray(array("1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "10" => 10))); $question->appendChild($response); break; case "C": //ARRAY (YES/UNCERTAIN/NO) radio-buttons quexml_create_subQuestions($question, $qid, $sgq); $response->appendChild(QueXMLFixedArray(array($qlang->gT("Yes") => 'Y', $qlang->gT("Uncertain") => 'U', $qlang->gT("No") => 'N'))); $question->appendChild($response); break; case "E": //ARRAY (Increase/Same/Decrease) radio-buttons quexml_create_subQuestions($question, $qid, $sgq); $response->appendChild(QueXMLFixedArray(array($qlang->gT("Increase") => 'I', $qlang->gT("Same") => 'S', $qlang->gT("Decrease") => 'D'))); $question->appendChild($response); break; case "F": //ARRAY (Flexible) - Row Format //select subQuestions from answers table where QID quexml_create_subQuestions($question, $qid, $sgq); $response->appendChild(QueXMLCreateFixed($qid, false, false, 0, $other, $sgq)); $question->appendChild($response); //select fixed responses from break; case "H": //ARRAY (Flexible) - Column Format quexml_create_subQuestions($question, $RowQ['qid'], $sgq); $response->appendChild(QueXMLCreateFixed($qid, true, false, 0, $other, $sgq)); $question->appendChild($response); break; case "1": //Dualscale multi-flexi array //select subQuestions from answers table where QID quexml_create_subQuestions($question, $qid, $sgq); //get the header of the first scale of the dual scale question $Query = "SELECT value FROM {{question_attributes}} WHERE qid = {$qid} AND language='{$quexmllang}' AND attribute='dualscale_headerA'"; $QRE = Yii::app()->db->createCommand($Query)->query(); $QROW = $QRE->read(); $response = $dom->createElement("response"); if ($QROW['value']) { $response->setAttribute("varName", QueXMLCleanup($QROW['value'])); } $response->appendChild(QueXMLCreateFixed($qid, false, false, 0, $other, $sgq)); //get the header of the second scale of the dual scale question $Query = "SELECT value FROM {{question_attributes}} WHERE qid = {$qid} AND language='{$quexmllang}' AND attribute='dualscale_headerB'"; $QRE = Yii::app()->db->createCommand($Query)->query(); $QROW = $QRE->read(); $response2 = $dom->createElement("response"); if ($QROW['value']) { $response2->setAttribute("varName", QueXMLCleanup($QROW['value'])); } $response2->appendChild(QueXMLCreateFixed($qid, false, false, 1, $other, $sgq)); $question->appendChild($response); $question->appendChild($response2); break; case ":": //multi-flexi array numbers quexml_create_subQuestions($question, $qid, $sgq); //get multiflexible_checkbox - if set then each box is a checkbox (single fixed response) $mcb = quexml_get_lengthth($qid, 'multiflexible_checkbox', -1); if ($mcb != -1) { quexml_create_multi($question, $qid, $sgq, 1); } else { //get multiflexible_max and maximum_chars - if set then make boxes of max of these widths $mcm = max(quexml_get_lengthth($qid, 'maximum_chars', 1), strlen(quexml_get_lengthth($qid, 'multiflexible_max', 1))); quexml_create_multi($question, $qid, $sgq, 1, array('f' => 'integer', 'len' => $mcm, 'lab' => '')); } break; case ";": //multi-flexi array text quexml_create_subQuestions($question, $qid, $sgq); //foreach question where scale_id = 1 this is a textbox quexml_create_multi($question, $qid, $sgq, 1, array('f' => 'text', 'len' => quexml_get_lengthth($qid, 'maximum_chars', 10), 'lab' => '')); break; case "^": //SLIDER CONTROL - not supported $response->appendChild(QueXMLFixedArray(array("NOT SUPPORTED:{$type}" => 1))); $question->appendChild($response); break; } //End Switch $section->appendChild($question); } $questionnaire->appendChild($section); } $dom->appendChild($questionnaire); $dom->formatOutput = true; return $dom->saveXML(); }
break; default: header("Content-Disposition: attachment; filename=results-survey" . $surveyid . ".csv"); header("Content-type: text/comma-separated-values; charset=UTF-8"); $separator = ","; break; } header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: public"); // Export Language is set by default to surveybaselang // * the explang language code is used in SQL queries // * the alang object is used to translate headers and hardcoded answers // In the future it might be possible to 'post' the 'export language' from // the exportresults form $explang = $surveybaselang; $elang = new limesurvey_lang($explang); //STEP 1: First line is column headings $fieldmap = createFieldMap($surveyid, 'full'); if ($thissurvey['savetimings'] === "Y") { //Append survey timings to the fieldmap array $fieldmap = $fieldmap + createTimingsFieldMap($surveyid, 'full'); } //Get the fieldnames from the survey table for column headings $surveytable = "{$dbprefix}survey_{$surveyid}"; if (isset($_POST['colselect'])) { $selectfields = ""; foreach ($_POST['colselect'] as $cs) { if (!isset($fieldmap[$cs]) && !isset($aTokenFieldNames[$cs]) && $cs != 'completed') { continue; } // skip invalid field names to prevent SQL injection
* other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * * $Id: index.php 10268 2011-06-15 09:17:29Z c_schmitz $ */ if (isset($_REQUEST['rootdir'])) { die('You cannot start this script directly'); } $action = ''; require_once dirname(__FILE__) . '/../../config-defaults.php'; require_once dirname(__FILE__) . '/../../common.php'; require_once dirname(__FILE__) . '/../admin_functions.php'; require_once dirname(__FILE__) . '/../update/updater.php'; // SET THE LANGUAGE???? -> DEFAULT SET TO EN FOR NOW require_once $rootdir . '/classes/core/language.php'; $clang = new limesurvey_lang("en"); $adminoutput = getAdminHeader(); // Alle future output is written into this and then outputted at the end of file ob_implicit_flush(true); sendcacheheaders(); if (!$database_exists) { $adminoutput .= "<br />\n" . "<table width='350' align='center' style='border: 1px solid #555555' cellpadding='1' cellspacing='0'>\n" . "\t<tr bgcolor='#555555'><td colspan='2' height='4'><font size='1' face='verdana' color='white'><strong>" . $clang->gT("LimeSurvey Setup") . "</strong></td></tr>\n" . "\t<tr bgcolor='#CCCCCC'><td align='center'>\n" . "<strong>" . $clang->gT("Welcome to LimeSurvey Setup!") . "</strong><br /><br />\n" . $clang->gT("The database defined in config.php does not exist.") . "<br />\n" . $clang->gT("LimeSurvey can attempt to create this database for you.") . "<br /><br />\n" . $clang->gT("Your selected database name is:") . "<strong> {$databasename}</strong><br />\n" . "<br /><input type='submit' value='" . $clang->gT("Create Database") . "' onclick='location.href=\"createdb.php\"' /></center>\n" . "</td></tr></table>\n" . "</body>\n</html>\n"; } elseif ($dbexistsbutempty && !(returnglobal('createdbstep2') == $clang->gT("Populate Database"))) { $connect->database = $databasename; $connect->Execute("USE DATABASE `{$databasename}`"); $adminoutput .= "<div class='messagebox ui-corner-all'><div class='header ui-widget-header' >" . $clang->gT("LimeSurvey Setup") . "</div>\n"; $adminoutput .= "<br /><div class='successtitle'>\n"; $adminoutput .= sprintf($clang->gT('A database named "%s" already exists.'), $databasename) . "</div><p>\n"; $adminoutput .= $clang->gT("Do you want to populate that database now by creating the necessary tables?") . "<br /><br />\n"; $adminoutput .= "<form method='post' action='createdb.php'>"; $adminoutput .= "<input type='submit' name='createdbstep2' value='" . $clang->gT("Populate Database") . "'></form></div>";
{ @session_name($stg_SessionName.'-runtime-'.$surveyid); } else { @session_name($stg_SessionName.'-runtime-publicportal'); } } else { session_name("LimeSurveyRuntime-$surveyid"); } session_set_cookie_params(0,$relativeurl.'/admin/'); @session_start(); $baselang = GetBaseLanguageFromSurveyID($surveyid); $clang = new limesurvey_lang($baselang); if (empty($_SESSION) || !isset($_SESSION['fieldname'])) { die("You don't have a valid session !"); } $file_index = (int)$_GET['file_index']; $fieldname = $_GET['fieldname']; $filename = "tmp/upload/".$_SESSION[$fieldname]['files'][$file_index]['filename']; $name = $_SESSION[$fieldname]['files'][$file_index]['name']; $fh = fopen($filename, 'w') or die("can't open file"); fclose($fh); if (unlink($filename))
* other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * * $Id: export_structure_quexml.php 9671 2010-12-21 20:02:24Z c_schmitz $ */ //Ensure script is not run directly, avoid path disclosure include_once "login_check.php"; if (!isset($surveyid)) { $surveyid = returnglobal('sid'); } if (isset($surveyprintlang) && !empty($surveyprintlang)) { $quexmllang = $surveyprintlang; } else { $quexmllang = GetBaseLanguageFromSurveyID($surveyid); } $qlang = new limesurvey_lang($quexmllang); if (!$surveyid) { echo $htmlheader . "<br />\n" . "<table width='350' align='center' style='border: 1px solid #555555' cellpadding='1' cellspacing='0'>\n" . "\t<tr bgcolor='#555555'><td colspan='2' height='4'><font size='1' face='verdana' color='white'><strong>" . _EXPORTSURVEY . "</strong></td></tr>\n" . "\t<tr><td align='center'>\n" . "{$setfont}<br /><strong><font color='red'>" . _ERROR . "</font></strong><br />\n" . _ES_NOSID . "<br />\n" . "<br /><input type='submit' {$btstyle} value='" . _GO_ADMIN . "' onClick=\"window.open('{$scriptname}', '_top')\">\n" . "\t</td></tr>\n" . "</table>\n" . "</body></html>\n"; exit; } function cleanup($string) { return trim(strip_tags(str_ireplace("<br />", "\n", $string))); } function create_free($f, $len, $lab = "") { global $dom; $free = $dom->create_element("free"); $format = $dom->create_element("format"); $format->set_content(cleanup($f)); $length = $dom->create_element("length");
/** * getqtypelist() Returns list of question types available in LimeSurvey. Edit this if you are adding a new * question type * * @global string $publicurl * @global string $sourcefrom * * @param string $SelectedCode Value of the Question Type (defaults to "T") * @param string $ReturnType Type of output from this function (defaults to selector) * * @return depending on $ReturnType param, returns a straight "array" of question types, or an <option></option> list * * Explanation of questiontype array: * * description : Question description * subquestions : 0= Does not support subquestions x=Number of subquestion scales * answerscales : 0= Does not need answers x=Number of answer scales (usually 1, but e.g. for dual scale question set to 2) * assessable : 0=Does not support assessment values when editing answerd 1=Support assessment values */ function getqtypelist($SelectedCode = "T", $ReturnType = "selector") { global $publicurl; global $sourcefrom, $clang; if (!isset($clang)) { $clang = new limesurvey_lang("en"); } $group['Arrays'] = $clang->gT('Arrays'); $group['MaskQuestions'] = $clang->gT("Mask questions"); $group['SinChoiceQues'] = $clang->gT("Single choice questions"); $group['MulChoiceQues'] = $clang->gT("Multiple choice questions"); $group['TextQuestions'] = $clang->gT("Text questions"); $qtypes = array("1" => array('description' => $clang->gT("Array dual scale"), 'group' => $group['Arrays'], 'subquestions' => 1, 'assessable' => 1, 'hasdefaultvalues' => 0, 'answerscales' => 2), "5" => array('description' => $clang->gT("5 Point Choice"), 'group' => $group['SinChoiceQues'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "A" => array('description' => $clang->gT("Array (5 Point Choice)"), 'group' => $group['Arrays'], 'subquestions' => 1, 'hasdefaultvalues' => 0, 'assessable' => 1, 'answerscales' => 0), "B" => array('description' => $clang->gT("Array (10 Point Choice)"), 'group' => $group['Arrays'], 'subquestions' => 1, 'hasdefaultvalues' => 0, 'assessable' => 1, 'answerscales' => 0), "C" => array('description' => $clang->gT("Array (Yes/No/Uncertain)"), 'group' => $group['Arrays'], 'subquestions' => 1, 'hasdefaultvalues' => 0, 'assessable' => 1, 'answerscales' => 0), "D" => array('description' => $clang->gT("Date"), 'group' => $group['MaskQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "E" => array('description' => $clang->gT("Array (Increase/Same/Decrease)"), 'group' => $group['Arrays'], 'subquestions' => 1, 'hasdefaultvalues' => 0, 'assessable' => 1, 'answerscales' => 0), "F" => array('description' => $clang->gT("Array"), 'group' => $group['Arrays'], 'subquestions' => 1, 'hasdefaultvalues' => 0, 'assessable' => 1, 'answerscales' => 1), "G" => array('description' => $clang->gT("Gender"), 'group' => $group['MaskQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "H" => array('description' => $clang->gT("Array by column"), 'group' => $group['Arrays'], 'hasdefaultvalues' => 0, 'subquestions' => 1, 'assessable' => 1, 'answerscales' => 1), "I" => array('description' => $clang->gT("Language Switch"), 'group' => $group['MaskQuestions'], 'hasdefaultvalues' => 0, 'subquestions' => 0, 'assessable' => 0, 'answerscales' => 0), "K" => array('description' => $clang->gT("Multiple Numerical Input"), 'group' => $group['MaskQuestions'], 'hasdefaultvalues' => 0, 'subquestions' => 1, 'assessable' => 1, 'answerscales' => 0), "L" => array('description' => $clang->gT("List (Radio)"), 'group' => $group['SinChoiceQues'], 'subquestions' => 0, 'hasdefaultvalues' => 1, 'assessable' => 1, 'answerscales' => 1), "M" => array('description' => $clang->gT("Multiple choice"), 'group' => $group['MulChoiceQues'], 'subquestions' => 1, 'hasdefaultvalues' => 1, 'assessable' => 1, 'answerscales' => 0), "N" => array('description' => $clang->gT("Numerical Input"), 'group' => $group['MaskQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "O" => array('description' => $clang->gT("List with comment"), 'group' => $group['SinChoiceQues'], 'subquestions' => 0, 'hasdefaultvalues' => 1, 'assessable' => 1, 'answerscales' => 1), "P" => array('description' => $clang->gT("Multiple choice with comments"), 'group' => $group['MulChoiceQues'], 'subquestions' => 1, 'hasdefaultvalues' => 1, 'assessable' => 1, 'answerscales' => 0), "Q" => array('description' => $clang->gT("Multiple Short Text"), 'group' => $group['TextQuestions'], 'subquestions' => 1, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "R" => array('description' => $clang->gT("Ranking"), 'group' => $group['MaskQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 1, 'answerscales' => 1), "S" => array('description' => $clang->gT("Short Free Text"), 'group' => $group['TextQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "T" => array('description' => $clang->gT("Long Free Text"), 'group' => $group['TextQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "U" => array('description' => $clang->gT("Huge Free Text"), 'group' => $group['TextQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "X" => array('description' => $clang->gT("Text display"), 'group' => $group['MaskQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "Y" => array('description' => $clang->gT("Yes/No"), 'group' => $group['MaskQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "!" => array('description' => $clang->gT("List (Dropdown)"), 'group' => $group['SinChoiceQues'], 'subquestions' => 0, 'hasdefaultvalues' => 1, 'assessable' => 1, 'answerscales' => 1), ":" => array('description' => $clang->gT("Array (Numbers)"), 'group' => $group['Arrays'], 'subquestions' => 2, 'hasdefaultvalues' => 0, 'assessable' => 1, 'answerscales' => 0), ";" => array('description' => $clang->gT("Array (Texts)"), 'group' => $group['Arrays'], 'subquestions' => 2, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0), "|" => array('description' => $clang->gT("File upload"), 'group' => $group['MaskQuestions'], 'subquestions' => 0, 'hasdefaultvalues' => 0, 'assessable' => 0, 'answerscales' => 0)); asort($qtypes); if ($ReturnType == "array") { return $qtypes; } if ($ReturnType == "group") { foreach ($qtypes as $qkey => $qtype) { $newqType[$qtype['group']][$qkey] = $qtype; } $qtypeselecter = ""; foreach ($newqType as $group => $members) { $qtypeselecter .= '<optgroup label="' . $group . '">'; foreach ($members as $TypeCode => $TypeProperties) { $qtypeselecter .= "<option value='{$TypeCode}'"; if ($SelectedCode == $TypeCode) { $qtypeselecter .= " selected='selected'"; } $qtypeselecter .= ">{$TypeProperties['description']}</option>\n"; } $qtypeselecter .= '</optgroup>'; } return $qtypeselecter; } $qtypeselecter = ""; foreach ($qtypes as $TypeCode => $TypeProperties) { $qtypeselecter .= "<option value='{$TypeCode}'"; if ($SelectedCode == $TypeCode) { $qtypeselecter .= " selected='selected'"; } $qtypeselecter .= ">{$TypeProperties['description']}</option>\n"; } return $qtypeselecter; }
} elseif ($subaction == "delete" && bHasSurveyPermission($surveyid, 'responses', 'delete')) { $dataentryoutput .= "<div class='header ui-widget-header'>" . $clang->gT("Data entry") . "</div>\n"; $dataentryoutput .= "<div class='messagebox ui-corner-all'>\n"; $thissurvey = getSurveyInfo($surveyid); $delquery = "DELETE FROM {$surveytable} WHERE id={$id}"; $delresult = $connect->Execute($delquery) or safe_die("Couldn't delete record {$id}<br />\n" . $connect->ErrorMsg()); $dataentryoutput .= "<div class='successheader'>" . $clang->gT("Record Deleted") . " (ID: {$id})</div><br /><br />\n" . "<input type='submit' value='" . $clang->gT("Browse Responses") . "' onclick=\"window.open('{$scriptname}?action=browse&sid={$surveyid}&subaction=all', '_top')\" /><br /><br />\n" . "</div>\n"; } else { $slangs = GetAdditionalLanguagesFromSurveyID($surveyid); $baselang = GetBaseLanguageFromSurveyID($surveyid); array_unshift($slangs, $baselang); if (!isset($_GET['language']) || !in_array($_GET['language'], $slangs)) { $sDataEntryLanguage = $baselang; $blang = $clang; } else { $blang = new limesurvey_lang($_GET['language']); $sDataEntryLanguage = $_GET['language']; } $langlistbox = languageDropdown($surveyid, $sDataEntryLanguage); $thissurvey = getSurveyInfo($surveyid); //This is the default, presenting a blank dataentry form $fieldmap = createFieldMap($surveyid); // PRESENT SURVEY DATAENTRY SCREEN $dataentryoutput .= $surveyoptions; $dataentryoutput .= "<div class='header ui-widget-header'>" . $clang->gT("Data entry") . "</div>\n"; $dataentryoutput .= "<form action='{$scriptname}?action=dataentry' enctype='multipart/form-data' name='addsurvey' method='post' id='addsurvey'>\n" . "<table class='data-entry-tbl' cellspacing='0'>\n" . "\t<tr>\n" . "\t<td colspan='3' align='center'>\n" . "\t<strong>" . $thissurvey['name'] . "</strong>\n" . "\t<br />" . FlattenText($thissurvey['description']) . "\n" . "\t</td>\n" . "\t</tr>\n"; $dataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n"; if (count(GetAdditionalLanguagesFromSurveyID($surveyid)) > 0) { $dataentryoutput .= "\t<tr>\n" . "\t<td colspan='3' align='center'>\n" . "\t" . $langlistbox . "\n" . "\t</td>\n" . "\t</tr>\n"; $dataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n"; }
* other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * * $Id: index.php 4729 2008-05-31 21:32:02Z nijaba $ */ if (isset($argv[1]) && ($argv[1] == 'install' || $argv[1] == 'upgrade') && isset($argv[2]) && isset($argv[3])) { require_once $argv[2]; require_once $argv[3]; } else { require_once dirname(__FILE__) . '/../../config-defaults.php'; $cmd_install = true; require_once dirname(__FILE__) . '/../../common.php'; } // SET THE LANGUAGE???? -> DEFAULT SET TO EN FOR NOW require_once $rootdir . '/classes/core/language.php'; $clang = new limesurvey_lang("en"); ob_implicit_flush(true); if (isset($argv[1]) && $argv[1] == 'install') { print "trying to create and populate {$databasename} on {$databaselocation}:{$databaseport} ({$databasetype}) \n"; if (!$database_exists) { if ($connect->Execute("CREATE DATABASE {$databasename};")) { print "\nDatabase {$databasename} on {$databasetype} CREATED \n"; } else { print "\nDatabase {$databasename} on {$databasetype} COULD NOT BE CREATED \n"; print "\n" . $connect->ErrorMsg(); return 1; } } else { if ($databasetype == 'mysql' || $databasetype == 'mysqli') { $connect->Execute("ALTER DATABASE `{$databasename}` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;"); }
} session_set_cookie_params(0, $relativeurl . '/'); @session_start(); if (empty($_SESSION) || !isset($_SESSION['fieldname'])) { die("You don't have a valid session !"); } $meta = '<script type="text/javascript"> var surveyid = "' . $surveyid . '"; var fieldname = "' . $_GET['fieldname'] . '"; var questgrppreview = ' . $_GET['preview'] . '; </script>'; $meta .= '<script type="text/javascript" src="scripts/ajaxupload.js"></script> <script type="text/javascript" src="scripts/uploader.js"></script> <link type="text/css" href="scripts/uploader.css" rel="stylesheet" />'; $baselang = GetBaseLanguageFromSurveyID($surveyid); $clang = new limesurvey_lang($baselang); $header = getHeader($meta); echo $header; echo "<script type='text/javascript'>\n var translt = {\n titleFld: '" . $clang->gT('Title', 'js') . "',\n commentFld: '" . $clang->gT('Comment', 'js') . "',\n errorNoMoreFiles: '" . $clang->gT('Sorry, no more files can be uploaded!', 'js') . "',\n errorOnlyAllowed: '" . $clang->gT('Sorry, only %s files can be uploaded for this question!', 'js') . "',\n uploading: '" . $clang->gT('Uploading', 'js') . "',\n selectfile: '" . $clang->gT('Select file', 'js') . "',\n errorNeedMore: '" . $clang->gT('Please upload %s more file(s).', 'js') . "',\n errorMoreAllowed: '" . $clang->gT('If you wish, you may upload %s more file(s); else you may return back to survey.', 'js') . "',\n errorMaxReached: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n errorTooMuch: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n errorNeedMoreConfirm: '" . $clang->gT("You need to upload %s more files for this question.\nAre you sure you want to exit?", 'js') . "'\n };\n </script>\n"; $fn = $_GET['fieldname']; $qid = $_GET['qid']; $qidattributes = getQuestionAttributes($qid); $body = ' <div id="notice"></div> <input type="hidden" id="ia" value="' . $fn . '" /> <input type="hidden" id="' . $fn . '_minfiles" value="' . $qidattributes['min_num_of_files'] . '" /> <input type="hidden" id="' . $fn . '_maxfiles" value="' . $qidattributes['max_num_of_files'] . '" /> <input type="hidden" id="' . $fn . '_maxfilesize" value="' . $qidattributes['max_filesize'] . '" /> <input type="hidden" id="' . $fn . '_allowed_filetypes" value="' . $qidattributes['allowed_filetypes'] . '" /> <input type="hidden" id="preview" value="' . $_SESSION['preview'] . '" /> <input type="hidden" id="' . $fn . '_show_comment" value="' . $qidattributes['show_comment'] . '" />
* is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. * */ require_once dirname(__FILE__) . '/../classes/core/startup.php'; require_once dirname(__FILE__) . '/../config-defaults.php'; require_once dirname(__FILE__) . '/../common.php'; require_once 'login_check.php'; if (!isset($_SESSION['loginID'])) { die; } if (!isset($_GET['lang'])) { $clang = new limesurvey_lang("en"); } else { $clang = new limesurvey_lang($_GET['lang']); } if (!isset($_GET['fieldname']) || !isset($_GET['fieldtext'])) { $output = ' <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <html> <head> <title>LimeSurvey ' . $clang->gT("HTML Editor") . '</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="robots" content="noindex, nofollow" /> </head>' . ' <body> <div class="maintitle"> LimeSurvey ' . $clang->gT("HTML Editor") . ' </div> <hr />
/** * quexml survey export */ public function showquexmlsurvey() { $iSurveyID = sanitize_int(Yii::app()->request->getParam('surveyid')); $lang = isset($_GET['lang']) ? Yii::app()->request->getParam('lang') : NULL; $tempdir = Yii::app()->getConfig("tempdir"); // Set the language of the survey, either from GET parameter of session var if ($lang != NULL) { $lang = preg_replace("/[^a-zA-Z0-9-]/", "", $lang); if ($lang) { $surveyprintlang = $lang; } } else { $surveyprintlang = Survey::model()->findByPk($iSurveyID)->language; } // Setting the selected language for printout $clang = new limesurvey_lang($surveyprintlang); Yii::import("application.libraries.admin.quexmlpdf", TRUE); $quexmlpdf = new quexmlpdf($this->getController()); set_time_limit(120); $noheader = TRUE; $quexml = quexml_export($iSurveyID, $surveyprintlang); $quexmlpdf->create($quexmlpdf->createqueXML($quexml)); //NEED TO GET QID from $quexmlpdf $qid = intval($quexmlpdf->getQuestionnaireId()); $zipdir = $this->_tempdir($tempdir); $f1 = "{$zipdir}/quexf_banding_{$qid}_{$surveyprintlang}.xml"; $f2 = "{$zipdir}/quexmlpdf_{$qid}_{$surveyprintlang}.pdf"; $f3 = "{$zipdir}/quexml_{$qid}_{$surveyprintlang}.xml"; $f4 = "{$zipdir}/readme.txt"; file_put_contents($f1, $quexmlpdf->getLayout()); file_put_contents($f2, $quexmlpdf->Output("quexml_{$qid}.pdf", 'S')); file_put_contents($f3, $quexml); file_put_contents($f4, $clang->gT('This archive contains a PDF file of the survey, the queXML file of the survey and a queXF banding XML file which can be used with queXF: http://quexf.sourceforge.net/ for processing scanned surveys.')); Yii::app()->loadLibrary('admin.pclzip.pclzip'); $zipfile = "{$tempdir}/quexmlpdf_{$qid}_{$surveyprintlang}.zip"; $z = new PclZip($zipfile); $z->create($zipdir, PCLZIP_OPT_REMOVE_PATH, $zipdir); unlink($f1); unlink($f2); unlink($f3); unlink($f4); rmdir($zipdir); $fn = "quexmlpdf_{$qid}_{$surveyprintlang}.zip"; $this->_addHeaders($fn, "application/zip", 0); header('Content-Transfer-Encoding: binary'); // load the file to send: readfile($zipfile); unlink($zipfile); }
//Checked if ($usresult) { $usrow = $usresult->FetchRow(); $stg_SessionName = $usrow['stg_value']; if ($surveyid) { @session_name($stg_SessionName . '-runtime-' . $surveyid); } else { @session_name($stg_SessionName . '-runtime-publicportal'); } } else { session_name("LimeSurveyRuntime-{$surveyid}"); } session_set_cookie_params(0, $relativeurl . '/admin/'); @session_start(); $baselang = GetBaseLanguageFromSurveyID($surveyid); $clang = new limesurvey_lang($baselang); if (empty($_SESSION) || !isset($_SESSION['fieldname'])) { die("You don't have a valid session !"); } $sFieldname = $_GET['fieldname']; $sFilename = sanitize_filename($_GET['filename']); $sOriginalFileName = sanitize_filename($_GET['name']); if (substr($sFilename, 0, 6) == 'futmp_') { $sFileDir = $tempdir . '/upload/'; } elseif (substr($sFilename, 0, 3) == 'fu_') { $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/"; } else { die('Invalid filename'); } $sJSON = $_SESSION[$sFieldname]; $aFiles = json_decode(stripslashes($sJSON), true);