alert("HI");';
*/
//split up results to extend statistics -> NOT WORKING YET! DO NOT ENABLE THIS!
//$showcombinedresults = 0;
//don't call this script directly!
if (isset($_REQUEST['homedir'])) {die('You cannot start this script directly');}
/**
* 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, $showaggregateddata;
if (is_null($statlangcode))
{
$statlang=GetBaseLanguageFromSurveyID($surveyid);
}
else
{
$statlang = new limesurvey_lang($statlangcode);
}
$fieldmap=createFieldMap($surveyid, "full", false, false, $statlang->langcode);
/*
* 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!
$query
".$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 = "
\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
$aquery
".$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 .= "";
}
} //end foreach -> loop through filter options to create SQL
//count number of answers
$query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid");
$qfs = questionnaireSampleFilterstate();
if ($qfs != false)
{
//Limit responses by questionnaire and/or sample
$query .= " JOIN `case` AS c ON ({$dbprefix}survey_$surveyid.token = c.token AND c.questionnaire_id = '{$qfs[0]}') ";
if ($qfs[1] != 0) //if a sample is selected
$query .= " JOIN `sample` AS s ON (s.sample_id = c.sample_id AND s.import_id = '{$qfs[1]}') ";
}
//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
$query
".$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);
}
//get me some data Scotty
$result=db_execute_num($query) or safe_die("Couldn't get results
$query
".$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:",'unescaped'));
$sheet->write($xlsRow,1,$results);
++$xlsRow;
$sheet->write($xlsRow,0,$statlang->gT("Total records in survey:",'unescaped'));
$sheet->write($xlsRow,1,$total);
if($total)
{
++$xlsRow;
$sheet->write($xlsRow,0,$statlang->gT("Percentage of total:",'unescaped'));
$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:",'unescaped'), $results);
$array[] = array($statlang->gT("Total records in survey:",'unescaped'), $total);
if($total)
$array[] = array($statlang->gT("Percentage of total:",'unescaped'), $percent."%");
$pdf->addPage('P','A4');
$pdf->Bookmark($pdf->delete_html($statlang->gT("Results",'unescaped')), 0, 0);
$pdf->titleintopdf($statlang->gT("Results",'unescaped'),$statlang->gT("Survey",'unescaped')." ".$surveyid);
$pdf->tableintopdf($array);
$pdf->addPage('P','A4');
break;
case 'html':
$statisticsoutput .= "
\n
| ".$statlang->gT("Results")." | |
|---|---|
| ".$statlang->gT("Number of records in this query:").' | ' ."$results |
| ".$statlang->gT("Total records in survey:").' | ' ."$total |
| ".$statlang->gT("Percentage of total:").' | ' ."$percent% |
| ".sprintf($statlang->gT("Field summary for %s"),$qtitle).":" ." | |||
|---|---|---|---|
| $qquestion | |||
| " .$statlang->gT("Calculation")." | \n" ."\t\t" .$statlang->gT("Result")." | \n" ."\t||
| ".$res[0]." | ".$res[1]." | ||
| ".sprintf($statlang->gT("Field summary for %s"),$qtitle).":" ." | |||
|---|---|---|---|
| $qquestion | |||
| " .$statlang->gT("Calculation")." | \n" ."\t\t" .$statlang->gT("Result")." | \n" ."\t||
| $shw[0] | \n" ."\t\t$shw[1] | \n" ."\t||
| \n"
."\t\t\t".$statlang->gT("Null values are ignored in calculations")." \n" ."\t\t\t".sprintf($statlang->gT("Q1 and Q3 calculated using %s"), "".$statlang->gT("minitab method")."") ."\n" ."\t\t | \n"
."\t|||
| " //headline .sprintf($statlang->gT("Field summary for %s"),$qtitle)."" ." | |||
|---|---|---|---|
| " //question title .$qquestion." | |||
| ";
break;
default:
break;
}
echo '';
$qfs = questionnaireSampleFilterstate();
$querylimit = "";
if ($qfs != false)
{
//Limit responses by questionnaire and/or sample
$querylimit .= " JOIN `case` AS c ON ({$dbprefix}survey_$surveyid.token = c.token AND c.questionnaire_id = '{$qfs[0]}') ";
if ($qfs[1] != 0) //if a sample is selected
$querylimit .= " JOIN `sample` AS s ON (s.sample_id = c.sample_id AND s.import_id = '{$qfs[1]}') ";
}
//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")." $querylimit 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")." $querylimit 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")." $querylimit 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")." $querylimit 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")." $querylimit 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")." $querylimit 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")." $querylimit WHERE cast(".db_quote_id($rt)." as varchar)= '$al[0]'";
}
else
$query = "SELECT count(*) FROM ".db_table_name("survey_$surveyid")." $querylimit 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")." $querylimit 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")." $querylimit 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 $query ".$connect->ErrorMsg()); // $statisticsoutput .= "\n\n\n"; // this just extracts the data, after we present while ($row=$result->FetchRow()) { //store temporarily value of answer count of question type '5' and 'A'. $tempcount = -1; //count can't be less han zero //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 (!isset($_POST['showtextinline']) && $browse===true) $fname .= " "; if(isset($_POST['showtextinline']) && ($qtype != "S" && $qtype != "U" && $qtype != "T" && $qtype != "Q")) { //Generate list of 'other' text entries for display $headPDF2=array(); $headPDF2[]=array($statlang->gt("'Other' Responses")); $tablePDF2=array(); $query2 = "SELECT ".db_quote_id($al[2])." FROM ".db_table_name("survey_$surveyid")." WHERE "; $query2 .= ($connect->databaseType == "mysql")? db_quote_id($al[2])." != ''" : "NOT (".db_quote_id($al[2])." LIKE '')"; $result2=db_execute_num($query2) or safe_die ("Couldn't do count of values $query ".$connect->ErrorMsg()); $fnamelast = " \n";
$fnamelast .= "".$clang->gT("'Other' Responses")." \n";
}
}
/*
* 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 (!isset($_POST['showtextinline']) && $browse===true) $fname .= " ";
}
elseif ($al[0] == "NoAnswer")
{
$fname= "$al[1]";
}
$statisticsoutput .= "\n"; //$fname .= $query2; while ($row2=$result2->FetchRow()) { $fnamelast .= $row2[0]." \n"; $tablePDF2[]=array($row2[0]); } $fnamelast .= " | \n"
."\t\t" ."".$statlang->gT("Count")." | \n" ."\t\t" ."".$statlang->gT("Percentage")." | \n" ."\t" ."".$statlang->gT("Count")." | \n" ."\t\t" ."".$statlang->gT("Percentage")." | \n" ."\t\t" ."".$statlang->gT("Sum")." | \n" ."\t\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 .= "".$statlang->gT("Answer")."\n" ."\t\t" ."".$statlang->gT("Count")." | \n" ."\t\t" ."".$statlang->gT("Percentage")." | \n" ."\t\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 { //store the original value! $tempcount = $row[0]; //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 { //store the original value! $tempcount = $row[0]; //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 { //store the original value! $tempcount = $row[0]; //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 .= "".$statlang->gT("Answer")."\n" ."\t\t" ."".$statlang->gT("Count")." | \n" ."\t\t" ."".$statlang->gT("Percentage")." | \n" ."\t\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 //first check if $tempcount is > 0. If yes, $row[0] has been modified and $tempcount has the original count. if ($tempcount > 0) { $lbl[] = iconv_wordwrap(FlattenText("$al[1] ($tempcount)"), 25, "\n"); // NMO 2009-03-24 $lblrtl[] = utf8_strrev(iconv_wordwrap(FlattenText("$al[1] )$tempcount("), 25, "\n")); // NMO 2009-03-24 } else { $lbl[] = iconv_wordwrap(FlattenText("$al[1] ($row[0])"), 30, "\n"); // NMO 2009-03-24 $lblrtl[] = utf8_strrev(iconv_wordwrap(FlattenText("$al[1] )$row[0]("), 30, "\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
| " . $label[$i] ."\n" ."\t\t | \n" //output absolute number of records ."\t\t" . $grawdata[$i] . "\n | "; //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"; //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 | "; } elseif ($qtype == "S" || $qtype == "U" || $qtype == "T" || $qtype == "Q") { $statisticsoutput .= "\n\t"; //output percentage $statisticsoutput .= sprintf("%01.2f", $percentage) . "%"; //adjust output $statisticsoutput .= "\t\t | "; 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"; $statisticsoutput .= sprintf("%01.2f", $percentage) . "% | "; //output again (no real aggregation here) $statisticsoutput .= "\t\t"; $statisticsoutput .= sprintf("%01.2f", $percentage)."%"; $statisticsoutput .= " | \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"; $statisticsoutput .= sprintf("%01.2f", $percentage) . "% | "; //output aggregated data $statisticsoutput .= "\t\t"; $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata)."%"; $statisticsoutput .= " | \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"; $statisticsoutput .= sprintf("%01.2f", $percentage) . "% | "; //output aggregated data $statisticsoutput .= "\t\t"; $statisticsoutput .= sprintf("%01.2f", $aggregatedgdata)."%"; $statisticsoutput .= " | \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\n"; $statisticsoutput .= "
| ".$statlang->gT("Sum")." (".$statlang->gT("Answers").") | "; $statisticsoutput .= "".$sumitems." | "; $statisticsoutput .= "$sumpercentage% | "; $statisticsoutput .= "$sumpercentage% | "; $statisticsoutput .= "\t\t \n\t
| ".$statlang->gT("Number of cases")." | "; //German: "Fallzahl" $statisticsoutput .= "".$TotalCompleted." | "; $statisticsoutput .= "$casepercentage% | "; //there has to be a whitespace within the table cell to display correctly $statisticsoutput .= ""; $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 | \n\t\n"; break; default: break; } } } //end else -> $gdata[$i] != "N/A" //increase counter $i++; $itemcounter++; } //end while if(isset($fnamelast)) { $statisticsoutput.= "
| ".$fnamelast." | |||
| ".$statlang->gT("Arithmetic mean")." | "; //German: "Fallzahl" $statisticsoutput .= "$am | ||
| ".$statlang->gT("Standard deviation")." | "; //German: "Fallzahl" $statisticsoutput .= "$stddev | ||