Exemplo n.º 1
0
 */
require_once '../../config.inc.php';
require_once 'charts.inc.php';
testlinkInitPage($db, false, false, "checkRights");
$cfg = new stdClass();
$cfg->scale = new stdClass();
$chart_cfg = config_get('results');
$chart_cfg = $chart_cfg['charts']['dimensions']['topLevelSuitesBarChart'];
$cfg->chartTitle = lang_get($chart_cfg['chartTitle']);
$cfg->XSize = $chart_cfg['XSize'];
$cfg->YSize = $chart_cfg['YSize'];
$cfg->beginX = $chart_cfg['beginX'];
$cfg->beginY = $chart_cfg['beginY'];
$cfg->scale->legendXAngle = $chart_cfg['legendXAngle'];
$info = getDataAndScale($db);
createChart($info, $cfg);
/*
  function: getDataAndScale
  args :
  
  returns: 
*/
function getDataAndScale(&$dbHandler)
{
    $obj = new stdClass();
    $totals = null;
    $resultsCfg = config_get('results');
    $dataSet = $_SESSION['statistics']['getTopLevelSuites'];
    $mapOfAggregate = $_SESSION['statistics']['getAggregateMap'];
    $obj->canDraw = !is_null($dataSet);
    if ($obj->canDraw) {
Exemplo n.º 2
0
 function graph()
 {
     Yii::app()->loadHelper('admin/statistics');
     Yii::app()->loadHelper("surveytranslator");
     // Initialise PCHART
     require_once Yii::app()->basePath . '/third_party/pchart/pchart/pChart.class';
     require_once Yii::app()->basePath . '/third_party/pchart/pchart/pData.class';
     require_once Yii::app()->basePath . '/third_party/pchart/pchart/pCache.class';
     Yii::import('application.third_party.ar-php.Arabic', true);
     $tempdir = Yii::app()->getConfig("tempdir");
     $MyCache = new pCache($tempdir . '/');
     $aData['success'] = 1;
     $sStatisticsLanguage = sanitize_languagecode($_POST['sStatisticsLanguage']);
     $oStatisticsLanguage = new Limesurvey_lang($sStatisticsLanguage);
     if (isset($_POST['cmd']) && isset($_POST['id'])) {
         list($qsid, $qgid, $qqid) = explode("X", substr($_POST['id'], 0), 3);
         if (!is_numeric(substr($qsid, 0, 1))) {
             // Strip first char when not numeric (probably T or D)
             $qsid = substr($qsid, 1);
         }
         $aFieldmap = createFieldMap($qsid, 'full', false, false, $sStatisticsLanguage);
         $qtype = $aFieldmap[$_POST['id']]['type'];
         $qqid = $aFieldmap[$_POST['id']]['qid'];
         $aattr = getQuestionAttributeValues($qqid);
         $field = substr($_POST['id'], 1);
         switch ($_POST['cmd']) {
             case 'showmap':
                 if (isset($aattr['location_mapservice'])) {
                     $aData['mapdata'] = array("coord" => getQuestionMapData($field, $qsid), "zoom" => $aattr['location_mapzoom'], "width" => $aattr['location_mapwidth'], "height" => $aattr['location_mapheight']);
                     QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showmap', 1);
                 } else {
                     $aData['success'] = 0;
                 }
                 break;
             case 'hidemap':
                 if (isset($aattr['location_mapservice'])) {
                     $aData['success'] = 1;
                     QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showmap', 0);
                 } else {
                     $aData['success'] = 0;
                 }
                 break;
             case 'showgraph':
                 if (isset($aattr['location_mapservice'])) {
                     $aData['mapdata'] = array("coord" => getQuestionMapData($field, $qsid), "zoom" => $aattr['location_mapzoom'], "width" => $aattr['location_mapwidth'], "height" => $aattr['location_mapheight']);
                 }
                 $bChartType = $qtype != "M" && $qtype != "P" && $aattr["statistics_graphtype"] == "1";
                 $adata = Yii::app()->session['stats'][$_POST['id']];
                 $aData['chartdata'] = createChart($qqid, $qsid, $bChartType, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $oStatisticsLanguage, $qtype);
                 QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showgraph', 1);
                 break;
             case 'hidegraph':
                 QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_showgraph', 0);
                 break;
             case 'showbar':
                 if ($qtype == "M" || $qtype == "P") {
                     $aData['success'] = 0;
                     break;
                 }
                 QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_graphtype', 0);
                 $adata = Yii::app()->session['stats'][$_POST['id']];
                 $aData['chartdata'] = createChart($qqid, $qsid, 0, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $oStatisticsLanguage, $qtype);
                 break;
             case 'showpie':
                 if ($qtype == "M" || $qtype == "P") {
                     $aData['success'] = 0;
                     break;
                 }
                 QuestionAttribute::model()->setQuestionAttribute($qqid, 'statistics_graphtype', 1);
                 $adata = Yii::app()->session['stats'][$_POST['id']];
                 $aData['chartdata'] = createChart($qqid, $qsid, 1, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache, $oStatisticsLanguage, $qtype);
                 break;
             default:
                 $aData['success'] = 0;
                 break;
         }
     } else {
         $aData['success'] = 0;
     }
     //$this->_renderWrappedTemplate('export', 'statistics_graph_view', $aData);
     $this->getController()->renderPartial('export/statistics_graph_view', $aData);
 }
Exemplo n.º 3
0
 /**
  * displayResults builds html output to display the actual results from a survey
  *
  * @param mixed $outputs
  * @param INT $results The number of results being displayed overall
  * @param mixed $rt
  * @param mixed $outputType
  * @param mixed $surveyid
  * @param mixed $sql
  * @param mixed $usegraph
  */
 protected function displayResults($outputs, $results, $rt, $outputType, $surveyid, $sql, $usegraph, $browse, $sLanguage)
 {
     /* Set up required variables */
     $TotalCompleted = 0;
     //Count of actually completed answers
     $statisticsoutput = "";
     $sDatabaseType = Yii::app()->db->getDriverName();
     $tempdir = Yii::app()->getConfig("tempdir");
     $tempurl = Yii::app()->getConfig("tempurl");
     $firstletter = substr($rt, 0, 1);
     $astatdata = array();
     if ($usegraph == 1) {
         //for creating graphs we need some more scripts which are included here
         require_once APPPATH . '/third_party/pchart/pchart/pChart.class';
         require_once APPPATH . '/third_party/pchart/pchart/pData.class';
         require_once APPPATH . '/third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache($tempdir . '/');
     }
     switch ($outputType) {
         case 'xls':
             $xlsTitle = sprintf(gT("Field summary for %s"), html_entity_decode($outputs['qtitle'], ENT_QUOTES, 'UTF-8'));
             $xlsDesc = html_entity_decode($outputs['qquestion'], ENT_QUOTES, 'UTF-8');
             $this->xlsRow++;
             $this->xlsRow++;
             $this->xlsRow++;
             $this->sheet->write($this->xlsRow, 0, $xlsTitle);
             $this->xlsRow++;
             $this->sheet->write($this->xlsRow, 0, $xlsDesc);
             $footXLS = array();
             break;
         case 'pdf':
             $sPDFQuestion = flattenText($outputs['qquestion'], false, true);
             $pdfTitle = $this->pdf->delete_html(sprintf(gT("Field summary for %s"), html_entity_decode($outputs['qtitle'], ENT_QUOTES, 'UTF-8')));
             $titleDesc = $sPDFQuestion;
             $this->pdf->AddPage('P', 'A4');
             $this->pdf->Bookmark($sPDFQuestion, 1, 0);
             $this->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>" . sprintf(gT("Field summary for %s"), $outputs['qtitle']) . "</strong>" . "</th></tr>\n" . "\t<tr><th colspan='4' align='center'><strong>" . $outputs['qquestion'] . "</strong></th></tr>\n" . "\t<tr>\n\t\t<th width='50%' align='center' >";
             break;
         default:
             break;
     }
     //loop though the array which contains all answer data
     $ColumnName_RM = array();
     foreach ($outputs['alist'] as $al) {
         //picks out answer list ($outputs['alist']/$al)) that come from the multiple list above
         if (isset($al[2]) && $al[2]) {
             //handling for "other" option
             if ($al[0] == gT("Other")) {
                 if ($outputs['qtype'] == '!' || $outputs['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
                     /* This query selects a count of responses where "other" has been selected */
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName(substr($al[2], 0, strlen($al[2]) - 5)) . "='-oth-'";
                 } else {
                     //get data - select a count of responses where no answer is provided
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ";
                     $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " != ''" : "NOT (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE '')";
                 }
             } elseif ($outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "S" || $outputs['qtype'] == "Q" || $outputs['qtype'] == ";") {
                 $sDatabaseType = Yii::app()->db->getDriverName();
                 //free text answers
                 if ($al[0] == "Answer") {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ";
                     $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " != ''" : "NOT (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE '')";
                 } elseif ($al[0] == "NoAnswer") {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( ";
                     $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " = '')" : " (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE ''))";
                 }
             } elseif ($outputs['qtype'] == "O") {
                 $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( ";
                 $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " <> '')" : " (" . Yii::app()->db->quoteColumnName($al[2]) . " NOT LIKE ''))";
                 // all other question types
             } else {
                 $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($al[2]) . " =";
                 //ranking question?
                 if (substr($rt, 0, 1) == "R") {
                     $query .= " '{$al['0']}'";
                 } else {
                     $query .= " 'Y'";
                 }
             }
         } else {
             if ($al[0] != "") {
                 //get more data
                 $sDatabaseType = Yii::app()->db->getDriverName();
                 if ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
                     // mssql cannot compare text blobs so we have to cast here
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar)= '{$al['0']}'";
                 } else {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($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 ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
                     // mssql cannot compare text blobs so we have to cast here
                     //$query = "SELECT count(*) FROM {{survey_$surveyid}} WHERE (".sanitize_int($rt)." IS NULL "
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( " . "cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar) = '' " . "OR cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar) = ' ' )";
                 } else {
                     //                $query = "SELECT count(*) FROM {{survey_$surveyid}} WHERE (".sanitize_int($rt)." IS NULL "
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( " . " " . Yii::app()->db->quoteColumnName($rt) . " = '' " . "OR " . Yii::app()->db->quoteColumnName($rt) . " = ' ') ";
                 }
             }
         }
         //check filter option
         if (incompleteAnsFilterState() == "incomplete") {
             $query .= " AND submitdate is null";
         } elseif (incompleteAnsFilterState() == "complete") {
             $query .= " AND submitdate is not null";
         }
         //check for any "sql" that has been passed from another script
         if (!empty($sql)) {
             $query .= " AND {$sql}";
         }
         //get data
         $row = Yii::app()->db->createCommand($query)->queryScalar();
         // $statisticsoutput .= "\n<!-- ($sql): $query -->\n\n";
         //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;
         //"no answer" handling
         if ($al[0] === "") {
             $fname = gT("No answer");
         } elseif ($al[0] === gT("Other") || $al[0] === "Answer" || $outputs['qtype'] === "O" && $al[0] === gT("Comments") || $outputs['qtype'] === "P") {
             if ($outputs['qtype'] == "P") {
                 $sColumnName = $al[2] . "comment";
             } else {
                 $sColumnName = $al[2];
             }
             $ColumnName_RM[] = $sColumnName;
             if ($outputs['qtype'] == 'O') {
                 $TotalCompleted -= $row;
             }
             $fname = "{$al['1']}";
             if ($browse === true) {
                 $fname .= " <input type='button' class='statisticsbrowsebutton' value='" . gT("Browse") . "' id='{$sColumnName}' />";
             }
             if ($browse === true && isset($_POST['showtextinline']) && $outputType == 'pdf') {
                 $headPDF2 = array();
                 $headPDF2[] = array(gT("ID"), gT("Response"));
                 $tablePDF2 = array();
                 $result2 = $this->_listcolumn($surveyid, $sColumnName);
                 foreach ($result2 as $row2) {
                     $tablePDF2[] = array($row2['id'], $row2['value']);
                 }
             }
             if ($browse === true && isset($_POST['showtextinline']) && $outputType == 'xls') {
                 $headXLS = array();
                 $tableXLS = array();
                 $headXLS[] = array(gT("ID"), gT("Response"));
                 $result2 = $this->_listcolumn($surveyid, $sColumnName);
                 foreach ($result2 as $row2) {
                     $tableXLS[] = array($row2['id'], $row2['value']);
                 }
             }
         } elseif ($outputs['qtype'] == "S" || $outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "Q") {
             $headPDF = array();
             $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"));
             //show free text answers
             if ($al[0] == "Answer") {
                 $fname = "{$al['1']}";
                 if ($browse === true) {
                     $fname .= " <input type='button'  class='statisticsbrowsebutton' value='" . gT("Browse") . "' id='{$sColumnName}' />";
                 }
             } elseif ($al[0] == "NoAnswer") {
                 $fname = "{$al['1']}";
             }
             $statisticsoutput .= "</th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . gT("Count") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . gT("Percentage") . "</strong></th>\n" . "\t</tr></thead>\n";
             if ($browse === true && isset($_POST['showtextinline']) && $outputType == 'pdf') {
                 $headPDF2 = array();
                 $headPDF2[] = array(gT("ID"), gT("Response"));
                 $tablePDF2 = array();
                 $result2 = $this->_listcolumn($surveyid, $sColumnName);
                 foreach ($result2 as $row2) {
                     $tablePDF2[] = array($row2['id'], $row2['value']);
                 }
             }
         } elseif (Yii::app()->getConfig('showaggregateddata') == 1) {
             if (!isset($showheadline) || $showheadline != false) {
                 if ($outputs['qtype'] == "5" || $outputs['qtype'] == "A") {
                     switch ($outputType) {
                         case 'xls':
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Answer"));
                             $this->sheet->write($this->xlsRow, 1, gT("Count"));
                             $this->sheet->write($this->xlsRow, 2, gT("Percentage"));
                             $this->sheet->write($this->xlsRow, 3, gT("Sum"));
                             break;
                         case 'pdf':
                             $headPDF = array();
                             $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"), gT("Sum"));
                             break;
                         case 'html':
                             //four columns
                             $statisticsoutput .= "<strong>" . gT("Answer") . "</strong></th>\n" . "\t\t<th width='15%' align='center' >" . "<strong>" . gT("Count") . "</strong></th>\n" . "\t\t<th width='20%' align='center' >" . "<strong>" . gT("Percentage") . "</strong></th>\n" . "\t\t<th width='15%' align='center' >" . "<strong>" . gT("Sum") . "</strong></th>\n" . "\t</tr></thead>\n";
                             break;
                         default:
                             break;
                     }
                     $showheadline = false;
                 } else {
                     switch ($outputType) {
                         case 'xls':
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Answer"));
                             $this->sheet->write($this->xlsRow, 1, gT("Count"));
                             $this->sheet->write($this->xlsRow, 2, gT("Percentage"));
                             break;
                         case 'pdf':
                             $headPDF = array();
                             $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"));
                             break;
                         case 'html':
                             //three columns
                             $statisticsoutput .= "<strong>" . gT("Answer") . "</strong></td>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . gT("Count") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . 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']})";
         } else {
             if (!isset($showheadline) || $showheadline != false) {
                 switch ($outputType) {
                     case 'xls':
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, gT("Answer"));
                         $this->sheet->write($this->xlsRow, 1, gT("Count"));
                         $this->sheet->write($this->xlsRow, 2, gT("Percentage"));
                         break;
                     case 'pdf':
                         $headPDF = array();
                         $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"));
                         break;
                     case 'html':
                         //three columns
                         $statisticsoutput .= "<strong>" . gT("Answer") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . gT("Count") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . 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 / $results * 100;
         } else {
             //no data!
             $gdata[] = "N/A";
         }
         //put absolute data into array
         $grawdata[] = $row;
         //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 has been modified and $tempcount has the original count.
         if ($tempcount > -1) {
             $lbl[wordwrap(FlattenText("{$al['1']}"), 25, "\n")] = $tempcount;
         } else {
             $lbl[wordwrap(FlattenText("{$al['1']}"), 25, "\n")] = $row;
         }
     }
     //end foreach -> loop through answer data
     //no filtering of incomplete answers and NO multiple option questions
     //if ((incompleteAnsFilterState() != "complete") and ($outputs['qtype'] != "M") and ($outputs['qtype'] != "P"))
     //error_log("TIBO ".print_r($showaggregated_indice_table,true));
     if ($outputs['qtype'] != "M" and $outputs['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(Yii::app()->getConfig('showaggregateddata')) && Yii::app()->getConfig('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)
         } else {
             //calculate total number of incompleted records
             $TotalIncomplete = $results - $TotalCompleted;
             //output
             if (incompleteAnsFilterState() != "complete") {
                 $fname = gT("Not completed or Not displayed");
             } else {
                 $fname = gT("Not displayed");
             }
             //we need some data
             if ($results > 0) {
                 //calculate percentage
                 $gdata[] = $TotalIncomplete / $results * 100;
             } 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 another array
             if (incompleteAnsFilterState() != "complete") {
                 $lbl[wordwrap(flattenText(gT("Not completed or Not displayed")), 20, "\n")] = $TotalIncomplete;
             } else {
                 $lbl[wordwrap(flattenText(gT("Not displayed")), 20, "\n")] = $TotalIncomplete;
             }
         }
         //end else -> noncompleted NOT checked
     }
     // For multi question type, we have to check non completed with ALL sub question set to NULL
     if ($outputs['qtype'] == "M" or $outputs['qtype'] == "P") {
         $criteria = new CDbCriteria();
         foreach ($outputs['alist'] as $al) {
             $criteria->addCondition(Yii::app()->db->quoteColumnName($al[2]) . " IS NULL");
         }
         if (incompleteAnsFilterState() == "incomplete") {
             $criteria->addCondition("submitdate IS NULL");
         } elseif (incompleteAnsFilterState() == "complete") {
             $criteria->addCondition("submitdate IS NOT NULL");
         }
         $multiNotDisplayed = SurveyDynamic::model($surveyid)->count($criteria);
         if (isset($_POST['noncompleted']) and $_POST['noncompleted'] == "on") {
             //counter
             $i = 0;
             while (isset($gdata[$i])) {
                 //we want to have some "real" data here
                 if ($gdata[$i] != "N/A") {
                     //calculate percentage
                     if ($results > $multiNotDisplayed) {
                         $gdata[$i] = $grawdata[$i] / ($results - $multiNotDisplayed) * 100;
                     } else {
                         $gdata[$i] = "N/A";
                     }
                 }
                 $i++;
             }
         } else {
             // Add a line with not displayed %
             if ($multiNotDisplayed > 0) {
                 if (incompleteAnsFilterState() != "complete") {
                     $fname = gT("Not completed or Not displayed");
                 } else {
                     $fname = gT("Not displayed");
                 }
                 $label[] = $fname;
                 //we need some data
                 if ($results > 0) {
                     //calculate percentage
                     $gdata[] = $multiNotDisplayed / $results * 100;
                 } else {
                     $gdata[] = "N/A";
                 }
                 //put data of incompleted records into array
                 $grawdata[] = $multiNotDisplayed;
             }
         }
     }
     //counter
     $i = 0;
     //we need to know which item we are editing
     $itemcounter = 1;
     //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";
         /*
          * If there is a "browse" button in this label, let's make sure there's an extra row afterwards
          * to store the columnlist
          *
          * */
         if (strpos($label[$i], "class='statisticsbrowsebutton'")) {
             $extraline = "<tr><td class='statisticsbrowsecolumn' colspan='3' style='display: none'>";
             if ($outputs['qtype'] == 'P') {
                 $extraline .= "<div class='statisticsbrowsecolumn' id='columnlist_{$ColumnName_RM[$i]}'></div></td></tr>\n";
             } else {
                 $extraline .= "<div class='statisticsbrowsecolumn' id='columnlist_{$sColumnName}'></div></td></tr>\n";
             }
         }
         //output absolute number of records
         $statisticsoutput .= "\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]);
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, $label[$i]);
                     $this->sheet->writeNumber($this->xlsRow, 1, $grawdata[$i]);
                     $this->sheet->writeNumber($this->xlsRow, 2, $gdata[$i] / 100, $this->xlsPercents);
                     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 Yii::app()->getConfig('showaggregateddata') setting
                     if (Yii::app()->getConfig('showaggregateddata') == 1 && ($outputs['qtype'] == "5" || $outputs['qtype'] == "A")) {
                         $statisticsoutput .= "\t\t</td>";
                     } elseif ($outputs['qtype'] == "S" || $outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "Q") {
                         $statisticsoutput .= "</td>\n\t";
                     }
                     $statisticsoutput .= "</tr>\n";
                     //Close the row
                     if (isset($extraline)) {
                         $statisticsoutput .= $extraline;
                     }
                     break;
                 default:
                     break;
             }
         } else {
             //check if data should be aggregated
             if (Yii::app()->getConfig('showaggregateddata') == 1 && ($outputs['qtype'] == "5" || $outputs['qtype'] == "A")) {
                 //mark that we have done soemthing special here
                 $aggregated = true;
                 if ($results - $grawdata[5] > 0) {
                     $percentage = $grawdata[$i] / ($results - $grawdata[5]) * 100;
                     // Only answered
                 } else {
                     $percentage = 0;
                 }
                 switch ($itemcounter) {
                     case 1:
                         if ($results - $grawdata[5] > 0) {
                             $aggregatedPercentage = ($grawdata[0] + $grawdata[1]) / ($results - $grawdata[5]) * 100;
                         } else {
                             $aggregatedPercentage = 0;
                         }
                         break;
                     case 3:
                         $aggregatedPercentage = $percentage;
                         break;
                     case 5:
                         if ($results - $grawdata[5] > 0) {
                             $aggregatedPercentage = ($grawdata[3] + $grawdata[4]) / ($results - $grawdata[5]) * 100;
                         } else {
                             $aggregatedPercentage = 0;
                         }
                         break;
                     case 6:
                     case 7:
                         if ($results - $grawdata[5] > 0) {
                             $percentage = $grawdata[$i] / $results * 100;
                             // All results
                         } else {
                             $percentage = 0;
                         }
                     default:
                         $aggregatedPercentage = 'na';
                         break;
                 }
                 switch ($outputType) {
                     case 'xls':
                         $label[$i] = flattenText($label[$i]);
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, $label[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 1, $grawdata[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 2, $percentage / 100, $this->xlsPercents);
                         if ($aggregatedPercentage !== 'na') {
                             $this->sheet->writeNumber($this->xlsRow, 3, $aggregatedPercentage / 100, $this->xlsPercents);
                         }
                         break;
                     case 'pdf':
                         $label[$i] = flattenText($label[$i]);
                         if ($aggregatedPercentage !== 'na') {
                             $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", sprintf("%01.2f", $aggregatedPercentage) . "%");
                         } else {
                             $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", "");
                         }
                         break;
                     case 'html':
                         //output percentage
                         $statisticsoutput .= "\t\t<td align='center' >";
                         $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>";
                         $statisticsoutput .= "\t\t<td align='center' >";
                         if ($aggregatedPercentage !== 'na') {
                             $statisticsoutput .= sprintf("%01.2f", $aggregatedPercentage) . "%";
                         } else {
                             $statisticsoutput .= '&nbsp;';
                         }
                         $statisticsoutput .= "</td>\t\t";
                         break;
                     default:
                         break;
                 }
                 if ($itemcounter == 5) {
                     // create new row "sum"
                     //calculate sum of items 1-5
                     $sumitems = $grawdata[0] + $grawdata[1] + $grawdata[2] + $grawdata[3] + $grawdata[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(gT("Sum") . " (" . gT("Answers") . ")", $sumitems, $sumpercentage . "%", $sumpercentage . "%");
                             $footXLS[] = array(gT("Number of cases"), $TotalCompleted, $casepercentage . "%", "");
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Sum") . " (" . gT("Answers") . ")");
                             $this->sheet->writeNumber($this->xlsRow, 1, $sumitems);
                             $this->sheet->writeNumber($this->xlsRow, 2, $sumpercentage / 100, $this->xlsPercents);
                             $this->sheet->writeNumber($this->xlsRow, 3, $sumpercentage / 100, $this->xlsPercents);
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Number of cases"));
                             $this->sheet->writeNumber($this->xlsRow, 1, $TotalCompleted);
                             $this->sheet->writeNumber($this->xlsRow, 2, $casepercentage / 100, $this->xlsPercents);
                             break;
                         case 'pdf':
                             $footPDF[] = array(gT("Sum") . " (" . gT("Answers") . ")", $sumitems, $sumpercentage . "%", $sumpercentage . "%");
                             $footPDF[] = array(gT("Number of cases"), $TotalCompleted, $casepercentage . "%", "");
                             break;
                         case 'html':
                             $statisticsoutput .= "\t\t&nbsp;\n\t</tr>\n";
                             $statisticsoutput .= "<tr><td align='center'><strong>" . gT("Sum") . " (" . 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&nbsp;\n\t</tr>\n";
                             $statisticsoutput .= "<tr><td align='center'>" . 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' >&nbsp;</td></tr>";
                             break;
                         default:
                             break;
                     }
                 }
             } else {
                 switch ($outputType) {
                     case 'xls':
                         $label[$i] = flattenText($label[$i]);
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, $label[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 1, $grawdata[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 2, $gdata[$i] / 100, $this->xlsPercents);
                         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&nbsp;</td>\n\t</tr>\n";
                         if (isset($extraline)) {
                             $statisticsoutput .= $extraline;
                         }
                         break;
                     default:
                         break;
                 }
             }
         }
         //end else -> $gdata[$i] != "N/A"
         //increase counter
         $i++;
         $itemcounter++;
         //Clear extraline
         unset($extraline);
     }
     //end while
     //only show additional values when this setting is enabled
     if (Yii::app()->getConfig('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 ($outputs['qtype'] == "5" || $outputs['qtype'] == "A") {
             $stddev = 0;
             $stddevarray = array_slice($grawdata, 0, 5, true);
             $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':
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, gT("Arithmetic mean"));
                     $this->sheet->writeNumber($this->xlsRow, 1, $am);
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, gT("Standard deviation"));
                     $this->sheet->writeNumber($this->xlsRow, 1, $stddev);
                     break;
                 case 'pdf':
                     $tablePDF[] = array(gT("Arithmetic mean"), $am, '', '');
                     $tablePDF[] = array(gT("Standard deviation"), $stddev, '', '');
                     break;
                 case 'html':
                     //calculate standard deviation
                     $statisticsoutput .= "<tr><td align='center'>" . gT("Arithmetic mean") . "</td>";
                     //German: "Fallzahl"
                     $statisticsoutput .= "<td>&nbsp;</td><td align='center'> {$am}</td><td>&nbsp;</td></tr>";
                     $statisticsoutput .= "<tr><td align='center'>" . gT("Standard deviation") . "</td>";
                     //German: "Fallzahl"
                     $statisticsoutput .= "<td>&nbsp;</td><td align='center'>{$stddev}</td><td>&nbsp;</td></tr>";
                     break;
                 default:
                     break;
             }
         }
     }
     if ($outputType == 'pdf') {
         //$tablePDF = array();
         $tablePDF = array_merge_recursive($tablePDF, $footPDF);
         $this->pdf->headTable($headPDF, $tablePDF);
         //$this->pdf->tableintopdf($tablePDF);
         //                if(isset($footPDF))
         //                foreach($footPDF as $foot)
         //                {
         //                    $footA = array($foot);
         //                    $this->pdf->tablehead($footA);
         //                }
         if (isset($headPDF2)) {
             $this->pdf->headTable($headPDF2, $tablePDF2);
         }
     }
     if ($outputType == 'xls' && (isset($headXLS) || isset($tableXLS))) {
         if (isset($headXLS)) {
             $this->xlsRow++;
             $this->xlsRow++;
             foreach ($headXLS as $aRow) {
                 $this->xlsRow++;
                 $iColumn = 0;
                 foreach ($aRow as $sValue) {
                     $this->sheet->write($this->xlsRow, $iColumn, $sValue, $this->formatBold);
                     $iColumn++;
                 }
             }
         }
         if (isset($tableXLS)) {
             foreach ($tableXLS as $aRow) {
                 $this->xlsRow++;
                 $iColumn = 0;
                 foreach ($aRow as $sValue) {
                     $this->sheet->write($this->xlsRow, $iColumn, $sValue);
                     $iColumn++;
                 }
             }
         }
     }
     if ($outputType == 'html') {
         $statisticsoutput .= "<tr><td colspan='4' style=\"text-align:center\" id='statzone_{$rt}'>";
     }
     //-------------------------- PCHART OUTPUT ----------------------------
     list($qsid, $qgid, $qqid) = explode("X", $rt, 3);
     $qsid = $surveyid;
     $aattr = getQuestionAttributeValues($outputs['parentqid'], substr($rt, 0, 1));
     //PCHART has to be enabled and we need some data
     if ($usegraph == 1) {
         $bShowGraph = $aattr["statistics_showgraph"] == "1";
         $bAllowPieChart = $outputs['qtype'] != "M" && $outputs['qtype'] != "P";
         $bAllowMap = isset($aattr["location_mapservice"]) && $aattr["location_mapservice"] == "1";
         $bShowMap = $bAllowMap && $aattr["statistics_showmap"] == "1";
         $bShowPieChart = $bAllowPieChart && (isset($aattr["statistics_graphtype"]) && $aattr["statistics_graphtype"] == "1");
         $astatdata[$rt] = array('id' => $rt, 'sg' => $bShowGraph, 'ap' => $bAllowPieChart, 'am' => $bAllowMap, 'sm' => $bShowMap, 'sp' => $bShowPieChart);
         $stats = Yii::app()->session['stats'];
         $stats[$rt] = array('lbl' => $lbl, 'gdata' => $gdata, 'grawdata' => $grawdata);
         Yii::app()->session['stats'] = $stats;
         if ($bShowGraph == true) {
             $cachefilename = createChart($qqid, $qsid, $bShowPieChart, $lbl, $gdata, $grawdata, $MyCache, $sLanguage, $outputs['qtype']);
             if ($cachefilename) {
                 //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':
                         $this->pdf->AddPage('P', 'A4');
                         $this->pdf->titleintopdf($pdfTitle, $titleDesc);
                         $this->pdf->Image($tempdir . "/" . $cachefilename, 0, 70, 180, 0, '', Yii::app()->getController()->createUrl("admin/survey/sa/view/surveyid/" . $surveyid), 'B', true, 150, 'C', false, false, 0, true);
                         break;
                     case 'html':
                         $statisticsoutput .= "<img src=\"{$tempurl}/" . $cachefilename . "\" border='1' />";
                         $aattr = getQuestionAttributeValues($qqid, $firstletter);
                         if ($bShowMap) {
                             $statisticsoutput .= "<div id=\"statisticsmap_{$rt}\" class=\"statisticsmap\"></div>";
                             $agmapdata[$rt] = array("coord" => getQuestionMapData(substr($rt, 1), $qsid), "zoom" => $aattr['location_mapzoom'], "width" => $aattr['location_mapwidth'], "height" => $aattr['location_mapheight']);
                         }
                         break;
                     default:
                         break;
                 }
             }
         }
     }
     //close table/output
     if ($outputType == 'html') {
         // show this block only when we show graphs and are not in the public statics controller
         // this is because the links don't work from that controller
         if ($usegraph == 1 && get_class(Yii::app()->getController()) !== 'Statistics_userController') {
             $sImgUrl = Yii::app()->getConfig('adminimageurl');
             $statisticsoutput .= "</td></tr><tr><td colspan='4'><div id='stats_{$rt}' class='graphdisplay' style=\"text-align:center\">" . "<img class='stats-hidegraph' src='{$sImgUrl}/chart_disabled.png' title='" . gT("Disable chart") . "' />" . "<img class='stats-showgraph' src='{$sImgUrl}/chart.png' title='" . gT("Enable chart") . "' />" . "<img class='stats-showbar' src='{$sImgUrl}/chart_bar.png' title='" . gT("Display as bar chart") . "' />" . "<img class='stats-showpie' src='{$sImgUrl}/chart_pie.png' title='" . gT("Display as pie chart") . "' />" . "<img class='stats-showmap' src='{$sImgUrl}/map_disabled.png' title='" . gT("Disable map display") . "' />" . "<img class='stats-hidemap' src='{$sImgUrl}/map.png' title='" . gT("Enable map display") . "' />" . "</div></td></tr>";
         }
         $statisticsoutput .= "</td></tr></table><br /> \n";
     }
     return array("statisticsoutput" => $statisticsoutput, "pdf" => $this->pdf, "astatdata" => $astatdata);
 }
Exemplo n.º 4
0
 /**
  * displayResults builds html output to display the actual results from a survey
  *
  * @param mixed $outputs
  * @param INT $results The number of results being displayed overall
  * @param mixed $rt
  * @param mixed $outputType
  * @param mixed $surveyid
  * @param mixed $sql
  * @param mixed $usegraph
  *
  *
  */
 protected function displayResults($outputs, $results, $rt, $outputType, $surveyid, $sql, $usegraph, $browse, $sLanguage)
 {
     /* Set up required variables */
     $TotalCompleted = 0;
     //Count of actually completed answers
     $statisticsoutput = "";
     $sDatabaseType = Yii::app()->db->getDriverName();
     $tempdir = Yii::app()->getConfig("tempdir");
     $tempurl = Yii::app()->getConfig("tempurl");
     $firstletter = substr($rt, 0, 1);
     $astatdata = array();
     if ($usegraph == 1 && $outputType != 'html') {
         //for creating graphs we need some more scripts which are included here
         require_once APPPATH . '/third_party/pchart/pchart/pChart.class';
         require_once APPPATH . '/third_party/pchart/pchart/pData.class';
         require_once APPPATH . '/third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache($tempdir . '/');
     }
     switch ($outputType) {
         case 'xls':
             $xlsTitle = sprintf(gT("Field summary for %s"), html_entity_decode($outputs['qtitle'], ENT_QUOTES, 'UTF-8'));
             $xlsDesc = html_entity_decode($outputs['qquestion'], ENT_QUOTES, 'UTF-8');
             $this->xlsRow++;
             $this->xlsRow++;
             $this->xlsRow++;
             $this->sheet->write($this->xlsRow, 0, $xlsTitle);
             $this->xlsRow++;
             $this->sheet->write($this->xlsRow, 0, $xlsDesc);
             $footXLS = array();
             break;
         case 'pdf':
             $sPDFQuestion = flattenText($outputs['qquestion'], false, true);
             $pdfTitle = $this->pdf->delete_html(sprintf(gT("Field summary for %s"), html_entity_decode($outputs['qtitle'], ENT_QUOTES, 'UTF-8')));
             $titleDesc = $sPDFQuestion;
             $this->pdf->AddPage('P', 'A4');
             $this->pdf->Bookmark($sPDFQuestion, 1, 0);
             $this->pdf->titleintopdf($pdfTitle, $sPDFQuestion);
             $tablePDF = array();
             $footPDF = array();
             break;
         case 'html':
             // output now generated in subview _statisticsoutuput_header
             break;
         default:
             break;
     }
     //loop though the array which contains all answer data
     $ColumnName_RM = array();
     //echo '<pre>'; var_dump($outputs['alist']); echo '</pre>';die;
     foreach ($outputs['alist'] as $al) {
         //picks out answer list ($outputs['alist']/$al)) that come from the multiple list above
         if (isset($al[2]) && $al[2]) {
             //handling for "other" option
             if ($al[0] == gT("Other")) {
                 if ($outputs['qtype'] == '!' || $outputs['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
                     /* This query selects a count of responses where "other" has been selected */
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName(substr($al[2], 0, strlen($al[2]) - 5)) . "='-oth-'";
                 } else {
                     //get data - select a count of responses where no answer is provided
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ";
                     $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " != ''" : "NOT (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE '')";
                 }
             } elseif ($outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "S" || $outputs['qtype'] == "Q" || $outputs['qtype'] == ";") {
                 $sDatabaseType = Yii::app()->db->getDriverName();
                 //free text answers
                 if ($al[0] == "Answer") {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ";
                     $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " != ''" : "NOT (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE '')";
                 } elseif ($al[0] == "NoAnswer") {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( ";
                     $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " = '')" : " (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE ''))";
                 }
             } elseif ($outputs['qtype'] == "O") {
                 $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( ";
                 $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " <> '')" : " (" . Yii::app()->db->quoteColumnName($al[2]) . " NOT LIKE ''))";
                 // all other question types
             } else {
                 $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($al[2]) . " =";
                 //ranking question?
                 if (substr($rt, 0, 1) == "R") {
                     $query .= " '{$al['0']}'";
                 } else {
                     $query .= " 'Y'";
                 }
             }
         } else {
             if ($al[0] != "") {
                 //get more data
                 $sDatabaseType = Yii::app()->db->getDriverName();
                 if ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
                     // mssql cannot compare text blobs so we have to cast here
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar)= '{$al['0']}'";
                 } else {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($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 ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
                     // mssql cannot compare text blobs so we have to cast here
                     //$query = "SELECT count(*) FROM {{survey_$surveyid}} WHERE (".sanitize_int($rt)." IS NULL "
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( " . "cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar) = '' " . "OR cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar) = ' ' )";
                 } elseif ($sDatabaseType == 'pgsql') {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( " . " " . Yii::app()->db->quoteColumnName($rt) . "::text = '' " . "OR " . Yii::app()->db->quoteColumnName($rt) . "::text = ' ') ";
                 } else {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( " . " " . Yii::app()->db->quoteColumnName($rt) . " = '' " . "OR " . Yii::app()->db->quoteColumnName($rt) . " = ' ') ";
                 }
             }
         }
         //check filter option
         if (incompleteAnsFilterState() == "incomplete") {
             $query .= " AND submitdate is null";
         } elseif (incompleteAnsFilterState() == "complete") {
             $query .= " AND submitdate is not null";
         }
         //check for any "sql" that has been passed from another script
         if (!empty($sql)) {
             $query .= " AND {$sql}";
         }
         //get data
         $row = Yii::app()->db->createCommand($query)->queryScalar();
         //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;
         //"no answer" handling
         if ($al[0] === "") {
             $fname = gT("No answer");
         } elseif ($al[0] === gT("Other") || $al[0] === "Answer" || $outputs['qtype'] === "O" && $al[0] === gT("Comments") || $outputs['qtype'] === "P") {
             if ($outputs['qtype'] == "P") {
                 $sColumnName = $al[2] . "comment";
             } else {
                 $sColumnName = $al[2];
             }
             $ColumnName_RM[] = $sColumnName;
             if ($outputs['qtype'] == 'O') {
                 $TotalCompleted -= $row;
             }
             $fname = "{$al['1']}";
             if ($browse === true) {
                 $fname .= " <input type='button' class='statisticsbrowsebutton btn btn-default btn-large' value='" . gT("Browse") . "' id='{$sColumnName}' />";
             }
             if ($browse === true && isset($_POST['showtextinline']) && $outputType == 'pdf') {
                 $headPDF2 = array();
                 $headPDF2[] = array(gT("ID"), gT("Response"));
                 $tablePDF2 = array();
                 $result2 = $this->_listcolumn($surveyid, $sColumnName);
                 foreach ($result2 as $row2) {
                     $tablePDF2[] = array($row2['id'], $row2['value']);
                 }
             }
             if ($browse === true && isset($_POST['showtextinline']) && $outputType == 'xls') {
                 $headXLS = array();
                 $tableXLS = array();
                 $headXLS[] = array(gT("ID"), gT("Response"));
                 $result2 = $this->_listcolumn($surveyid, $sColumnName);
                 foreach ($result2 as $row2) {
                     $tableXLS[] = array($row2['id'], $row2['value']);
                 }
             }
         } elseif ($outputs['qtype'] == "S" || $outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "Q") {
             $headPDF = array();
             $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"));
             //show free text answers
             if ($al[0] == "Answer") {
                 $fname = "{$al['1']}";
                 if ($browse === true) {
                     $fname .= " <input type='button'  class='statisticsbrowsebutton btn btn-default btn-large' value='" . gT("Browse") . "' id='{$sColumnName}' />";
                 }
             } elseif ($al[0] == "NoAnswer") {
                 $fname = "{$al['1']}";
             }
             $bShowCount = true;
             $bShowPercentage = true;
             $bAnswer = true;
             // For view
             $bSum = false;
             if ($browse === true && isset($_POST['showtextinline']) && $outputType == 'pdf') {
                 $headPDF2 = array();
                 $headPDF2[] = array(gT("ID"), gT("Response"));
                 $tablePDF2 = array();
                 $result2 = $this->_listcolumn($surveyid, $sColumnName);
                 foreach ($result2 as $row2) {
                     $tablePDF2[] = array($row2['id'], $row2['value']);
                 }
             }
         } elseif (Yii::app()->getConfig('showaggregateddata') == 1) {
             if (!isset($showheadline) || $showheadline != false) {
                 if ($outputs['qtype'] == "5" || $outputs['qtype'] == "A") {
                     switch ($outputType) {
                         case 'xls':
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Answer"));
                             $this->sheet->write($this->xlsRow, 1, gT("Count"));
                             $this->sheet->write($this->xlsRow, 2, gT("Percentage"));
                             $this->sheet->write($this->xlsRow, 3, gT("Sum"));
                             break;
                         case 'pdf':
                             $headPDF = array();
                             $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"), gT("Sum"));
                             break;
                         case 'html':
                             //four columns
                             $bShowCount = true;
                             $bShowPercentage = true;
                             $bAnswer = true;
                             $bSum = true;
                             break;
                         default:
                             break;
                     }
                     $showheadline = false;
                 } else {
                     switch ($outputType) {
                         case 'xls':
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Answer"));
                             $this->sheet->write($this->xlsRow, 1, gT("Count"));
                             $this->sheet->write($this->xlsRow, 2, gT("Percentage"));
                             break;
                         case 'pdf':
                             $headPDF = array();
                             $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"));
                             break;
                         case 'html':
                             //three columns
                             $bAnswer = true;
                             // For view
                             $bSum = false;
                             $bShowCount = true;
                             $bShowPercentage = true;
                             break;
                         default:
                             break;
                     }
                     $showheadline = false;
                 }
             }
             //text for answer column is always needed
             $fname = "{$al['1']} ({$al['0']})";
         } else {
             if (!isset($showheadline) || $showheadline != false) {
                 switch ($outputType) {
                     case 'xls':
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, gT("Answer"));
                         $this->sheet->write($this->xlsRow, 1, gT("Count"));
                         $this->sheet->write($this->xlsRow, 2, gT("Percentage"));
                         break;
                     case 'pdf':
                         $headPDF = array();
                         $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"));
                         break;
                     case 'html':
                         //three columns
                         $bAnswer = true;
                         // For view
                         $bSum = false;
                         $bShowCount = true;
                         $bShowPercentage = true;
                         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 / $results * 100;
         } else {
             //no data!
             $gdata[] = "N/A";
         }
         //put absolute data into array
         $grawdata[] = $row;
         if (!(in_array('is_comment', $al) || in_array('is_no_answer', $al))) {
             $grawdata_percents[] = $row;
         }
         //var_dump($grawdata); die();
         //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 has been modified and $tempcount has the original count.
         if ($tempcount > -1) {
             $flatLabel = wordwrap(FlattenText("{$al['1']}"), 25, "\n");
             // If the flatten label is empty (like for picture, or HTML, etc.)
             // We replace it by the subquestion code
             if ($flatLabel == '') {
                 $flatLabel = $al[0];
             }
             // For legend
             $lbl[$flatLabel] = $tempcount;
         } else {
             $flatLabel = wordwrap(FlattenText("{$al['1']}"), 25, "\n");
             // If the flatten label is empty (like for picture, or HTML, etc.)
             // We replace it by the subquestion code
             if ($flatLabel == '') {
                 $flatLabel = $al[0];
             }
             $lbl[$flatLabel] = $row;
         }
         // For Graph labels
         switch ($_POST['graph_labels']) {
             case 'qtext':
                 $aGraphLabels[] = $sFlatLabel = $flatLabel;
                 break;
             case 'both':
                 $aGraphLabels[] = $sFlatLabel = $al[0] . ': ' . $flatLabel;
                 break;
             default:
                 $aGraphLabels[] = $sFlatLabel = $al[0];
                 break;
         }
         if (!(in_array('is_comment', $al) || in_array('is_no_answer', $al))) {
             $aGraphLabelsPercent[] = $sFlatLabel;
             $lblPercent[$flatLabel] = $lbl[$flatLabel];
         }
     }
     //end foreach -> loop through answer data
     //no filtering of incomplete answers and NO multiple option questions
     //if ((incompleteAnsFilterState() != "complete") and ($outputs['qtype'] != "M") and ($outputs['qtype'] != "P"))
     //error_log("TIBO ".print_r($showaggregated_indice_table,true));
     if ($outputs['qtype'] != "M" and $outputs['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'] == 1) && (isset(Yii::app()->getConfig('showaggregateddata')) && Yii::app()->getConfig('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'] == 1) {
             //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)
         } else {
             //calculate total number of incompleted records
             $TotalIncomplete = $results - $TotalCompleted;
             //output
             if (incompleteAnsFilterState() != "complete") {
                 $fname = gT("Not completed or Not displayed");
             } else {
                 $fname = gT("Not displayed");
             }
             //we need some data
             if ($results > 0) {
                 //calculate percentage
                 $gdata[] = $TotalIncomplete / $results * 100;
             } 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 another array
             if (incompleteAnsFilterState() != "complete") {
                 $flatLabel = gT("Not completed or Not displayed");
                 // If the flatten label is empty (like for picture, or HTML, etc.)
                 // We replace it by the subquestion code
                 if ($flatLabel == '') {
                     $flatLabel = $al[0];
                 }
                 $lbl[$flatLabel] = $TotalIncomplete;
             } else {
                 $flatLabel = gT("Not displayed");
                 // If the flatten label is empty (like for picture, or HTML, etc.)
                 // We replace it by the subquestion code
                 if ($flatLabel == '') {
                     $flatLabel = $al[0];
                 }
                 $lbl[$flatLabel] = $TotalIncomplete;
             }
         }
         //end else -> noncompleted NOT checked
     }
     // For multi question type, we have to check non completed with ALL sub question set to NULL
     if ($outputs['qtype'] == "M" or $outputs['qtype'] == "P") {
         $criteria = new CDbCriteria();
         foreach ($outputs['alist'] as $al) {
             $criteria->addCondition(Yii::app()->db->quoteColumnName($al[2]) . " IS NULL");
         }
         if (incompleteAnsFilterState() == "incomplete") {
             $criteria->addCondition("submitdate IS NULL");
         } elseif (incompleteAnsFilterState() == "complete") {
             $criteria->addCondition("submitdate IS NOT NULL");
         }
         $multiNotDisplayed = SurveyDynamic::model($surveyid)->count($criteria);
         if (isset($_POST['noncompleted']) and $_POST['noncompleted'] == 1) {
             //counter
             $i = 0;
             while (isset($gdata[$i])) {
                 //we want to have some "real" data here
                 if ($gdata[$i] != "N/A") {
                     //calculate percentage
                     if ($results > $multiNotDisplayed) {
                         $gdata[$i] = $grawdata[$i] / ($results - $multiNotDisplayed) * 100;
                     } else {
                         $gdata[$i] = "N/A";
                     }
                 }
                 $i++;
             }
         } else {
             // Add a line with not displayed %
             if ($multiNotDisplayed > 0) {
                 if (incompleteAnsFilterState() != "complete") {
                     $fname = gT("Not completed or Not displayed");
                 } else {
                     $fname = gT("Not displayed");
                 }
                 $label[] = $fname;
                 $lbl[$fname] = $multiNotDisplayed;
                 //we need some data
                 if ($results > 0) {
                     //calculate percentage
                     $gdata[] = $multiNotDisplayed / $results * 100;
                 } else {
                     $gdata[] = "N/A";
                 }
                 //put data of incompleted records into array
                 $grawdata[] = $multiNotDisplayed;
             }
         }
     }
     // Columns
     $statsColumns = $_POST['stats_columns'];
     switch ($statsColumns) {
         case "1":
             $nbcols = "12";
             $canvaWidth = "1150";
             $canvaHeight = "800";
             break;
         case "3":
             $nbcols = "4";
             $canvaWidth = "333";
             $canvaHeight = "500";
             break;
         default:
             $nbcols = "6";
             $canvaWidth = "500";
             $canvaHeight = "500";
             break;
     }
     //
     //counter
     $i = 0;
     //we need to know which item we are editing
     $itemcounter = 1;
     $aData['nbcols'] = $nbcols;
     $aData['canvaWidth'] = $canvaWidth;
     $aData['canvaHeight'] = $canvaHeight;
     $aData['outputs'] = isset($outputs) ? $outputs : '';
     $aData['bSum'] = isset($bSum) ? $bSum : false;
     $aData['bAnswer'] = isset($bAnswer) ? $bAnswer : false;
     $aData['bShowCount'] = isset($bShowCount) ? $bShowCount : false;
     $aData['bShowPercentage'] = isset($bShowPercentage) ? $bShowPercentage : false;
     $statisticsoutput = Yii::app()->getController()->renderPartial('/admin/export/generatestats/_statisticsoutput_header', $aData, true);
     //loop through all available answers
     ////
     while (isset($gdata[$i])) {
         $aData['i'] = $i;
         ///// We'll render at the end of this loop statisticsoutput_answer
         //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
          */
         /*
          * If there is a "browse" button in this label, let's make sure there's an extra row afterwards
          * to store the columnlist
          *
          * */
         if (strpos($label[$i], "statisticsbrowsebutton")) {
             $extraline = "<tr><td class='statisticsbrowsecolumn' colspan='3' style='display: none'>";
             if ($outputs['qtype'] == 'P') {
                 $extraline .= "<div class='statisticsbrowsecolumn' id='columnlist_{$ColumnName_RM[$i]}'></div></td></tr>\n";
                 $sColumnNameForView = $ColumnName_RM[$i];
             } else {
                 $extraline .= "<div class='statisticsbrowsecolumn' id='columnlist_{$sColumnName}'></div></td></tr>\n";
                 $sColumnNameForView = $sColumnName;
             }
         }
         //no data
         if ($gdata[$i] === "N/A") {
             switch ($outputType) {
                 case 'xls':
                     $label[$i] = flattenText($label[$i]);
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, $label[$i]);
                     $this->sheet->writeNumber($this->xlsRow, 1, $grawdata[$i]);
                     $this->sheet->writeNumber($this->xlsRow, 2, $gdata[$i] / 100, $this->xlsPercents);
                     break;
                 case 'pdf':
                     $tablePDF[] = array(flattenText($label[$i]), $grawdata[$i], sprintf("%01.2f", $gdata[$i]) . "%", "");
                     break;
                 case 'html':
                     //output when having no data
                     /// _statisticsoutput_answer
                     $bNAgData = true;
                     if (isset($extraline)) {
                         $bNAgDataExtraLine = $extraline;
                     }
                     break;
                 default:
                     break;
             }
         } else {
             //check if data should be aggregated
             if (Yii::app()->getConfig('showaggregateddata') == 1 && ($outputs['qtype'] == "5" || $outputs['qtype'] == "A")) {
                 //mark that we have done soemthing special here
                 $aggregated = true;
                 if ($results - $grawdata[5] > 0) {
                     $percentage = $grawdata[$i] / ($results - $grawdata[5]) * 100;
                     // Only answered
                 } else {
                     $percentage = 0;
                 }
                 switch ($itemcounter) {
                     case 1:
                         if ($results - $grawdata[5] > 0) {
                             $aggregatedPercentage = ($grawdata[0] + $grawdata[1]) / ($results - $grawdata[5]) * 100;
                         } else {
                             $aggregatedPercentage = 0;
                         }
                         break;
                     case 3:
                         $aggregatedPercentage = $percentage;
                         break;
                     case 5:
                         if ($results - $grawdata[5] > 0) {
                             $aggregatedPercentage = ($grawdata[3] + $grawdata[4]) / ($results - $grawdata[5]) * 100;
                         } else {
                             $aggregatedPercentage = 0;
                         }
                         break;
                     case 6:
                     case 7:
                         if ($results - $grawdata[5] > 0) {
                             $percentage = $grawdata[$i] / $results * 100;
                             // All results
                         } else {
                             $percentage = 0;
                         }
                     default:
                         $aggregatedPercentage = 'na';
                         break;
                 }
                 switch ($outputType) {
                     case 'xls':
                         $label[$i] = flattenText($label[$i]);
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, $label[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 1, $grawdata[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 2, $percentage / 100, $this->xlsPercents);
                         if ($aggregatedPercentage !== 'na') {
                             $this->sheet->writeNumber($this->xlsRow, 3, $aggregatedPercentage / 100, $this->xlsPercents);
                         }
                         break;
                     case 'pdf':
                         $label[$i] = flattenText($label[$i]);
                         if ($aggregatedPercentage !== 'na') {
                             $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", sprintf("%01.2f", $aggregatedPercentage) . "%");
                         } else {
                             $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", "");
                         }
                         break;
                     case 'html':
                         //output percentage
                         $bNAgData = true;
                         if ($aggregatedPercentage !== 'na') {
                             $showAggregatedPercentage = true;
                         } else {
                             $showEmptyAggregatedPercentage = true;
                         }
                         break;
                     default:
                         break;
                 }
                 if ($itemcounter == 5) {
                     // new row "sum"
                     //calculate sum of items 1-5
                     $sumitems = $grawdata[0] + $grawdata[1] + $grawdata[2] + $grawdata[3] + $grawdata[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(gT("Sum") . " (" . gT("Answers") . ")", $sumitems, $sumpercentage . "%", $sumpercentage . "%");
                             $footXLS[] = array(gT("Number of cases"), $TotalCompleted, $casepercentage . "%", "");
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Sum") . " (" . gT("Answers") . ")");
                             $this->sheet->writeNumber($this->xlsRow, 1, $sumitems);
                             $this->sheet->writeNumber($this->xlsRow, 2, $sumpercentage / 100, $this->xlsPercents);
                             $this->sheet->writeNumber($this->xlsRow, 3, $sumpercentage / 100, $this->xlsPercents);
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Number of cases"));
                             $this->sheet->writeNumber($this->xlsRow, 1, $TotalCompleted);
                             $this->sheet->writeNumber($this->xlsRow, 2, $casepercentage / 100, $this->xlsPercents);
                             break;
                         case 'pdf':
                             $footPDF[] = array(gT("Sum") . " (" . gT("Answers") . ")", $sumitems, $sumpercentage . "%", $sumpercentage . "%");
                             $footPDF[] = array(gT("Number of cases"), $TotalCompleted, $casepercentage . "%", "");
                             break;
                         case 'html':
                             $bShowSumAnswer = true;
                             break;
                         default:
                             break;
                     }
                 }
             } else {
                 switch ($outputType) {
                     case 'xls':
                         $label[$i] = flattenText($label[$i]);
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, $label[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 1, $grawdata[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 2, $gdata[$i] / 100, $this->xlsPercents);
                         break;
                     case 'pdf':
                         $label[$i] = flattenText($label[$i]);
                         $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $gdata[$i]) . "%", "");
                         break;
                     case 'html':
                         //output percentage
                         $bNAgData = true;
                         if (isset($extraline)) {
                             $bNAgDataExtraLine = $extraline;
                         }
                         break;
                     default:
                         break;
                 }
             }
         }
         //end else -> $gdata[$i] != "N/A"
         //increase counter
         $i++;
         $itemcounter++;
         //Clear extraline
         unset($extraline);
         // Convert grawdata_percent to percent
         if (isset($grawdata_percents)) {
             $pTotal = array_sum($grawdata_percents);
             if ($pTotal > 0) {
                 foreach ($grawdata_percents as $key => $data) {
                     $grawdata_percents[$key] = round($data / $pTotal * 100, 2);
                 }
             }
         } else {
             $grawdata_percents = array();
         }
         ///// HERE RENDER statisticsoutput_answer
         $aData['label'] = $label;
         $aData['grawdata'] = $grawdata;
         $aData['grawdata_percent'] = $grawdata_percents;
         $aData['gdata'] = $gdata;
         $aData['extraline'] = isset($extraline) ? $extraline : false;
         $aData['aggregated'] = isset($aggregated) ? $aggregated : false;
         $aData['aggregatedPercentage'] = isset($aggregatedPercentage) ? $aggregatedPercentage : false;
         $aData['sumitems'] = isset($sumitems) ? $sumitems : false;
         $aData['sumpercentage'] = isset($sumpercentage) ? $sumpercentage : false;
         $aData['TotalCompleted'] = isset($TotalCompleted) ? $TotalCompleted : false;
         $aData['casepercentage'] = isset($casepercentage) ? $casepercentage : false;
         $aData['bNAgData'] = isset($bNAgData) ? $bNAgData : false;
         $aData['bNAgDataExtraLine'] = isset($bNAgDataExtraLine) ? $bNAgDataExtraLine : false;
         $aData['showAggregatedPercentage'] = isset($showAggregatedPercentage) ? $showAggregatedPercentage : false;
         $aData['showEmptyAggregatedPercentage'] = isset($showEmptyAggregatedPercentage) ? $showEmptyAggregatedPercentage : false;
         $aData['bShowSumAnswer'] = isset($bShowSumAnswer) ? $bShowSumAnswer : false;
         // Generate answer
         // _statisticsoutput_answer
         $statisticsoutput .= Yii::app()->getController()->renderPartial('/admin/export/generatestats/_statisticsoutput_answer', $aData, true);
         $extraline = false;
         $aggregated = false;
         $aggregatedPercentage = false;
         $sumitems = false;
         $sumpercentage = false;
         $TotalCompleted = false;
         $casepercentage = false;
         $bNAgData = false;
         $bNAgDataExtraLine = false;
         $showAggregatedPercentage = false;
         $showEmptyAggregatedPercentage = false;
         $bShowSumAnswer = false;
     }
     //end while
     $aData['showaggregateddata'] = false;
     //only show additional values when this setting is enabled
     if (Yii::app()->getConfig('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 ($outputs['qtype'] == "5" || $outputs['qtype'] == "A") {
             $stddev = 0;
             $stddevarray = array_slice($grawdata, 0, 5, true);
             $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':
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, gT("Arithmetic mean"));
                     $this->sheet->writeNumber($this->xlsRow, 1, $am);
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, gT("Standard deviation"));
                     $this->sheet->writeNumber($this->xlsRow, 1, $stddev);
                     break;
                 case 'pdf':
                     $tablePDF[] = array(gT("Arithmetic mean"), $am, '', '');
                     $tablePDF[] = array(gT("Standard deviation"), $stddev, '', '');
                     break;
                 case 'html':
                     //calculate standard deviation
                     $aData['am'] = $am;
                     $aData['stddev'] = $stddev;
                     $statisticsoutput .= Yii::app()->getController()->renderPartial('/admin/export/generatestats/_statisticsoutput_arithmetic', $aData, true);
                     break;
                 default:
                     break;
             }
         }
     }
     if ($outputType == 'pdf') {
         //$tablePDF = array();
         $tablePDF = array_merge_recursive($tablePDF, $footPDF);
         if (!isset($headPDF)) {
             // TODO: Why is $headPDF sometimes undefined here?
             $headPDF = array();
         }
         $this->pdf->headTable($headPDF, $tablePDF);
         //$this->pdf->tableintopdf($tablePDF);
         //                if(isset($footPDF))
         //                foreach($footPDF as $foot)
         //                {
         //                    $footA = array($foot);
         //                    $this->pdf->tablehead($footA);
         //                }
         if (isset($headPDF2)) {
             $this->pdf->headTable($headPDF2, $tablePDF2);
         }
     }
     if ($outputType == 'xls' && (isset($headXLS) || isset($tableXLS))) {
         if (isset($headXLS)) {
             $this->xlsRow++;
             $this->xlsRow++;
             foreach ($headXLS as $aRow) {
                 $this->xlsRow++;
                 $iColumn = 0;
                 foreach ($aRow as $sValue) {
                     $this->sheet->write($this->xlsRow, $iColumn, $sValue, $this->formatBold);
                     $iColumn++;
                 }
             }
         }
         if (isset($tableXLS)) {
             foreach ($tableXLS as $aRow) {
                 $this->xlsRow++;
                 $iColumn = 0;
                 foreach ($aRow as $sValue) {
                     $this->sheet->write($this->xlsRow, $iColumn, $sValue);
                     $iColumn++;
                 }
             }
         }
     }
     if ($outputType == 'html') {
     }
     // _statisticsoutput_graphs.php
     //-------------------------- PCHART OUTPUT ----------------------------
     list($qsid, $qgid, $qqid) = explode("X", $rt, 3);
     $qsid = $surveyid;
     $aattr = getQuestionAttributeValues($outputs['parentqid'], substr($rt, 0, 1));
     //PCHART has to be enabled and we need some data
     //
     if ($usegraph == 1) {
         $bShowGraph = $aattr["statistics_showgraph"] == "1";
         $bAllowPieChart = $outputs['qtype'] != "M" && $outputs['qtype'] != "P";
         $bAllowMap = isset($aattr["location_mapservice"]) && $aattr["location_mapservice"] == "1";
         $bShowMap = $bAllowMap && $aattr["statistics_showmap"] == "1";
         $bShowPieChart = $bAllowPieChart && (isset($aattr["statistics_graphtype"]) && $aattr["statistics_graphtype"] == "1");
         $astatdata[$rt] = array('id' => $rt, 'sg' => $bShowGraph, 'ap' => $bAllowPieChart, 'am' => $bAllowMap, 'sm' => $bShowMap, 'sp' => $bShowPieChart);
         $stats = Yii::app()->session['stats'];
         $stats[$rt] = array('lbl' => $lbl, 'gdata' => $gdata, 'grawdata' => $grawdata);
         Yii::app()->session['stats'] = $stats;
         if ($bShowGraph == true) {
             $cachefilename = '';
             if ($outputType == 'xls' || $outputType == 'pdf') {
                 $cachefilename = createChart($qqid, $qsid, $bShowPieChart, $lbl, $gdata, $grawdata, $MyCache, $sLanguage, $outputs['qtype']);
             }
             if ($cachefilename || $outputType == 'html') {
                 //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':
                         $this->pdf->AddPage('P', 'A4');
                         $this->pdf->titleintopdf($pdfTitle, $titleDesc);
                         $this->pdf->Image($tempdir . "/" . $cachefilename, 0, 70, 180, 0, '', Yii::app()->getController()->createUrl("admin/survey/sa/view/surveyid/" . $surveyid), 'B', true, 150, 'C', false, false, 0, true);
                         break;
                     case 'html':
                         if (isset($aattr["statistics_graphtype"])) {
                             $req_chart_type = $aattr["statistics_graphtype"];
                         }
                         //// If user forced the chartype from statistics_view
                         if (isset($_POST['charttype']) && $_POST['charttype'] != 'default') {
                             $req_chart_type = $_POST['charttype'];
                         }
                         //// The value of the select box in the question advanced setting is numerical. So we need to translate it.
                         if (isset($req_chart_type)) {
                             switch ($req_chart_type) {
                                 case '1':
                                     $charttype = "Pie";
                                     break;
                                 case '2':
                                     $charttype = "Radar";
                                     break;
                                 case '3':
                                     $charttype = "Line";
                                     break;
                                 case '4':
                                     $charttype = "PolarArea";
                                     break;
                                 case '5':
                                     $charttype = "Doughnut";
                                     break;
                                 default:
                                     $charttype = "Bar";
                                     break;
                             }
                         }
                         //// Here the 72 colors of the original limesurvey palette.
                         //// This could be change by some user palette coming from database.
                         $COLORS_FOR_SURVEY = array('20,130,200', '232,95,51', '34,205,33', '210,211,28', '134,179,129', '201,171,131', '251,231,221', '23,169,161', '167,187,213', '211,151,213', '147,145,246', '147,39,90', '250,250,201', '201,250,250', '94,0,94', '250,125,127', '0,96,201', '201,202,250', '0,0,127', '250,0,250', '250,250,0', '0,250,250', '127,0,127', '127,0,0', '0,125,127', '0,0,250', '0,202,250', '201,250,250', '201,250,201', '250,250,151', '151,202,250', '251,149,201', '201,149,250', '250,202,151', '45,96,250', '45,202,201', '151,202,0', '250,202,0', '250,149,0', '250,96,0', '184,230,115', '102,128,64', '220,230,207', '134,191,48', '184,92,161', '128,64,112', '230,207,224', '191,48,155', '230,138,115', '128,77,64', '230,211,207', '191,77,48', '80,161,126', '64,128,100', '207,230,220', '48,191,130', '25,25,179', '18,18,125', '200,200,255', '145,145,255', '255,178,0', '179,125,0', '255,236,191', '255,217,128', '255,255,0', '179,179,0', '255,255,191', '255,255,128', '102,0,153', '71,0,107', '234,191,255', '213,128,255');
                         //// $lbl is generated somewhere upthere by the original code. We translate it for chartjs.
                         $labels = array();
                         foreach ($lbl as $name => $lb) {
                             $labels[] = $name;
                         }
                         if (isset($lblPercent)) {
                             foreach ($lblPercent as $name => $lb) {
                                 $labels_percent[] = $name;
                             }
                         } else {
                             $labels_percent = array();
                         }
                         break;
                     default:
                         break;
                 }
             }
         }
     }
     //close table/output
     if ($outputType == 'html') {
         // show this block only when we show graphs and are not in the public statics controller
         if ($usegraph == 1 && $bShowGraph && get_class(Yii::app()->getController()) !== 'Statistics_userController') {
             // We clean the labels
             $iMaxLabelLength = 0;
             // We clean the labels
             // Labels for graphs
             $iMaxLabelLength = 0;
             foreach ($aGraphLabels as $key => $label) {
                 $cleanLabel = $label;
                 $cleanLabel = viewHelper::flatEllipsizeText($cleanLabel, true, 20);
                 $graph_labels[$key] = $cleanLabel;
                 $iMaxLabelLength = strlen($cleanLabel) > $iMaxLabelLength ? strlen($cleanLabel) : $iMaxLabelLength;
             }
             if (isset($aGraphLabelsPercent)) {
                 foreach ($aGraphLabelsPercent as $key => $label) {
                     $cleanLabel = $label;
                     $cleanLabel = viewHelper::flatEllipsizeText($cleanLabel, true, 20);
                     $graph_labels_percent[$key] = $cleanLabel;
                 }
             } else {
                 $graph_labels_percent = array();
             }
             $iCanvaHeight = $iMaxLabelLength * 3;
             $aData['iCanvaHeight'] = $iCanvaHeight > 150 ? $iCanvaHeight : 150;
             $qqid = str_replace('#', '_', $qqid);
             $aData['rt'] = $rt;
             $aData['qqid'] = $qqid;
             $aData['graph_labels'] = $graph_labels;
             $aData['graph_labels_percent'] = $labels_percent;
             $aData['labels'] = $labels;
             //$aData['COLORS_FOR_SURVEY'] = COLORS_FOR_SURVEY;
             $aData['charttype'] = isset($charttype) ? $charttype : 'Bar';
             $aData['sChartname'] = '';
             $aData['grawdata'] = $grawdata;
             $aData['color'] = rand(0, 70);
             $aData['COLORS_FOR_SURVEY'] = $COLORS_FOR_SURVEY;
             $aData['lbl'] = $lbl;
             ///
             $statisticsoutput .= Yii::app()->getController()->renderPartial('/admin/export/generatestats/_statisticsoutput_graphs', $aData, true);
         }
         $statisticsoutput .= "</table></div> <!-- in statistics helper --> \n";
     }
     return array("statisticsoutput" => $statisticsoutput, "pdf" => $this->pdf, "astatdata" => $astatdata);
 }
Exemplo n.º 5
0
 function graph()
 {
     Yii::app()->loadHelper('admin/statistics');
     Yii::app()->loadHelper("surveytranslator");
     // Initialise PCHART
     require_once Yii::app()->basePath . '/third_party/pchart/pchart/pChart.class';
     require_once Yii::app()->basePath . '/third_party/pchart/pchart/pData.class';
     require_once Yii::app()->basePath . '/third_party/pchart/pchart/pCache.class';
     $tempdir = Yii::app()->getConfig("tempdir");
     $MyCache = new pCache($tempdir . '/');
     $aData['success'] = 1;
     if (isset($_POST['cmd']) && isset($_POST['id'])) {
         list($qsid, $qgid, $qqid) = explode("X", substr($_POST['id'], 0), 3);
         $qtype = substr($_POST['id'], 0, 1);
         $aattr = getQuestionAttributeValues($qqid, substr($_POST['id'], 0, 1));
         $field = substr($_POST['id'], 1);
         switch ($_POST['cmd']) {
             case 'showmap':
                 if (isset($aattr['location_mapservice'])) {
                     $aData['mapdata'] = array("coord" => getQuestionMapData($field, $qsid), "zoom" => $aattr['location_mapzoom'], "width" => $aattr['location_mapwidth'], "height" => $aattr['location_mapheight']);
                     Question_attributes::model()->setAttribute($qqid, 'statistics_showmap', 1);
                 } else {
                     $aData['success'] = 0;
                 }
                 break;
             case 'hidemap':
                 if (isset($aattr['location_mapservice'])) {
                     $aData['success'] = 1;
                     Question_attributes::model()->setAttribute($qqid, 'statistics_showmap', 0);
                 } else {
                     $aData['success'] = 0;
                 }
                 break;
             case 'showgraph':
                 if (isset($aattr['location_mapservice'])) {
                     $aData['mapdata'] = array("coord" => getQuestionMapData($field, $qsid), "zoom" => $aattr['location_mapzoom'], "width" => $aattr['location_mapwidth'], "height" => $aattr['location_mapheight']);
                 }
                 $bChartType = $qtype != "M" && $qtype != "P" && $aattr["statistics_graphtype"] == "1";
                 $adata = Yii::app()->session['stats'][$_POST['id']];
                 $aData['chartdata'] = createChart($qqid, $qsid, $bChartType, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache);
                 Question_attributes::model()->setAttribute($qqid, 'statistics_showgraph', 1);
                 break;
             case 'hidegraph':
                 Question_attributes::model()->setAttribute($qqid, 'statistics_showgraph', 0);
                 break;
             case 'showbar':
                 if ($qtype == "M" || $qtype == "P") {
                     $aData['success'] = 0;
                     break;
                 }
                 Question_attributes::model()->setAttribute($qqid, 'statistics_graphtype', 0);
                 $adata = Yii::app()->session['stats'][$_POST['id']];
                 $aData['chartdata'] = createChart($qqid, $qsid, 0, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache);
                 break;
             case 'showpie':
                 if ($qtype == "M" || $qtype == "P") {
                     $aData['success'] = 0;
                     break;
                 }
                 Question_attributes::model()->setAttribute($qqid, 'statistics_graphtype', 1);
                 $adata = Yii::app()->session['stats'][$_POST['id']];
                 $aData['chartdata'] = createChart($qqid, $qsid, 1, $adata['lbl'], $adata['gdata'], $adata['grawdata'], $MyCache);
                 break;
             default:
                 $aData['success'] = 0;
                 break;
         }
     } else {
         $aData['success'] = 0;
     }
     //$this->_renderWrappedTemplate('export', 'statistics_graph_view', $aData);
     $this->getController()->render('export/statistics_graph_view', $aData);
 }
Exemplo n.º 6
0
 /**
  * displayResults builds html output to display the actual results from a survey
  *
  * @param mixed $outputs
  * @param INT $results The number of results being displayed overall
  * @param mixed $rt
  * @param mixed $outputType
  * @param mixed $surveyid
  * @param mixed $sql
  * @param mixed $usegraph
  * 
  * 
  */
 protected function displayResults($outputs, $results, $rt, $outputType, $surveyid, $sql, $usegraph, $browse, $sLanguage)
 {
     /* Set up required variables */
     $TotalCompleted = 0;
     //Count of actually completed answers
     $statisticsoutput = "";
     $sDatabaseType = Yii::app()->db->getDriverName();
     $tempdir = Yii::app()->getConfig("tempdir");
     $tempurl = Yii::app()->getConfig("tempurl");
     $firstletter = substr($rt, 0, 1);
     $astatdata = array();
     if ($usegraph == 1) {
         //for creating graphs we need some more scripts which are included here
         require_once APPPATH . '/third_party/pchart/pchart/pChart.class';
         require_once APPPATH . '/third_party/pchart/pchart/pData.class';
         require_once APPPATH . '/third_party/pchart/pchart/pCache.class';
         $MyCache = new pCache($tempdir . '/');
     }
     switch ($outputType) {
         case 'xls':
             $xlsTitle = sprintf(gT("Field summary for %s"), html_entity_decode($outputs['qtitle'], ENT_QUOTES, 'UTF-8'));
             $xlsDesc = html_entity_decode($outputs['qquestion'], ENT_QUOTES, 'UTF-8');
             $this->xlsRow++;
             $this->xlsRow++;
             $this->xlsRow++;
             $this->sheet->write($this->xlsRow, 0, $xlsTitle);
             $this->xlsRow++;
             $this->sheet->write($this->xlsRow, 0, $xlsDesc);
             $footXLS = array();
             break;
         case 'pdf':
             $sPDFQuestion = flattenText($outputs['qquestion'], false, true);
             $pdfTitle = $this->pdf->delete_html(sprintf(gT("Field summary for %s"), html_entity_decode($outputs['qtitle'], ENT_QUOTES, 'UTF-8')));
             $titleDesc = $sPDFQuestion;
             $this->pdf->AddPage('P', 'A4');
             $this->pdf->Bookmark($sPDFQuestion, 1, 0);
             $this->pdf->titleintopdf($pdfTitle, $sPDFQuestion);
             $tablePDF = array();
             $footPDF = array();
             break;
         case 'html':
             //output
             $statisticsoutput .= "<table class='statisticstable table table-bordered'>\n" . "\t<thead><tr class='success'><th colspan='4' align='center' style='text-align: center; '><strong>" . sprintf(gT("Field summary for %s"), $outputs['qtitle']) . "</strong>" . "</th></tr>\n" . "\t<tr><th colspan='4' align='center' style='text-align: center; '><strong>" . $outputs['qquestion'] . "</strong></th></tr>\n" . "\t<tr>\n\t\t<th width='50%' align='center' >";
             break;
         default:
             break;
     }
     //loop though the array which contains all answer data
     $ColumnName_RM = array();
     foreach ($outputs['alist'] as $al) {
         //picks out answer list ($outputs['alist']/$al)) that come from the multiple list above
         if (isset($al[2]) && $al[2]) {
             //handling for "other" option
             if ($al[0] == gT("Other")) {
                 if ($outputs['qtype'] == '!' || $outputs['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
                     /* This query selects a count of responses where "other" has been selected */
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName(substr($al[2], 0, strlen($al[2]) - 5)) . "='-oth-'";
                 } else {
                     //get data - select a count of responses where no answer is provided
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ";
                     $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " != ''" : "NOT (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE '')";
                 }
             } elseif ($outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "S" || $outputs['qtype'] == "Q" || $outputs['qtype'] == ";") {
                 $sDatabaseType = Yii::app()->db->getDriverName();
                 //free text answers
                 if ($al[0] == "Answer") {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ";
                     $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " != ''" : "NOT (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE '')";
                 } elseif ($al[0] == "NoAnswer") {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( ";
                     $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " = '')" : " (" . Yii::app()->db->quoteColumnName($al[2]) . " LIKE ''))";
                 }
             } elseif ($outputs['qtype'] == "O") {
                 $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( ";
                 $query .= $sDatabaseType == "mysql" ? Yii::app()->db->quoteColumnName($al[2]) . " <> '')" : " (" . Yii::app()->db->quoteColumnName($al[2]) . " NOT LIKE ''))";
                 // all other question types
             } else {
                 $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($al[2]) . " =";
                 //ranking question?
                 if (substr($rt, 0, 1) == "R") {
                     $query .= " '{$al['0']}'";
                 } else {
                     $query .= " 'Y'";
                 }
             }
         } else {
             if ($al[0] != "") {
                 //get more data
                 $sDatabaseType = Yii::app()->db->getDriverName();
                 if ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
                     // mssql cannot compare text blobs so we have to cast here
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar)= '{$al['0']}'";
                 } else {
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE " . Yii::app()->db->quoteColumnName($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 ($sDatabaseType == 'mssql' || $sDatabaseType == 'sqlsrv' || $sDatabaseType == 'dblib') {
                     // mssql cannot compare text blobs so we have to cast here
                     //$query = "SELECT count(*) FROM {{survey_$surveyid}} WHERE (".sanitize_int($rt)." IS NULL "
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( " . "cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar) = '' " . "OR cast(" . Yii::app()->db->quoteColumnName($rt) . " as varchar) = ' ' )";
                 } else {
                     //                $query = "SELECT count(*) FROM {{survey_$surveyid}} WHERE (".sanitize_int($rt)." IS NULL "
                     $query = "SELECT count(*) FROM {{survey_{$surveyid}}} WHERE ( " . " " . Yii::app()->db->quoteColumnName($rt) . " = '' " . "OR " . Yii::app()->db->quoteColumnName($rt) . " = ' ') ";
                 }
             }
         }
         //check filter option
         if (incompleteAnsFilterState() == "incomplete") {
             $query .= " AND submitdate is null";
         } elseif (incompleteAnsFilterState() == "complete") {
             $query .= " AND submitdate is not null";
         }
         //check for any "sql" that has been passed from another script
         if (!empty($sql)) {
             $query .= " AND {$sql}";
         }
         //get data
         $row = Yii::app()->db->createCommand($query)->queryScalar();
         // $statisticsoutput .= "\n<!-- ($sql): $query -->\n\n";
         //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;
         //"no answer" handling
         if ($al[0] === "") {
             $fname = gT("No answer");
         } elseif ($al[0] === gT("Other") || $al[0] === "Answer" || $outputs['qtype'] === "O" && $al[0] === gT("Comments") || $outputs['qtype'] === "P") {
             if ($outputs['qtype'] == "P") {
                 $sColumnName = $al[2] . "comment";
             } else {
                 $sColumnName = $al[2];
             }
             $ColumnName_RM[] = $sColumnName;
             if ($outputs['qtype'] == 'O') {
                 $TotalCompleted -= $row;
             }
             $fname = "{$al['1']}";
             if ($browse === true) {
                 $fname .= " <input type='button' class='statisticsbrowsebutton btn btn-default btn-large' value='" . gT("Browse") . "' id='{$sColumnName}' />";
             }
             if ($browse === true && isset($_POST['showtextinline']) && $outputType == 'pdf') {
                 $headPDF2 = array();
                 $headPDF2[] = array(gT("ID"), gT("Response"));
                 $tablePDF2 = array();
                 $result2 = $this->_listcolumn($surveyid, $sColumnName);
                 foreach ($result2 as $row2) {
                     $tablePDF2[] = array($row2['id'], $row2['value']);
                 }
             }
             if ($browse === true && isset($_POST['showtextinline']) && $outputType == 'xls') {
                 $headXLS = array();
                 $tableXLS = array();
                 $headXLS[] = array(gT("ID"), gT("Response"));
                 $result2 = $this->_listcolumn($surveyid, $sColumnName);
                 foreach ($result2 as $row2) {
                     $tableXLS[] = array($row2['id'], $row2['value']);
                 }
             }
         } elseif ($outputs['qtype'] == "S" || $outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "Q") {
             $headPDF = array();
             $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"));
             //show free text answers
             if ($al[0] == "Answer") {
                 $fname = "{$al['1']}";
                 if ($browse === true) {
                     $fname .= " <input type='button'  class='statisticsbrowsebutton btn btn-default btn-large' value='" . gT("Browse") . "' id='{$sColumnName}' />";
                 }
             } elseif ($al[0] == "NoAnswer") {
                 $fname = "{$al['1']}";
             }
             $statisticsoutput .= "</th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . gT("Count") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . gT("Percentage") . "</strong></th>\n" . "\t</tr></thead>\n";
             if ($browse === true && isset($_POST['showtextinline']) && $outputType == 'pdf') {
                 $headPDF2 = array();
                 $headPDF2[] = array(gT("ID"), gT("Response"));
                 $tablePDF2 = array();
                 $result2 = $this->_listcolumn($surveyid, $sColumnName);
                 foreach ($result2 as $row2) {
                     $tablePDF2[] = array($row2['id'], $row2['value']);
                 }
             }
         } elseif (Yii::app()->getConfig('showaggregateddata') == 1) {
             if (!isset($showheadline) || $showheadline != false) {
                 if ($outputs['qtype'] == "5" || $outputs['qtype'] == "A") {
                     switch ($outputType) {
                         case 'xls':
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Answer"));
                             $this->sheet->write($this->xlsRow, 1, gT("Count"));
                             $this->sheet->write($this->xlsRow, 2, gT("Percentage"));
                             $this->sheet->write($this->xlsRow, 3, gT("Sum"));
                             break;
                         case 'pdf':
                             $headPDF = array();
                             $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"), gT("Sum"));
                             break;
                         case 'html':
                             //four columns
                             $statisticsoutput .= "<strong>" . gT("Answer") . "</strong></th>\n" . "\t\t<th width='15%' align='center' >" . "<strong>" . gT("Count") . "</strong></th>\n" . "\t\t<th width='20%' align='center' >" . "<strong>" . gT("Percentage") . "</strong></th>\n" . "\t\t<th width='15%' align='center' >" . "<strong>" . gT("Sum") . "</strong></th>\n" . "\t</tr></thead>\n";
                             break;
                         default:
                             break;
                     }
                     $showheadline = false;
                 } else {
                     switch ($outputType) {
                         case 'xls':
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Answer"));
                             $this->sheet->write($this->xlsRow, 1, gT("Count"));
                             $this->sheet->write($this->xlsRow, 2, gT("Percentage"));
                             break;
                         case 'pdf':
                             $headPDF = array();
                             $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"));
                             break;
                         case 'html':
                             //three columns
                             $statisticsoutput .= "<strong>" . gT("Answer") . "</strong></td>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . gT("Count") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . 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']})";
         } else {
             if (!isset($showheadline) || $showheadline != false) {
                 switch ($outputType) {
                     case 'xls':
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, gT("Answer"));
                         $this->sheet->write($this->xlsRow, 1, gT("Count"));
                         $this->sheet->write($this->xlsRow, 2, gT("Percentage"));
                         break;
                     case 'pdf':
                         $headPDF = array();
                         $headPDF[] = array(gT("Answer"), gT("Count"), gT("Percentage"));
                         break;
                     case 'html':
                         //three columns
                         $statisticsoutput .= "<strong>" . gT("Answer") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . gT("Count") . "</strong></th>\n" . "\t\t<th width='25%' align='center' >" . "<strong>" . 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 / $results * 100;
         } else {
             //no data!
             $gdata[] = "N/A";
         }
         //put absolute data into array
         $grawdata[] = $row;
         //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 has been modified and $tempcount has the original count.
         if ($tempcount > -1) {
             $lbl[wordwrap(FlattenText("{$al['1']}"), 25, "\n")] = $tempcount;
         } else {
             $lbl[wordwrap(FlattenText("{$al['1']}"), 25, "\n")] = $row;
         }
     }
     //end foreach -> loop through answer data
     //no filtering of incomplete answers and NO multiple option questions
     //if ((incompleteAnsFilterState() != "complete") and ($outputs['qtype'] != "M") and ($outputs['qtype'] != "P"))
     //error_log("TIBO ".print_r($showaggregated_indice_table,true));
     if ($outputs['qtype'] != "M" and $outputs['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(Yii::app()->getConfig('showaggregateddata')) && Yii::app()->getConfig('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)
         } else {
             //calculate total number of incompleted records
             $TotalIncomplete = $results - $TotalCompleted;
             //output
             if (incompleteAnsFilterState() != "complete") {
                 $fname = gT("Not completed or Not displayed");
             } else {
                 $fname = gT("Not displayed");
             }
             //we need some data
             if ($results > 0) {
                 //calculate percentage
                 $gdata[] = $TotalIncomplete / $results * 100;
             } 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 another array
             if (incompleteAnsFilterState() != "complete") {
                 $lbl[wordwrap(flattenText(gT("Not completed or Not displayed")), 20, "\n")] = $TotalIncomplete;
             } else {
                 $lbl[wordwrap(flattenText(gT("Not displayed")), 20, "\n")] = $TotalIncomplete;
             }
         }
         //end else -> noncompleted NOT checked
     }
     // For multi question type, we have to check non completed with ALL sub question set to NULL
     if ($outputs['qtype'] == "M" or $outputs['qtype'] == "P") {
         $criteria = new CDbCriteria();
         foreach ($outputs['alist'] as $al) {
             $criteria->addCondition(Yii::app()->db->quoteColumnName($al[2]) . " IS NULL");
         }
         if (incompleteAnsFilterState() == "incomplete") {
             $criteria->addCondition("submitdate IS NULL");
         } elseif (incompleteAnsFilterState() == "complete") {
             $criteria->addCondition("submitdate IS NOT NULL");
         }
         $multiNotDisplayed = SurveyDynamic::model($surveyid)->count($criteria);
         if (isset($_POST['noncompleted']) and $_POST['noncompleted'] == "on") {
             //counter
             $i = 0;
             while (isset($gdata[$i])) {
                 //we want to have some "real" data here
                 if ($gdata[$i] != "N/A") {
                     //calculate percentage
                     if ($results > $multiNotDisplayed) {
                         $gdata[$i] = $grawdata[$i] / ($results - $multiNotDisplayed) * 100;
                     } else {
                         $gdata[$i] = "N/A";
                     }
                 }
                 $i++;
             }
         } else {
             // Add a line with not displayed %
             if ($multiNotDisplayed > 0) {
                 if (incompleteAnsFilterState() != "complete") {
                     $fname = gT("Not completed or Not displayed");
                 } else {
                     $fname = gT("Not displayed");
                 }
                 $label[] = $fname;
                 //we need some data
                 if ($results > 0) {
                     //calculate percentage
                     $gdata[] = $multiNotDisplayed / $results * 100;
                 } else {
                     $gdata[] = "N/A";
                 }
                 //put data of incompleted records into array
                 $grawdata[] = $multiNotDisplayed;
             }
         }
     }
     //counter
     $i = 0;
     //we need to know which item we are editing
     $itemcounter = 1;
     //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";
         /*
          * If there is a "browse" button in this label, let's make sure there's an extra row afterwards
          * to store the columnlist
          *
          * */
         if (strpos($label[$i], "statisticsbrowsebutton")) {
             $extraline = "<tr><td class='statisticsbrowsecolumn' colspan='3' style='display: none'>";
             if ($outputs['qtype'] == 'P') {
                 $extraline .= "<div class='statisticsbrowsecolumn' id='columnlist_{$ColumnName_RM[$i]}'></div></td></tr>\n";
             } else {
                 $extraline .= "<div class='statisticsbrowsecolumn' id='columnlist_{$sColumnName}'></div></td></tr>\n";
             }
         }
         //output absolute number of records
         $statisticsoutput .= "\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]);
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, $label[$i]);
                     $this->sheet->writeNumber($this->xlsRow, 1, $grawdata[$i]);
                     $this->sheet->writeNumber($this->xlsRow, 2, $gdata[$i] / 100, $this->xlsPercents);
                     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 Yii::app()->getConfig('showaggregateddata') setting
                     if (Yii::app()->getConfig('showaggregateddata') == 1 && ($outputs['qtype'] == "5" || $outputs['qtype'] == "A")) {
                         $statisticsoutput .= "\t\t</td>";
                     } elseif ($outputs['qtype'] == "S" || $outputs['qtype'] == "U" || $outputs['qtype'] == "T" || $outputs['qtype'] == "Q") {
                         $statisticsoutput .= "</td>\n\t";
                     }
                     $statisticsoutput .= "</tr>\n";
                     //Close the row
                     if (isset($extraline)) {
                         $statisticsoutput .= $extraline;
                     }
                     break;
                 default:
                     break;
             }
         } else {
             //check if data should be aggregated
             if (Yii::app()->getConfig('showaggregateddata') == 1 && ($outputs['qtype'] == "5" || $outputs['qtype'] == "A")) {
                 //mark that we have done soemthing special here
                 $aggregated = true;
                 if ($results - $grawdata[5] > 0) {
                     $percentage = $grawdata[$i] / ($results - $grawdata[5]) * 100;
                     // Only answered
                 } else {
                     $percentage = 0;
                 }
                 switch ($itemcounter) {
                     case 1:
                         if ($results - $grawdata[5] > 0) {
                             $aggregatedPercentage = ($grawdata[0] + $grawdata[1]) / ($results - $grawdata[5]) * 100;
                         } else {
                             $aggregatedPercentage = 0;
                         }
                         break;
                     case 3:
                         $aggregatedPercentage = $percentage;
                         break;
                     case 5:
                         if ($results - $grawdata[5] > 0) {
                             $aggregatedPercentage = ($grawdata[3] + $grawdata[4]) / ($results - $grawdata[5]) * 100;
                         } else {
                             $aggregatedPercentage = 0;
                         }
                         break;
                     case 6:
                     case 7:
                         if ($results - $grawdata[5] > 0) {
                             $percentage = $grawdata[$i] / $results * 100;
                             // All results
                         } else {
                             $percentage = 0;
                         }
                     default:
                         $aggregatedPercentage = 'na';
                         break;
                 }
                 switch ($outputType) {
                     case 'xls':
                         $label[$i] = flattenText($label[$i]);
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, $label[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 1, $grawdata[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 2, $percentage / 100, $this->xlsPercents);
                         if ($aggregatedPercentage !== 'na') {
                             $this->sheet->writeNumber($this->xlsRow, 3, $aggregatedPercentage / 100, $this->xlsPercents);
                         }
                         break;
                     case 'pdf':
                         $label[$i] = flattenText($label[$i]);
                         if ($aggregatedPercentage !== 'na') {
                             $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", sprintf("%01.2f", $aggregatedPercentage) . "%");
                         } else {
                             $tablePDF[] = array($label[$i], $grawdata[$i], sprintf("%01.2f", $percentage) . "%", "");
                         }
                         break;
                     case 'html':
                         //output percentage
                         $statisticsoutput .= "\t\t<td align='center' >";
                         $statisticsoutput .= sprintf("%01.2f", $percentage) . "%</td>";
                         $statisticsoutput .= "\t\t<td align='center' >";
                         if ($aggregatedPercentage !== 'na') {
                             $statisticsoutput .= sprintf("%01.2f", $aggregatedPercentage) . "%";
                         } else {
                             $statisticsoutput .= '&nbsp;';
                         }
                         $statisticsoutput .= "</td>\t\t";
                         break;
                     default:
                         break;
                 }
                 if ($itemcounter == 5) {
                     // create new row "sum"
                     //calculate sum of items 1-5
                     $sumitems = $grawdata[0] + $grawdata[1] + $grawdata[2] + $grawdata[3] + $grawdata[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(gT("Sum") . " (" . gT("Answers") . ")", $sumitems, $sumpercentage . "%", $sumpercentage . "%");
                             $footXLS[] = array(gT("Number of cases"), $TotalCompleted, $casepercentage . "%", "");
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Sum") . " (" . gT("Answers") . ")");
                             $this->sheet->writeNumber($this->xlsRow, 1, $sumitems);
                             $this->sheet->writeNumber($this->xlsRow, 2, $sumpercentage / 100, $this->xlsPercents);
                             $this->sheet->writeNumber($this->xlsRow, 3, $sumpercentage / 100, $this->xlsPercents);
                             $this->xlsRow++;
                             $this->sheet->write($this->xlsRow, 0, gT("Number of cases"));
                             $this->sheet->writeNumber($this->xlsRow, 1, $TotalCompleted);
                             $this->sheet->writeNumber($this->xlsRow, 2, $casepercentage / 100, $this->xlsPercents);
                             break;
                         case 'pdf':
                             $footPDF[] = array(gT("Sum") . " (" . gT("Answers") . ")", $sumitems, $sumpercentage . "%", $sumpercentage . "%");
                             $footPDF[] = array(gT("Number of cases"), $TotalCompleted, $casepercentage . "%", "");
                             break;
                         case 'html':
                             $statisticsoutput .= "\t\t&nbsp;\n\t</tr>\n";
                             $statisticsoutput .= "<tr><td align='center'><strong>" . gT("Sum") . " (" . 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&nbsp;\n\t</tr>\n";
                             $statisticsoutput .= "<tr><td align='center'>" . 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' >&nbsp;</td></tr>";
                             break;
                         default:
                             break;
                     }
                 }
             } else {
                 switch ($outputType) {
                     case 'xls':
                         $label[$i] = flattenText($label[$i]);
                         $this->xlsRow++;
                         $this->sheet->write($this->xlsRow, 0, $label[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 1, $grawdata[$i]);
                         $this->sheet->writeNumber($this->xlsRow, 2, $gdata[$i] / 100, $this->xlsPercents);
                         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&nbsp;</td>\n\t</tr>\n";
                         if (isset($extraline)) {
                             $statisticsoutput .= $extraline;
                         }
                         break;
                     default:
                         break;
                 }
             }
         }
         //end else -> $gdata[$i] != "N/A"
         //increase counter
         $i++;
         $itemcounter++;
         //Clear extraline
         unset($extraline);
     }
     //end while
     //only show additional values when this setting is enabled
     if (Yii::app()->getConfig('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 ($outputs['qtype'] == "5" || $outputs['qtype'] == "A") {
             $stddev = 0;
             $stddevarray = array_slice($grawdata, 0, 5, true);
             $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':
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, gT("Arithmetic mean"));
                     $this->sheet->writeNumber($this->xlsRow, 1, $am);
                     $this->xlsRow++;
                     $this->sheet->write($this->xlsRow, 0, gT("Standard deviation"));
                     $this->sheet->writeNumber($this->xlsRow, 1, $stddev);
                     break;
                 case 'pdf':
                     $tablePDF[] = array(gT("Arithmetic mean"), $am, '', '');
                     $tablePDF[] = array(gT("Standard deviation"), $stddev, '', '');
                     break;
                 case 'html':
                     //calculate standard deviation
                     $statisticsoutput .= "<tr><td align='center'>" . gT("Arithmetic mean") . "</td>";
                     //German: "Fallzahl"
                     $statisticsoutput .= "<td>&nbsp;</td><td align='center'> {$am}</td><td>&nbsp;</td></tr>";
                     $statisticsoutput .= "<tr><td align='center'>" . gT("Standard deviation") . "</td>";
                     //German: "Fallzahl"
                     $statisticsoutput .= "<td>&nbsp;</td><td align='center'>{$stddev}</td><td>&nbsp;</td></tr>";
                     break;
                 default:
                     break;
             }
         }
     }
     if ($outputType == 'pdf') {
         //$tablePDF = array();
         $tablePDF = array_merge_recursive($tablePDF, $footPDF);
         $this->pdf->headTable($headPDF, $tablePDF);
         //$this->pdf->tableintopdf($tablePDF);
         //                if(isset($footPDF))
         //                foreach($footPDF as $foot)
         //                {
         //                    $footA = array($foot);
         //                    $this->pdf->tablehead($footA);
         //                }
         if (isset($headPDF2)) {
             $this->pdf->headTable($headPDF2, $tablePDF2);
         }
     }
     if ($outputType == 'xls' && (isset($headXLS) || isset($tableXLS))) {
         if (isset($headXLS)) {
             $this->xlsRow++;
             $this->xlsRow++;
             foreach ($headXLS as $aRow) {
                 $this->xlsRow++;
                 $iColumn = 0;
                 foreach ($aRow as $sValue) {
                     $this->sheet->write($this->xlsRow, $iColumn, $sValue, $this->formatBold);
                     $iColumn++;
                 }
             }
         }
         if (isset($tableXLS)) {
             foreach ($tableXLS as $aRow) {
                 $this->xlsRow++;
                 $iColumn = 0;
                 foreach ($aRow as $sValue) {
                     $this->sheet->write($this->xlsRow, $iColumn, $sValue);
                     $iColumn++;
                 }
             }
         }
     }
     if ($outputType == 'html') {
         $statisticsoutput .= "<tr><td colspan='4' style=\"text-align:center\" id='statzone_{$rt}'>";
     }
     //-------------------------- PCHART OUTPUT ----------------------------
     list($qsid, $qgid, $qqid) = explode("X", $rt, 3);
     $qsid = $surveyid;
     $aattr = getQuestionAttributeValues($outputs['parentqid'], substr($rt, 0, 1));
     //PCHART has to be enabled and we need some data
     if ($usegraph == 1) {
         $bShowGraph = $aattr["statistics_showgraph"] == "1";
         $bAllowPieChart = $outputs['qtype'] != "M" && $outputs['qtype'] != "P";
         $bAllowMap = isset($aattr["location_mapservice"]) && $aattr["location_mapservice"] == "1";
         $bShowMap = $bAllowMap && $aattr["statistics_showmap"] == "1";
         $bShowPieChart = $bAllowPieChart && (isset($aattr["statistics_graphtype"]) && $aattr["statistics_graphtype"] == "1");
         $astatdata[$rt] = array('id' => $rt, 'sg' => $bShowGraph, 'ap' => $bAllowPieChart, 'am' => $bAllowMap, 'sm' => $bShowMap, 'sp' => $bShowPieChart);
         $stats = Yii::app()->session['stats'];
         $stats[$rt] = array('lbl' => $lbl, 'gdata' => $gdata, 'grawdata' => $grawdata);
         Yii::app()->session['stats'] = $stats;
         if ($bShowGraph == true) {
             $cachefilename = createChart($qqid, $qsid, $bShowPieChart, $lbl, $gdata, $grawdata, $MyCache, $sLanguage, $outputs['qtype']);
             if ($cachefilename) {
                 //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':
                         $this->pdf->AddPage('P', 'A4');
                         $this->pdf->titleintopdf($pdfTitle, $titleDesc);
                         $this->pdf->Image($tempdir . "/" . $cachefilename, 0, 70, 180, 0, '', Yii::app()->getController()->createUrl("admin/survey/sa/view/surveyid/" . $surveyid), 'B', true, 150, 'C', false, false, 0, true);
                         break;
                     case 'html':
                         //// This QD code generate the chart.js.
                         //// It's mixing PHP, JS and painfull from hell.
                         //// for more details, read : http://goo.gl/ylbikt
                         //// TODO : this is a rest of the first cycle of dev
                         //// Should be possible to use only one canvas now...
                         $pie_visibility = $radar_visibility = $line_visibility = $polar__visibility = $doughnut_visibility = $bar_visibility = 'hidden';
                         if (isset($aattr["statistics_graphtype"])) {
                             $req_chart_type = $aattr["statistics_graphtype"];
                         }
                         //// If user forced the chartype from statistics_view
                         if ($_POST['charttype'] != 'default') {
                             $req_chart_type = $_POST['charttype'];
                         }
                         //// The value of the select box in the question advanced setting is numerical. So we need to translate it.
                         if (isset($req_chart_type)) {
                             switch ($req_chart_type) {
                                 case '1':
                                     $charttype = "Pie";
                                     $pie_visibility = ' active ';
                                     break;
                                 case '2':
                                     $charttype = "Radar";
                                     $radar_visibility = ' active ';
                                     break;
                                 case '3':
                                     $charttype = "Line";
                                     $line_visibility = ' active ';
                                     break;
                                 case '4':
                                     $charttype = "PolarArea";
                                     $polar__visibility = ' active ';
                                     break;
                                 case '5':
                                     $charttype = "Doughnut";
                                     $doughnut_visibility = ' active ';
                                     break;
                                 default:
                                     $charttype = "Bar";
                                     $bar_visibility = ' active ';
                                     break;
                             }
                         }
                         //// Here the 72 colors of the original limesurvey palette.
                         //// This could be change by some user palette coming from database.
                         $COLORS_FOR_SURVEY = array('20,130,200', '232,95,51', '34,205,33', '210,211,28', '134,179,129', '201,171,131', '251,231,221', '23,169,161', '167,187,213', '211,151,213', '147,145,246', '147,39,90', '250,250,201', '201,250,250', '94,0,94', '250,125,127', '0,96,201', '201,202,250', '0,0,127', '250,0,250', '250,250,0', '0,250,250', '127,0,127', '127,0,0', '0,125,127', '0,0,250', '0,202,250', '201,250,250', '201,250,201', '250,250,151', '151,202,250', '251,149,201', '201,149,250', '250,202,151', '45,96,250', '45,202,201', '151,202,0', '250,202,0', '250,149,0', '250,96,0', '184,230,115', '102,128,64', '220,230,207', '134,191,48', '184,92,161', '128,64,112', '230,207,224', '191,48,155', '230,138,115', '128,77,64', '230,211,207', '191,77,48', '80,161,126', '64,128,100', '207,230,220', '48,191,130', '25,25,179', '18,18,125', '200,200,255', '145,145,255', '255,178,0', '179,125,0', '255,236,191', '255,217,128', '255,255,0', '179,179,0', '255,255,191', '255,255,128', '102,0,153', '71,0,107', '234,191,255', '213,128,255');
                         //// $lbl is generated somewhere upthere by the original code. We translate it for chartjs.
                         $labels = array();
                         foreach ($lbl as $name => $lb) {
                             $labels[] = $name;
                         }
                         //// As said before, one canva should be enough now. Just need to modify the init_chart functions, and to remove the visibility logic.
                         $statisticsoutput .= '<div class="col-sm-12">
                                                 <div class="col-sm-10 vcenter" id="chartjs-container-' . $qqid . '">
                                                     <canvas class="canvas-chart ' . $bar_visibility . '" id="chartjs-Bar-' . $qqid . '" width="400" height="150"></canvas>
                                                     <canvas class="canvas-chart ' . $pie_visibility . '" id="chartjs-Pie-' . $qqid . '" width="400" height="150"></canvas>
                                                     <canvas class="canvas-chart ' . $radar_visibility . '" id="chartjs-Radar-' . $qqid . '" width="400" height="150"></canvas>
                                                     <canvas class="canvas-chart ' . $line_visibility . '" id="chartjs-Line-' . $qqid . '" width="400" height="150"></canvas>
                                                     <canvas class="canvas-chart ' . $polar__visibility . '" id="chartjs-PolarArea-' . $qqid . '" width="400" height="150"></canvas>
                                                     <canvas class="canvas-chart ' . $doughnut_visibility . '" id="chartjs-Doughnut-' . $qqid . '" width="400" height="150"></canvas>
                                                 </div>';
                         $statisticsoutput .= $this->get_chartjs_legend($labels, $COLORS_FOR_SURVEY);
                         ////TODO : animate on scroll
                         //// Here, we directly insert a <script> generating the chart for $qqid. Of course, this chart is generated on page load.
                         //// So, it could be hard for navigator if hundreds of charts are loaded... A lazy load, with nice animation on scroll will be needed
                         //// See : http://stackoverflow.com/questions/18772547/how-to-make-the-chart-js-animate-when-scrolled-to-that-section
                         $statisticsoutput .= $this->init_chart_js_graph($charttype, $labels, $qqid, $grawdata, $COLORS_FOR_SURVEY, false);
                         //// This is from the old code. Don't know if still used.
                         $aattr = getQuestionAttributeValues($qqid, $firstletter);
                         if ($bShowMap) {
                             $statisticsoutput .= "<div id=\"statisticsmap_{$rt}\" class=\"statisticsmap\"></div>";
                             $agmapdata[$rt] = array("coord" => getQuestionMapData(substr($rt, 1), $qsid), "zoom" => $aattr['location_mapzoom'], "width" => $aattr['location_mapwidth'], "height" => $aattr['location_mapheight']);
                         }
                         break;
                     default:
                         break;
                 }
             }
         }
     }
     //close table/output
     if ($outputType == 'html') {
         // show this block only when we show graphs and are not in the public statics controller
         // this is because the links don't work from that controller
         if ($usegraph == 1 && get_class(Yii::app()->getController()) !== 'Statistics_userController') {
             $sImgUrl = Yii::app()->getConfig('adminimageurl');
             $statisticsoutput .= "</td></tr><tr><td colspan='4'>";
             //// The buttons to switch the graph type
             $statisticsoutput .= '<div class="chartjs-buttons" style=\\"text-align:center\\">';
             //// Bar chart
             $statisticsoutput .= '    <button type="button" id="button-chartjs-Bar-' . $qqid . '" class="btn btn-default chart-type-control" data-canva-id="chartjs-Bar-' . $qqid . '" aria-label="Left Align">
                                         <i class="fa fa-bar-chart"></i>
                                         ' . gT('Bar chart') . '
                                      </button>';
             //// Pie chart
             $statisticsoutput .= '    <button type="button" id="button-chartjs-Pie-' . $qqid . '" class="btn btn-default chart-type-control" data-canva-id="chartjs-Pie-' . $qqid . '" aria-label="Left Align">
                                         <i class="fa fa-pie-chart"></i>
                                         ' . gT('Pie chart') . '
                                      </button>';
             //// Radar chart
             $statisticsoutput .= '    <button type="button" id="button-chartjs-Radar-' . $qqid . '" class="btn btn-default chart-type-control" data-canva-id="chartjs-Radar-' . $qqid . '" aria-label="Left Align">
                                         <i class="fa fa-crosshairs"></i>
                                         ' . gT('Radar chart') . '
                                      </button>';
             //// Line chart
             $statisticsoutput .= '    <button type="button" id="button-chartjs-Line-' . $qqid . '" class="btn btn-default chart-type-control" data-canva-id="chartjs-Line-' . $qqid . '" aria-label="Left Align">
                                         <i class="fa fa-line-chart"></i>
                                         ' . gT('Line chart') . '
                                      </button>';
             //// Polar chart
             $statisticsoutput .= '    <button type="button" id="button-chartjs-PolarArea-' . $qqid . '" class="btn btn-default chart-type-control" data-canva-id="chartjs-PolarArea-' . $qqid . '" aria-label="Left Align">
                                         <i class="fa fa-sun-o"></i>
                                         ' . gT('Polar chart') . '
                                      </button>';
             //// Doughnut chart
             $statisticsoutput .= '    <button type="button" id="button-chartjs-Doughnut-' . $qqid . '" class="btn btn-default chart-type-control" data-canva-id="chartjs-Doughnut-' . $qqid . '" aria-label="Left Align">
                                         <i class="fa fa fa-circle-o"></i>
                                         ' . gT('Doughnut chart') . '
                                      </button>';
             //// Here, we directly insert the script to handle each button.
             //// Sure, we could have use statistic.js, to get the click on chart-type-control, etc etc : but we did it the fast way
             //// TODO : refactore that on a jQuery plugin, more general.
             $statisticsoutput .= '<script>/*<![CDATA[*/';
             $statisticsoutput .= '$(document).ready(function(){';
             //// each button will have its own 'onclick' event, wich generate a new chartjs object
             //// the hidden and active class togle should be replaced by a single canva being cleared.
             foreach (array('Bar', 'Radar', 'Line', 'Doughnut', 'PolarArea', 'Pie') as $ctype) {
                 $statisticsoutput .= ' $("#button-chartjs-' . $ctype . '-' . $qqid . '").click(function(){
                        $("#chartjs-container-' . $qqid . ' .active").addClass("hidden").removeClass("active");
                        $("#chartjs-' . $ctype . '-' . $qqid . '").removeClass("hidden");
                        $("#chartjs-' . $ctype . '-' . $qqid . '").addClass("active");
                        $("#chartjs-' . $ctype . '-' . $qqid . '").width("100%");
                        $("#chartjs-' . $ctype . '-' . $qqid . '").height("441px");';
                 //// We call the PHP function wich will build the javascript wich will build the js object.
                 //// for details, see : http://goo.gl/JtnOsZ
                 $statisticsoutput .= $this->init_chart_js_graph($ctype, $labels, $qqid, $grawdata, $COLORS_FOR_SURVEY, true);
                 $statisticsoutput .= '});';
             }
             $statisticsoutput .= '})';
             $statisticsoutput .= ' /*]]>*/ </script></div>';
             $statisticsoutput .= "<div id='stats_{$rt}' class='graphdisplay' style=\"text-align:center\">";
             $statisticsoutput .= "</div></td></tr>";
             /*
                             $statisticsoutput .= "</td></tr><tr><td colspan='4'><div id='stats_$rt' class='graphdisplay' style=\"text-align:center\">"
                             ."<img class='stats-hidegraph' src='$sImgUrl/chart_disabled.png' title='". gT("Disable chart") ."' />"
                             ."<img class='stats-showgraph' src='$sImgUrl/chart.png' title='". gT("Enable chart") ."' />"
                             ."<img class='stats-showbar' src='$sImgUrl/chart_bar.png' title='". gT("Display as bar chart") ."' />"
                             ."<img class='stats-showpie' src='$sImgUrl/chart_pie.png' title='". gT("Display as pie chart") ."' />"
                             ."<img class='stats-showmap' src='$sImgUrl/map_disabled.png' title='". gT("Disable map display") ."' />"
                             ."<img class='stats-hidemap' src='$sImgUrl/map.png' title='". gT("Enable map display") ."' />"
                             ."</div></td></tr>";
             */
         }
         $statisticsoutput .= "</td></tr></table><br /> \n";
     }
     return array("statisticsoutput" => $statisticsoutput, "pdf" => $this->pdf, "astatdata" => $astatdata);
 }