Esempio n. 1
1
 /**
  * View a single response in detail
  *
  * @param mixed $iSurveyID
  * @param mixed $iId
  * @param mixed $sBrowseLang
  */
 public function view($iSurveyID, $iId, $sBrowseLang = '')
 {
     if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
         $aData = $this->_getData(array('iId' => $iId, 'iSurveyId' => $iSurveyID, 'browselang' => $sBrowseLang));
         $sBrowseLanguage = $aData['language'];
         extract($aData);
         $aViewUrls = array();
         $fieldmap = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
         $bHaveToken = $aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID);
         // Boolean : show (or not) the token
         if (!Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
             unset($fieldmap['token']);
             $bHaveToken = false;
         }
         //add token to top of list if survey is not private
         if ($bHaveToken) {
             $fnames[] = array("token", gT("Token ID"), 'code' => 'token');
             $fnames[] = array("firstname", gT("First name"), 'code' => 'firstname');
             // or token:firstname ?
             $fnames[] = array("lastname", gT("Last name"), 'code' => 'lastname');
             $fnames[] = array("email", gT("Email"), 'code' => 'email');
         }
         $fnames[] = array("submitdate", gT("Submission date"), gT("Completed"), "0", 'D', 'code' => 'submitdate');
         $fnames[] = array("completed", gT("Completed"), "0");
         foreach ($fieldmap as $field) {
             if ($field['fieldname'] == 'lastpage' || $field['fieldname'] == 'submitdate') {
                 continue;
             }
             if ($field['type'] == 'interview_time') {
                 continue;
             }
             if ($field['type'] == 'page_time') {
                 continue;
             }
             if ($field['type'] == 'answer_time') {
                 continue;
             }
             //$question = $field['question'];
             $question = viewHelper::getFieldText($field);
             if ($field['type'] != "|") {
                 $fnames[] = array($field['fieldname'], viewHelper::getFieldText($field), 'code' => viewHelper::getFieldCode($field, array('LEMcompat' => true)));
             } elseif ($field['aid'] !== 'filecount') {
                 $qidattributes = getQuestionAttributeValues($field['qid']);
                 for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++) {
                     $filenum = sprintf(gT("File %s"), $i + 1);
                     if ($qidattributes['show_title'] == 1) {
                         $fnames[] = array($field['fieldname'], "{$filenum} - {$question} (" . gT('Title') . ")", 'code' => viewHelper::getFieldCode($field) . '(title)', "type" => "|", "metadata" => "title", "index" => $i);
                     }
                     if ($qidattributes['show_comment'] == 1) {
                         $fnames[] = array($field['fieldname'], "{$filenum} - {$question} (" . gT('Comment') . ")", 'code' => viewHelper::getFieldCode($field) . '(comment)', "type" => "|", "metadata" => "comment", "index" => $i);
                     }
                     $fnames[] = array($field['fieldname'], "{$filenum} - {$question} (" . gT('File name') . ")", 'code' => viewHelper::getFieldCode($field) . '(name)', "type" => "|", "metadata" => "name", "index" => $i);
                     $fnames[] = array($field['fieldname'], "{$filenum} - {$question} (" . gT('File size') . ")", 'code' => viewHelper::getFieldCode($field) . '(size)', "type" => "|", "metadata" => "size", "index" => $i);
                     //$fnames[] = array($field['fieldname'], "File ".($i+1)." - ".$field['question']." (extension)", "type"=>"|", "metadata"=>"ext",     "index"=>$i);
                 }
             } else {
                 $fnames[] = array($field['fieldname'], gT("File count"));
             }
         }
         $nfncount = count($fnames) - 1;
         if ($iId < 1) {
             $iId = 1;
         }
         $exist = SurveyDynamic::model($iSurveyID)->exist($iId);
         $next = SurveyDynamic::model($iSurveyID)->next($iId, true);
         $previous = SurveyDynamic::model($iSurveyID)->previous($iId, true);
         $aData['exist'] = $exist;
         $aData['next'] = $next;
         $aData['previous'] = $previous;
         $aData['id'] = $iId;
         $aViewUrls[] = 'browseidheader_view';
         if ($exist) {
             $oPurifier = new CHtmlPurifier();
             //SHOW INDIVIDUAL RECORD
             $oCriteria = new CDbCriteria();
             if ($bHaveToken) {
                 $oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
             }
             $oCriteria->addCondition("id = {$iId}");
             $iIdresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
             foreach ($iIdresult as $iIdrow) {
                 $iId = $iIdrow['id'];
                 $rlanguage = $iIdrow['startlanguage'];
             }
             $aData['bHasFile'] = false;
             if (isset($rlanguage)) {
                 $aData['rlanguage'] = $rlanguage;
             }
             foreach ($iIdresult as $iIdrow) {
                 $highlight = false;
                 for ($i = 0; $i < $nfncount + 1; $i++) {
                     if ($fnames[$i][0] != 'completed' && is_null($iIdrow[$fnames[$i][0]])) {
                         continue;
                         // irrelevant, so don't show
                     }
                     $inserthighlight = '';
                     if ($highlight) {
                         $inserthighlight = "class='highlight'";
                     }
                     if ($fnames[$i][0] == 'completed') {
                         if ($iIdrow['submitdate'] == NULL || $iIdrow['submitdate'] == "N") {
                             $answervalue = "N";
                         } else {
                             $answervalue = "Y";
                         }
                     } else {
                         if (isset($fnames[$i]['type']) && $fnames[$i]['type'] == "|") {
                             $index = $fnames[$i]['index'];
                             $metadata = $fnames[$i]['metadata'];
                             $phparray = json_decode_ls($iIdrow[$fnames[$i][0]]);
                             if (isset($phparray[$index])) {
                                 switch ($metadata) {
                                     case "size":
                                         $answervalue = sprintf(gT("%s KB"), intval($phparray[$index][$metadata]));
                                         break;
                                     case "name":
                                         $answervalue = CHtml::link($oPurifier->purify(rawurldecode($phparray[$index][$metadata])), $this->getController()->createUrl("/admin/responses", array("sa" => "actionDownloadfile", "surveyid" => $surveyid, "iResponseId" => $iId, "sFileName" => $phparray[$index][$metadata])));
                                         break;
                                     default:
                                         $answervalue = htmlspecialchars(strip_tags(stripJavaScript($phparray[$index][$metadata])));
                                 }
                                 $aData['bHasFile'] = true;
                             } else {
                                 $answervalue = "";
                             }
                         } else {
                             $answervalue = htmlspecialchars(strip_tags(stripJavaScript(getExtendedAnswer($iSurveyID, $fnames[$i][0], $iIdrow[$fnames[$i][0]], $sBrowseLanguage))), ENT_QUOTES);
                         }
                     }
                     $aData['answervalue'] = $answervalue;
                     $aData['inserthighlight'] = $inserthighlight;
                     $aData['fnames'] = $fnames;
                     $aData['i'] = $i;
                     $aViewUrls['browseidrow_view'][] = $aData;
                 }
             }
         } else {
             Yii::app()->session['flashmessage'] = gT("This response ID is invalid.");
         }
         $aViewUrls[] = 'browseidfooter_view';
         $aData['sidemenu']['state'] = false;
         $aData['menu']['edition'] = true;
         $aData['menu']['view'] = true;
         $aData['menu']['close'] = true;
         // This resets the url on the close button to go to the upper view
         $aData['menu']['closeurl'] = $this->getController()->createUrl("admin/responses/sa/browse/surveyid/" . $iSurveyId);
         $this->_renderWrappedTemplate('', $aViewUrls, $aData);
     } else {
         $aData = array();
         $aData['surveyid'] = $iSurveyID;
         $message = array();
         $message['title'] = gT('Access denied!');
         $message['message'] = gT('You do not have permission to access this page.');
         $message['class'] = "error";
         $this->_renderWrappedTemplate('survey', array("message" => $message), $aData);
     }
 }
 /**
  * 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);
 }
Esempio n. 3
0
function do_array_dual($ia)
{
    global $thissurvey;
    $aLastMoveResult = LimeExpressionManager::GetLastMoveResult();
    $aMandatoryViolationSubQ = $aLastMoveResult['mandViolation'] && $ia[6] == 'Y' ? explode("|", $aLastMoveResult['unansweredSQs']) : array();
    $repeatheadings = Yii::app()->getConfig("repeatheadings");
    $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings");
    $extraclass = "";
    $answertypeclass = "";
    // Maybe not
    $caption = "";
    // Just leave empty, are replaced after
    $inputnames = array();
    $labelans1 = array();
    $labelans = array();
    $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
    if ($aQuestionAttributes['random_order'] == 1) {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom();
    } else {
        $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY question_order";
    }
    $ansresult = dbExecuteAssoc($ansquery);
    //Checked
    $aSubQuestions = $ansresult->readAll();
    $anscount = count($aSubQuestions);
    $lquery = "SELECT * FROM {{answers}} WHERE scale_id=0 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code";
    $lresult = dbExecuteAssoc($lquery);
    //Checked
    $aAnswersScale0 = $lresult->readAll();
    $lquery1 = "SELECT * FROM {{answers}} WHERE scale_id=1 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code";
    $lresult1 = dbExecuteAssoc($lquery1);
    //Checked
    $aAnswersScale1 = $lresult1->readAll();
    if ($aQuestionAttributes['use_dropdown'] == 1) {
        $useDropdownLayout = true;
        $extraclass .= " dropdown-list";
        $answertypeclass .= " dropdown";
        $doDualScaleFunction = "doDualScaleDropDown";
        // javascript funtion to lauch at end of answers
        $caption = gT("An array with sub-question on each line, with 2 answers to provide on each line. You have to select the answer.");
    } else {
        $useDropdownLayout = false;
        $extraclass .= " radio-list";
        $answertypeclass .= " radio";
        $doDualScaleFunction = "doDualScaleRadio";
        $caption = gT("An array with sub-question on each line, with 2 answers to provide on each line. The answers are contained in the table header. ");
    }
    if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) {
        $repeatheadings = intval($aQuestionAttributes['repeat_headings']);
        $minrepeatheadings = 0;
    }
    if (trim($aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $leftheader = $aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
    } else {
        $leftheader = '';
    }
    if (trim($aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $rightheader = $aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
    } else {
        $rightheader = '';
    }
    if (trim($aQuestionAttributes['answer_width']) != '') {
        $answerwidth = $aQuestionAttributes['answer_width'];
    } else {
        $answerwidth = 20;
    }
    // Find if we have rigth and center text
    // TODO move "|" to attribute
    $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%'";
    $rigthCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
    $rightexists = $rigthCount > 0;
    // $right_exists: flag to find out if there are any right hand answer parts. leaving right column but don't force with
    $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%|%'";
    $centerCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
    $centerexists = $centerCount > 0;
    // $center_exists: flag to find out if there are any center hand answer parts. leaving center column but don't force with
    // Label and code for input
    foreach ($aAnswersScale0 as $lrow) {
        $labels0[] = array('code' => $lrow['code'], 'title' => $lrow['answer']);
    }
    foreach ($aAnswersScale1 as $lrow) {
        $labels1[] = array('code' => $lrow['code'], 'title' => $lrow['answer']);
    }
    if (count($aAnswersScale0) > 0 && $anscount) {
        $answer = "";
        $fn = 1;
        // Used by repeat_heading
        if ($useDropdownLayout === false) {
            $columnswidth = 100 - $answerwidth;
            foreach ($aAnswersScale0 as $lrow) {
                $labelans0[] = $lrow['answer'];
                $labelcode0[] = $lrow['code'];
            }
            foreach ($aAnswersScale1 as $lrow) {
                $labelans1[] = $lrow['answer'];
                $labelcode1[] = $lrow['code'];
            }
            $numrows = count($labelans0) + count($labelans1);
            // Add needed row and fill some boolean: shownoanswer, rightexists, centerexists
            $shownoanswer = $ia[6] != "Y" && SHOW_NO_ANSWER == 1;
            if ($shownoanswer) {
                $numrows++;
                $caption .= gT("The last cell are for no answer. ");
            }
            if ($rightexists) {
                $numrows++;
            }
            if ($centerexists) {
                $numrows++;
            }
            $cellwidth = $columnswidth / $numrows;
            //$cellwidth=sprintf("%02d", $cellwidth); // No reason to do this, except to leave place for separator ?  But then table can not be the same in all browser
            // Header row and colgroups
            $mycolumns = "\t<col class=\"col-answers\" width=\"{$answerwidth}%\" />\n";
            $answer_head_line = "\t<th class=\"header_answer_text\">&nbsp;</th>\n\n";
            $mycolumns .= "\t<colgroup class=\"col-responses group-1\">\n";
            $odd_even = '';
            foreach ($labelans0 as $ld) {
                $answer_head_line .= "\t<th>" . $ld . "</th>\n";
                $odd_even = alternation($odd_even);
                $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n";
            }
            $mycolumns .= "\t</colgroup>\n";
            if (count($labelans1) > 0) {
                $separatorwidth = $centerexists ? "width=\"{$cellwidth}%\" " : "";
                $mycolumns .= "\t<col class=\"separator\" {$separatorwidth}/>\n";
                $mycolumns .= "\t<colgroup class=\"col-responses group-2\">\n";
                $answer_head_line .= "\n\t<td class=\"header_separator\">&nbsp;</td>\n\n";
                // Separator : and No answer for accessibility for first colgroup
                foreach ($labelans1 as $ld) {
                    $answer_head_line .= "\t<th>" . $ld . "</th>\n";
                    $odd_even = alternation($odd_even);
                    $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n";
                }
                $mycolumns .= "\t</colgroup>\n";
            }
            if ($shownoanswer || $rightexists) {
                $rigthwidth = $rightexists ? "width=\"{$cellwidth}%\" " : "";
                $mycolumns .= "\t<col class=\"separator rigth_separator\" {$rigthwidth}/>\n";
                $answer_head_line .= "\n\t<td class=\"header_separator rigth_separator\">&nbsp;</td>\n";
            }
            if ($shownoanswer) {
                $mycolumns .= "\t<col class=\"col-no-answer\"  width=\"{$cellwidth}%\" />\n";
                $answer_head_line .= "\n\t<th class=\"header_no_answer\">" . gT('No answer') . "</th>\n";
            }
            $answer_head2 = "\n<tr class=\"array1 header_row dontread\">\n" . $answer_head_line . "</tr>\n";
            // build first row of header if needed
            if ($leftheader != '' || $rightheader != '') {
                $answer_head1 = "<tr class=\"array1 groups header_row\">\n" . "\t<th class=\"header_answer_text\">&nbsp;</th>\n" . "\t<th colspan=\"" . count($labelans0) . "\" class=\"dsheader\">{$leftheader}</th>\n";
                if (count($labelans1) > 0) {
                    $answer_head1 .= "\t<td class=\"header_separator\">&nbsp;</td>\n" . "\t<th colspan=\"" . count($labelans1) . "\" class=\"dsheader\">{$rightheader}</th>\n";
                }
                if ($shownoanswer || $rightexists) {
                    $rigthclass = $rightexists ? " header_answer_text_right" : "";
                    $answer_head1 .= "\t<td class=\"header_separator {$rigthclass}\">&nbsp;</td>\n";
                    if ($shownoanswer) {
                        $answer_head1 .= "\t<th class=\"header_no_answer\">&nbsp;</th>\n";
                    }
                }
                $answer_head1 .= "</tr>\n";
            } else {
                $answer_head1 = "";
            }
            $answer .= "\n<table class=\"question subquestions-list questions-list\" summary=\"{$caption}\">\n" . $mycolumns . "\n\t<thead>\n" . $answer_head1 . $answer_head2 . "\n\t</thead>\n" . "<tbody>\n";
            // And no each line of body
            $trbc = '';
            foreach ($aSubQuestions as $ansrow) {
                // Build repeat headings if needed
                if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) {
                    if ($anscount - $fn + 1 >= $minrepeatheadings) {
                        $answer .= "</tbody>\n<tbody>";
                        // Close actual body and open another one
                        //$answer .= $answer_head1;
                        $answer .= "\n<tr class=\"repeat headings\">\n" . $answer_head_line . "</tr>\n";
                    }
                }
                $trbc = alternation($trbc, 'row');
                $answertext = $ansrow['question'];
                // rigth and center answertext: not explode for ? Why not
                if (strpos($answertext, '|')) {
                    $answertextrigth = substr($answertext, strpos($answertext, '|') + 1);
                    $answertext = substr($answertext, 0, strpos($answertext, '|'));
                } else {
                    $answertextrigth = "";
                }
                if ($centerexists) {
                    $answertextcenter = substr($answertextrigth, 0, strpos($answertextrigth, '|'));
                    $answertextrigth = substr($answertextrigth, strpos($answertextrigth, '|') + 1);
                } else {
                    $answertextcenter = "";
                }
                $myfname = $ia[1] . $ansrow['title'];
                $myfname0 = $ia[1] . $ansrow['title'] . '#0';
                $myfid0 = $ia[1] . $ansrow['title'] . '_0';
                $myfname1 = $ia[1] . $ansrow['title'] . '#1';
                // new multi-scale-answer
                $myfid1 = $ia[1] . $ansrow['title'] . '_1';
                /* Check the Sub Q mandatory violation */
                if ($ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ))) {
                    $answertext = "<span class='errormandatory'>{$answertext}</span>";
                }
                // Get array_filter stuff
                list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} answers-list radio-list");
                $answer .= $htmltbody2;
                array_push($inputnames, $myfname0);
                $answer .= "\t<th class=\"answertext\">\n" . $hiddenfield . "{$answertext}\n";
                // Hidden answers used by EM: sure can be added in javascript
                $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid0}\" id=\"java{$myfid0}\" value=\"";
                if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0])) {
                    $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0];
                }
                $answer .= "\" />\n";
                if (count($labelans1) > 0) {
                    $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid1}\" id=\"java{$myfid1}\" value=\"";
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1])) {
                        $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1];
                    }
                    $answer .= "\" />\n";
                }
                $answer .= "\t</th>\n";
                $hiddenanswers = '';
                $thiskey = 0;
                foreach ($labelcode0 as $ld) {
                    $answer .= "\t<td class=\"answer_cell_1_00{$ld} answer-item {$answertypeclass}-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname0}\" value=\"{$ld}\" id=\"answer{$myfid0}-{$ld}\" ";
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == $ld) {
                        $answer .= CHECKED;
                    }
                    $answer .= "  />\n" . "<label class=\"hide read\" for=\"answer{$myfid0}-{$ld}\">{$labelans0[$thiskey]}</label>\n" . "\n\t</td>\n";
                    $thiskey++;
                }
                if (count($labelans1) > 0) {
                    $answer .= "\t<td class=\"dual_scale_separator information-item\">";
                    if ($shownoanswer) {
                        $answer .= "\t<input class='radio jshide read' type='radio' name='{$myfname0}' value='' id='answer{$myfid0}-' ";
                        if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") {
                            $answer .= CHECKED;
                        }
                        $answer .= " />\n";
                    }
                    $answer .= "<label for='answer{$myfid0}-' class= \"hide read\">" . gT("No answer") . "</label>";
                    $answer .= "\t{$answertextcenter}</td>\n";
                    // separator
                    array_push($inputnames, $myfname1);
                    $thiskey = 0;
                    foreach ($labelcode1 as $ld) {
                        $answer .= "\t<td class=\"answer_cell_2_00{$ld}  answer-item radio-item\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname1}\" value=\"{$ld}\" id=\"answer{$myfid1}-{$ld}\" ";
                        if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == $ld) {
                            $answer .= CHECKED;
                        }
                        $answer .= " />\n" . "<label class=\"hide read\" for=\"answer{$myfid1}-{$ld}\">{$labelans1[$thiskey]}</label>\n" . "\t</td>\n";
                        $thiskey++;
                    }
                }
                if ($shownoanswer || $rightexists) {
                    $answer .= "\t<td class=\"answertextright dual_scale_separator information-item\">{$answertextrigth}</td>\n";
                }
                if ($shownoanswer) {
                    $answer .= "\t<td class=\"dual_scale_no_answer answer-item radio-item noanswer-item\">\n";
                    if (count($labelans1) > 0) {
                        $answer .= "\t<input class='radio' type='radio' name='{$myfname1}' value='' id='answer{$myfid1}-' ";
                        if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == "") {
                            $answer .= CHECKED;
                        }
                        // --> START NEW FEATURE - SAVE
                        $answer .= " />\n";
                        $answer .= "<label class='hide read' for='answer{$myfid1}-'>" . gT("No answer") . "</label>";
                    } else {
                        $answer .= "\t<input class='radio' type='radio' name='{$myfname0}' value='' id='answer{$myfid0}-' ";
                        if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] == "") {
                            $answer .= CHECKED;
                        }
                        $answer .= "<label class='hide read' for='answer{$myfid0}-'>" . gT("No answer") . "<label>\n";
                        $answer .= " />\n";
                    }
                    $answer .= "\t</td>\n";
                }
                $answer .= "</tr>\n";
                $fn++;
            }
            $answer .= "</tbody>\n";
            $answer .= "</table>";
        } elseif ($useDropdownLayout === true) {
            $separatorwidth = (100 - $answerwidth) / 10;
            $cellwidth = (100 - $answerwidth - $separatorwidth) / 2;
            $answer = "";
            // Get attributes for Headers and Prefix/Suffix
            if (trim($aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
                list($ddprefix, $ddsuffix) = explode("|", $aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]);
                $ddprefix = $ddprefix;
                $ddsuffix = $ddsuffix;
            } else {
                $ddprefix = '';
                $ddsuffix = '';
            }
            if (trim($aQuestionAttributes['dropdown_separators']) != '') {
                $aSeparator = explode('|', $aQuestionAttributes['dropdown_separators']);
                if (isset($aSeparator[1])) {
                    $interddSep = $aSeparator[1];
                } else {
                    $interddSep = $aSeparator[0];
                }
            } else {
                $interddSep = '';
            }
            $colspan_1 = '';
            $colspan_2 = '';
            $suffix_cell = '';
            $answer .= "\n<table class=\"question subquestion-list questions-list dropdown-list\" summary=\"{$caption}\">\n" . "\t<col class=\"answertext\" width=\"{$answerwidth}%\" />\n";
            if ($ddprefix != '' || $ddsuffix != '') {
                $answer .= "\t<colgroup width=\"{$cellwidth}%\">\n";
            }
            if ($ddprefix != '') {
                $answer .= "\t\t<col class=\"ddprefix\" />\n";
                $colspan_1 = ' colspan="2"';
            }
            $headcolwidth = $ddprefix != '' || $ddsuffix != '' ? "" : " width=\"{$cellwidth}%\"";
            $answer .= "\t<col class=\"dsheader\"{$headcolwidth} />\n";
            if ($ddsuffix != '') {
                $answer .= "\t<col class=\"ddsuffix\" />\n";
            }
            if ($ddprefix != '' || $ddsuffix != '') {
                $answer .= "\t</colgroup>\n";
            }
            $answer .= "\t<col class=\"ddarrayseparator\" width=\"{$separatorwidth}%\" />\n";
            if ($ddprefix != '' || $ddsuffix != '') {
                $answer .= "\t<colgroup width=\"{$cellwidth}%\">\n";
            }
            if ($ddprefix != '') {
                $answer .= "\t\t<col class=\"ddprefix\" />\n";
            }
            $answer .= "\t<col class=\"dsheader\"{$headcolwidth} />\n";
            if ($ddsuffix != '') {
                $answer .= "\t<col class=\"ddsuffix\" />\n";
            }
            if ($ddprefix != '' || $ddsuffix != '') {
                $answer .= "\t</colgroup>\n";
            }
            // colspan : for header only
            if ($ddprefix != '' && $ddsuffix != '') {
                $colspan = ' colspan="3"';
            } elseif ($ddprefix != '' || $ddsuffix != '') {
                $colspan = ' colspan="2"';
            } else {
                $colspan = "";
            }
            // headers
            $answer .= "\n\t<thead>\n" . "<tr>\n" . "\t<td>&nbsp;</td>\n" . "\t<th{$colspan}>{$leftheader}</th>\n" . "\t<td>&nbsp;</td>\n" . "\t<th{$colspan}>{$rightheader}</th>\n";
            $answer .= "\t</tr>\n" . "\t</thead>\n";
            $answer .= "\n<tbody>\n";
            $trbc = '';
            foreach ($aSubQuestions as $ansrow) {
                $myfname = $ia[1] . $ansrow['title'];
                $myfname0 = $ia[1] . $ansrow['title'] . "#0";
                $myfid0 = $ia[1] . $ansrow['title'] . "_0";
                $myfname1 = $ia[1] . $ansrow['title'] . "#1";
                $myfid1 = $ia[1] . $ansrow['title'] . "_1";
                $sActualAnswer0 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname0] : "";
                $sActualAnswer1 = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) ? $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] : "";
                if ($ia[6] == 'Y' && (in_array($myfname0, $aMandatoryViolationSubQ) || in_array($myfname1, $aMandatoryViolationSubQ))) {
                    $answertext = "<span class='errormandatory'>" . $ansrow['question'] . "</span>";
                } else {
                    $answertext = $ansrow['question'];
                }
                list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, $trbc, $myfname, "tr", "{$trbc} subquestion-list questions-list dropdown-list");
                $answer .= $htmltbody2;
                $answer .= "\t<th class=\"answertext\">\n" . "<label for=\"answer{$myfid0}\">{$answertext}</label>\n";
                // Hidden answers used by EM: sure can be added in javascript
                $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid0}\" id=\"java{$myfid0}\" value=\"{$sActualAnswer0}\" />\n";
                $answer .= "<input type=\"hidden\" disabled=\"disabled\" name=\"java{$myfid1}\" id=\"java{$myfid1}\" value=\"{$sActualAnswer1}\" />\n";
                $answer . "\t</th>\n";
                // Selector 0
                if ($ddprefix != '') {
                    $answer .= "\t<td class=\"ddprefix information-item\">{$ddprefix}</td>\n";
                }
                $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<select name=\"{$myfname0}\" id=\"answer{$myfid0}\">\n";
                // Show the 'Please choose' if there are no answer actually
                if ($sActualAnswer0 == '') {
                    $answer .= "\t<option value=\"\" " . SELECTED . ">" . gT('Please choose...') . "</option>\n";
                }
                foreach ($labels0 as $lrow) {
                    $answer .= "\t<option value=\"" . $lrow['code'] . '" ';
                    if ($sActualAnswer0 == $lrow['code']) {
                        $answer .= SELECTED;
                    }
                    $answer .= '>' . flattenText($lrow['title']) . "</option>\n";
                }
                if ($sActualAnswer0 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER) {
                    $answer .= "\t<option value=\"\">" . gT('No answer') . "</option>\n";
                }
                $answer .= "</select>\n";
                $answer .= "</td>\n";
                if ($ddsuffix != '') {
                    $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n";
                }
                $inputnames[] = $myfname0;
                $answer .= "\t<td class=\"ddarrayseparator information-item\">{$interddSep}</td>\n";
                //Separator
                // Selector 1
                if ($ddprefix != '') {
                    $answer .= "\t<td class='ddprefix information-item'>{$ddprefix}</td>\n";
                }
                $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<label class=\"hide read\" for=\"answer{$myfid1}\">{$answertext}</label>" . "<select name=\"{$myfname1}\" id=\"answer{$myfid1}\">\n";
                // Show the 'Please choose' if there are no answer actually
                if ($sActualAnswer1 == '') {
                    $answer .= "\t<option value=\"\" " . SELECTED . ">" . gT('Please choose...') . "</option>\n";
                }
                foreach ($labels1 as $lrow1) {
                    $answer .= "\t<option value=\"" . $lrow1['code'] . '" ';
                    if ($sActualAnswer1 == $lrow1['code']) {
                        $answer .= SELECTED;
                    }
                    $answer .= '>' . flattenText($lrow1['title']) . "</option>\n";
                }
                if ($sActualAnswer1 != '' && $ia[6] != 'Y' && SHOW_NO_ANSWER) {
                    $answer .= "\t<option value=\"\">" . gT('No answer') . "</option>\n";
                }
                $answer .= "</select>\n";
                $answer .= "</td>\n";
                if ($ddsuffix != '') {
                    $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n";
                }
                $inputnames[] = $myfname1;
                $answer .= "</tr>\n";
            }
            $answer .= "\t</tbody>\n";
            $answer .= "</table>\n";
        }
    } else {
        $answer = "<p class='error'>" . gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n";
        $inputnames = "";
    }
    Yii::app()->getClientScript()->registerScriptFile(Yii::app()->getConfig('generalscripts') . "dualscale.js");
    $answer .= "<script type='text/javascript'>\n" . "  <!--\n" . " {$doDualScaleFunction}({$ia[0]});\n" . " -->\n" . "</script>\n";
    return array($answer, $inputnames);
}
/**
* Creates an array with details on a particular response for display purposes
* Used in Print answers, Detailed response view and Detailed admin notification email
*
* @param mixed $iSurveyID
* @param mixed $iResponseID
* @param mixed $sLanguageCode
* @param boolean $bHonorConditions Apply conditions
*/
function getFullResponseTable($iSurveyID, $iResponseID, $sLanguageCode, $bHonorConditions = true)
{
    $aFieldMap = createFieldMap($iSurveyID, 'full', false, false, $sLanguageCode);
    //Get response data
    $idrow = SurveyDynamic::model($iSurveyID)->findByAttributes(array('id' => $iResponseID));
    // Create array of non-null values - those are the relevant ones
    $aRelevantFields = array();
    foreach ($aFieldMap as $sKey => $fname) {
        if (LimeExpressionManager::QuestionIsRelevant($fname['qid']) || $bHonorConditions == false) {
            $aRelevantFields[$sKey] = $fname;
        }
    }
    $aResultTable = array();
    $oldgid = 0;
    $oldqid = 0;
    foreach ($aRelevantFields as $sKey => $fname) {
        if (!empty($fname['qid'])) {
            $attributes = getQuestionAttributeValues($fname['qid']);
            if (getQuestionAttributeValue($attributes, 'hidden') == 1) {
                continue;
            }
        }
        $question = $fname['question'];
        $subquestion = '';
        if (isset($fname['gid']) && !empty($fname['gid'])) {
            //Check to see if gid is the same as before. if not show group name
            if ($oldgid !== $fname['gid']) {
                $oldgid = $fname['gid'];
                if (LimeExpressionManager::GroupIsRelevant($fname['gid']) || $bHonorConditions == false) {
                    $aResultTable['gid_' . $fname['gid']] = array($fname['group_name'], QuestionGroup::model()->getGroupDescription($fname['gid'], $sLanguageCode));
                }
            }
        }
        if (!empty($fname['qid'])) {
            if ($oldqid !== $fname['qid']) {
                $oldqid = $fname['qid'];
                if (isset($fname['subquestion']) || isset($fname['subquestion1']) || isset($fname['subquestion2'])) {
                    $aResultTable['qid_' . $fname['sid'] . 'X' . $fname['gid'] . 'X' . $fname['qid']] = array($fname['question'], '', '');
                } else {
                    $answer = getExtendedAnswer($iSurveyID, $fname['fieldname'], $idrow[$fname['fieldname']], $sLanguageCode);
                    $aResultTable[$fname['fieldname']] = array($question, '', $answer);
                    continue;
                }
            }
        } else {
            $answer = getExtendedAnswer($iSurveyID, $fname['fieldname'], $idrow[$fname['fieldname']], $sLanguageCode);
            $aResultTable[$fname['fieldname']] = array($question, '', $answer);
            continue;
        }
        if (isset($fname['subquestion'])) {
            $subquestion = "[{$fname['subquestion']}]";
        }
        if (isset($fname['subquestion1'])) {
            $subquestion = "[{$fname['subquestion1']}]";
        }
        if (isset($fname['subquestion2'])) {
            $subquestion .= "[{$fname['subquestion2']}]";
        }
        $answer = getExtendedAnswer($iSurveyID, $fname['fieldname'], $idrow[$fname['fieldname']], $sLanguageCode);
        $aResultTable[$fname['fieldname']] = array($question, $subquestion, $answer);
    }
    return $aResultTable;
}
/**
* Caculate assessement scores
*
* @param mixed $surveyid
* @param mixed $returndataonly - only returns an array with data
*/
function doAssessment($surveyid, $returndataonly = false)
{
    $clang = Yii::app()->lang;
    $baselang = Survey::model()->findByPk($surveyid)->language;
    if (Survey::model()->findByPk($surveyid)->assessments != "Y") {
        return false;
    }
    $total = 0;
    if (!isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
        $_SESSION['survey_' . $surveyid]['s_lang'] = $baselang;
    }
    $query = "SELECT * FROM {{assessments}}\n    WHERE sid={$surveyid} and language='" . $_SESSION['survey_' . $surveyid]['s_lang'] . "'\n    ORDER BY scope, id";
    if ($result = dbExecuteAssoc($query)) {
        $aResultSet = $result->readAll();
        if (count($aResultSet) > 0) {
            foreach ($aResultSet as $row) {
                if ($row['scope'] == "G") {
                    $assessment['group'][$row['gid']][] = array("name" => $row['name'], "min" => $row['minimum'], "max" => $row['maximum'], "message" => $row['message']);
                } else {
                    $assessment['total'][] = array("name" => $row['name'], "min" => $row['minimum'], "max" => $row['maximum'], "message" => $row['message']);
                }
            }
            $fieldmap = createFieldMap($surveyid, "full", false, false, $_SESSION['survey_' . $surveyid]['s_lang']);
            $i = 0;
            $total = 0;
            $groups = array();
            foreach ($fieldmap as $field) {
                if (in_array($field['type'], array('1', 'F', 'H', 'W', 'Z', 'L', '!', 'M', 'O', 'P'))) {
                    $fieldmap[$field['fieldname']]['assessment_value'] = 0;
                    if (isset($_SESSION['survey_' . $surveyid][$field['fieldname']])) {
                        if ($field['type'] == "M" || $field['type'] == "P") {
                            if ($_SESSION['survey_' . $surveyid][$field['fieldname']] == "Y") {
                                $aAttributes = getQuestionAttributeValues($field['qid'], $field['type']);
                                $fieldmap[$field['fieldname']]['assessment_value'] = (int) $aAttributes['assessment_value'];
                                $total = $total + (int) $aAttributes['assessment_value'];
                            }
                        } else {
                            $usquery = "SELECT assessment_value FROM {{answers}} where qid=" . $field['qid'] . " and language='{$baselang}' and code=" . dbQuoteAll($_SESSION['survey_' . $surveyid][$field['fieldname']]);
                            $usresult = dbExecuteAssoc($usquery);
                            //Checked
                            if ($usresult) {
                                $usrow = $usresult->read();
                                $fieldmap[$field['fieldname']]['assessment_value'] = $usrow['assessment_value'];
                                $total = $total + $usrow['assessment_value'];
                            }
                        }
                    }
                    $groups[] = $field['gid'];
                }
                $i++;
            }
            $groups = array_unique($groups);
            foreach ($groups as $group) {
                $grouptotal = 0;
                foreach ($fieldmap as $field) {
                    if ($field['gid'] == $group && isset($field['assessment_value'])) {
                        //$grouptotal=$grouptotal+$field['answer'];
                        if (isset($_SESSION['survey_' . $surveyid][$field['fieldname']])) {
                            $grouptotal = $grouptotal + $field['assessment_value'];
                        }
                    }
                }
                $subtotal[$group] = $grouptotal;
            }
        }
        $assessments = "";
        if (isset($subtotal) && is_array($subtotal)) {
            foreach ($subtotal as $key => $val) {
                if (isset($assessment['group'][$key])) {
                    foreach ($assessment['group'][$key] as $assessed) {
                        if ($val >= $assessed['min'] && $val <= $assessed['max'] && $returndataonly === false) {
                            $assessments .= "\t<!-- GROUP ASSESSMENT: Score: {$val} Min: " . $assessed['min'] . " Max: " . $assessed['max'] . "-->\n                            <table class='assessments'>\n                            <tr>\n                            <th>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), $assessed['name']) . "\n                            </th>\n                            </tr>\n                            <tr>\n                            <td>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), $assessed['message']) . "\n                            </td>\n                            </tr>\n                            </table><br />\n";
                        }
                    }
                }
            }
        }
        if (isset($assessment['total'])) {
            foreach ($assessment['total'] as $assessed) {
                if ($total >= $assessed['min'] && $total <= $assessed['max'] && $returndataonly === false) {
                    $assessments .= "\t\t\t<!-- TOTAL ASSESSMENT: Score: {$total} Min: " . $assessed['min'] . " Max: " . $assessed['max'] . "-->\n                    <table class='assessments' align='center'>\n                    <tr>\n                    <th>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), stripslashes($assessed['name'])) . "\n                    </th>\n                    </tr>\n                    <tr>\n                    <td>" . str_replace(array("{PERC}", "{TOTAL}"), array($val, $total), stripslashes($assessed['message'])) . "\n                    </td>\n                    </tr>\n                    </table>\n";
                }
            }
        }
        if ($returndataonly == true) {
            return array('total' => $total);
        } else {
            return $assessments;
        }
    }
}
Esempio n. 6
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);
 }
Esempio n. 7
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);
 }
    /**
     * Main function
     *
     * @param mixed $surveyid
     * @param mixed $args
     */
    function run($surveyid, $args)
    {
        global $errormsg;
        extract($args);
        $LEMsessid = 'survey_' . $surveyid;
        $sTemplatePath = getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR;
        if (isset($_SESSION['survey_' . $surveyid]['templatepath'])) {
            $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
        }
        // $LEMdebugLevel - customizable debugging for Lime Expression Manager
        $LEMdebugLevel = 0;
        // LEM_DEBUG_TIMING;    // (LEM_DEBUG_TIMING + LEM_DEBUG_VALIDATION_SUMMARY + LEM_DEBUG_VALIDATION_DETAIL);
        $LEMskipReprocessing = false;
        // true if used GetLastMoveResult to avoid generation of unneeded extra JavaScript
        switch ($thissurvey['format']) {
            case "A":
                //All in one
                $surveyMode = 'survey';
                break;
            default:
            case "S":
                //One at a time
                $surveyMode = 'question';
                break;
            case "G":
                //Group at a time
                $surveyMode = 'group';
                break;
        }
        $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
        $radix = $radix['seperator'];
        $surveyOptions = array('active' => $thissurvey['active'] == 'Y', 'allowsave' => $thissurvey['allowsave'] == 'Y', 'anonymized' => $thissurvey['anonymized'] != 'N', 'assessments' => $thissurvey['assessments'] == 'Y', 'datestamp' => $thissurvey['datestamp'] == 'Y', 'hyperlinkSyntaxHighlighting' => ($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY, 'ipaddr' => $thissurvey['ipaddr'] == 'Y', 'radix' => $radix, 'refurl' => $thissurvey['refurl'] == "Y" ? $_SESSION[$LEMsessid]['refurl'] : NULL, 'savetimings' => $thissurvey['savetimings'] == "Y", 'surveyls_dateformat' => isset($thissurvey['surveyls_dateformat']) ? $thissurvey['surveyls_dateformat'] : 1, 'startlanguage' => isset($clang->langcode) ? $clang->langcode : $thissurvey['language'], 'target' => Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'surveys' . DIRECTORY_SEPARATOR . $thissurvey['sid'] . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR, 'tempdir' => Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR, 'timeadjust' => isset($timeadjust) ? $timeadjust : 0, 'token' => isset($clienttoken) ? $clienttoken : NULL);
        //Security Checked: POST, GET, SESSION, REQUEST, returnGlobal, DB
        $previewgrp = false;
        if ($surveyMode == 'group' && isset($param['action']) && $param['action'] == 'previewgroup') {
            $previewgrp = true;
        }
        $previewquestion = false;
        if ($surveyMode == 'question' && isset($param['action']) && $param['action'] == 'previewquestion') {
            $previewquestion = true;
        }
        //        if (isset($param['newtest']) && $param['newtest'] == "Y")
        //            setcookie("limesurvey_timers", "0");   //@todo fix - sometimes results in headers already sent error
        $show_empty_group = false;
        if ($previewgrp || $previewquestion) {
            $_SESSION[$LEMsessid]['prevstep'] = 1;
            $_SESSION[$LEMsessid]['maxstep'] = 0;
        } else {
            //RUN THIS IF THIS IS THE FIRST TIME , OR THE FIRST PAGE ########################################
            if (!isset($_SESSION[$LEMsessid]['step'])) {
                buildsurveysession($surveyid);
                $sTemplatePath = $_SESSION[$LEMsessid]['templatepath'];
                if ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
                    LimeExpressionManager::SetDirtyFlag();
                }
                LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
                $_SESSION[$LEMsessid]['step'] = 0;
                if ($surveyMode == 'survey') {
                    $move = "movenext";
                    // to force a call to NavigateForwards()
                } elseif (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
                    $move = "movenext";
                    $_SESSION[$LEMsessid]['step'] = 1;
                }
            } else {
                if ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
                    LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
                    LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
                }
            }
            $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
            if (!isset($_SESSION[$LEMsessid]['totalsteps'])) {
                $_SESSION[$LEMsessid]['totalsteps'] = 0;
            }
            if (!isset($_SESSION[$LEMsessid]['maxstep'])) {
                $_SESSION[$LEMsessid]['maxstep'] = 0;
            }
            if (isset($_SESSION[$LEMsessid]['LEMpostKey']) && isset($_POST['LEMpostKey']) && $_POST['LEMpostKey'] != $_SESSION[$LEMsessid]['LEMpostKey']) {
                // then trying to resubmit (e.g. Next, Previous, Submit) from a cached copy of the page
                // Does not try to save anything from the page to the database
                $moveResult = LimeExpressionManager::GetLastMoveResult(true);
                if (isset($_POST['thisstep']) && isset($moveResult['seq']) && $_POST['thisstep'] == $moveResult['seq']) {
                    // then pressing F5 or otherwise refreshing the current page, which is OK
                    $LEMskipReprocessing = true;
                    $move = "movenext";
                    // so will re-display the survey
                } else {
                    // trying to use browser back buttons, which may be disallowed if no 'previous' button is present
                    $LEMskipReprocessing = true;
                    $move = "movenext";
                    // so will re-display the survey
                    $invalidLastPage = true;
                    $vpopup = "<script type=\"text/javascript\">\n\n                    <!--\n \$(document).ready(function(){\n                    alert(\"" . $clang->gT("Please use the LimeSurvey navigation buttons or index.  It appears you attempted to use the browser back button to re-submit a page.", "js") . "\");});\n //-->\n\n                    </script>\n";
                }
            }
            if (!(isset($_POST['saveall']) || isset($_POST['saveprompt']) || isset($_POST['loadall']) || isset($_GET['sid']) || $LEMskipReprocessing || isset($move) && preg_match('/^changelang_/', $move))) {
                $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step'];
            }
            if (!isset($_SESSION[$LEMsessid]['prevstep'])) {
                $_SESSION[$LEMsessid]['prevstep'] = -1;
                // this only happens on re-load
            }
            if (isset($_SESSION[$LEMsessid]['LEMtokenResume'])) {
                LimeExpressionManager::StartSurvey($thissurvey['sid'], $surveyMode, $surveyOptions, false, $LEMdebugLevel);
                $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
                // if late in the survey, will re-validate contents, which may be overkill
                unset($_SESSION[$LEMsessid]['LEMtokenResume']);
            } else {
                if (!$LEMskipReprocessing) {
                    //Move current step ###########################################################################
                    if (isset($move) && $move == 'moveprev' && ($thissurvey['allowprev'] == 'Y' || $thissurvey['allowjumps'] == 'Y')) {
                        $moveResult = LimeExpressionManager::NavigateBackwards();
                        if ($moveResult['at_start']) {
                            $_SESSION[$LEMsessid]['step'] = 0;
                            unset($moveResult);
                            // so display welcome page again
                        }
                    }
                    if (isset($move) && $move == "movenext") {
                        $moveResult = LimeExpressionManager::NavigateForwards();
                    }
                    if (isset($move) && $move == 'movesubmit') {
                        if ($surveyMode == 'survey') {
                            $moveResult = LimeExpressionManager::NavigateForwards();
                        } else {
                            // may be submitting from the navigation bar, in which case need to process all intervening questions
                            // in order to update equations and ensure there are no intervening relevant mandatory or relevant invalid questions
                            $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false);
                        }
                    }
                    if (isset($move) && preg_match('/^changelang_/', $move)) {
                        // jump to current step using new language, processing POST values
                        $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, false, true);
                        // do process the POST data
                    }
                    if (isset($move) && isNumericInt($move) && $thissurvey['allowjumps'] == 'Y') {
                        $move = (int) $move;
                        if ($move > 0 && ($move <= $_SESSION[$LEMsessid]['step'] || isset($_SESSION[$LEMsessid]['maxstep']) && $move <= $_SESSION[$LEMsessid]['maxstep'])) {
                            $moveResult = LimeExpressionManager::JumpTo($move, false);
                        }
                    }
                    if (!isset($moveResult) && !($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0)) {
                        // Just in case not set via any other means, but don't do this if it is the welcome page
                        $moveResult = LimeExpressionManager::GetLastMoveResult(true);
                        $LEMskipReprocessing = true;
                    }
                }
            }
            if (isset($moveResult)) {
                if ($moveResult['finished'] == true) {
                    $move = 'movesubmit';
                } else {
                    $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
                    // step is index base 1
                    $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                }
                if ($move == "movesubmit" && $moveResult['finished'] == false) {
                    // then there are errors, so don't finalize the survey
                    $move = "movenext";
                    // so will re-display the survey
                    $invalidLastPage = true;
                }
            }
            // We do not keep the participant session anymore when the same browser is used to answer a second time a survey (let's think of a library PC for instance).
            // Previously we used to keep the session and redirect the user to the
            // submit page.
            if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0) {
                $_SESSION[$LEMsessid]['test'] = time();
                display_first_page();
                exit;
            }
            //CHECK IF ALL MANDATORY QUESTIONS HAVE BEEN ANSWERED ############################################
            //First, see if we are moving backwards or doing a Save so far, and its OK not to check:
            if (isset($move) && ($move == "moveprev" || is_int($move) && $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['maxstep'] || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']) || isset($_POST['saveall']) && $_POST['saveall'] == $clang->gT("Save your responses so far")) {
                if (Yii::app()->getConfig('allowmandbackwards') == 1) {
                    $backok = "Y";
                } else {
                    $backok = "N";
                }
            } else {
                $backok = "N";
                // NA, since not moving backwards
            }
            // TODO FIXME
            if ($thissurvey['active'] == "Y") {
                Yii::import("application.libraries.Save");
                $cSave = new Save();
            }
            if ($thissurvey['active'] == "Y" && isset($_POST['saveall'])) {
                // must do this here to process the POSTed values
                $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false);
                // by jumping to current step, saves data so far
                $cSave->showsaveform();
                // generates a form and exits, awaiting input
            }
            if ($thissurvey['active'] == "Y" && isset($_POST['saveprompt'])) {
                // The response from the save form
                // CREATE SAVED CONTROL RECORD USING SAVE FORM INFORMATION
                $flashmessage = $cSave->savedcontrol();
                if (isset($errormsg) && $errormsg != "") {
                    $cSave->showsaveform();
                    // reshow the form if there is an error
                }
                $moveResult = LimeExpressionManager::GetLastMoveResult(true);
                $LEMskipReprocessing = true;
                // TODO - does this work automatically for token answer persistence? Used to be savedsilent()
            }
            //Now, we check mandatory questions if necessary
            //CHECK IF ALL CONDITIONAL MANDATORY QUESTIONS THAT APPLY HAVE BEEN ANSWERED
            global $notanswered;
            if (isset($moveResult) && !$moveResult['finished']) {
                $unansweredSQList = $moveResult['unansweredSQs'];
                if (strlen($unansweredSQList) > 0 && $backok != "N") {
                    $notanswered = explode('|', $unansweredSQList);
                } else {
                    $notanswered = array();
                }
                //CHECK INPUT
                $invalidSQList = $moveResult['invalidSQs'];
                if (strlen($invalidSQList) > 0 && $backok != "N") {
                    $notvalidated = explode('|', $invalidSQList);
                } else {
                    $notvalidated = array();
                }
            }
            // CHECK UPLOADED FILES
            // TMSW - Move this into LEM::NavigateForwards?
            $filenotvalidated = checkUploadedFileValidity($surveyid, $move, $backok);
            //SEE IF THIS GROUP SHOULD DISPLAY
            $show_empty_group = false;
            if ($_SESSION[$LEMsessid]['step'] == 0) {
                $show_empty_group = true;
            }
            $redata = compact(array_keys(get_defined_vars()));
            //SUBMIT ###############################################################################
            if (isset($move) && $move == "movesubmit") {
                //                setcookie("limesurvey_timers", "", time() - 3600); // remove the timers cookies   //@todo fix - sometimes results in headers already sent error
                if ($thissurvey['refurl'] == "Y") {
                    if (!in_array("refurl", $_SESSION[$LEMsessid]['insertarray'])) {
                        $_SESSION[$LEMsessid]['insertarray'][] = "refurl";
                    }
                }
                resetTimers();
                //Before doing the "templatereplace()" function, check the $thissurvey['url']
                //field for limereplace stuff, and do transformations!
                $thissurvey['surveyls_url'] = passthruReplace($thissurvey['surveyls_url'], $thissurvey);
                $thissurvey['surveyls_url'] = templatereplace($thissurvey['surveyls_url'], $thissurvey);
                // to do INSERTANS substitutions
                //END PAGE - COMMIT CHANGES TO DATABASE
                if ($thissurvey['active'] != "Y") {
                    if ($thissurvey['assessments'] == "Y") {
                        $assessments = doAssessment($surveyid);
                    }
                    sendCacheHeaders();
                    doHeader();
                    echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
                    //Check for assessments
                    if ($thissurvey['assessments'] == "Y" && $assessments) {
                        echo templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata);
                    }
                    // fetch all filenames from $_SESSIONS['files'] and delete them all
                    // from the /upload/tmp/ directory
                    /* echo "<pre>";print_r($_SESSION);echo "</pre>";
                       for($i = 1; isset($_SESSION[$LEMsessid]['files'][$i]); $i++)
                       {
                       unlink('upload/tmp/'.$_SESSION[$LEMsessid]['files'][$i]['filename']);
                       }
                       */
                    // can't kill session before end message, otherwise INSERTANS doesn't work.
                    $completed = templatereplace($thissurvey['surveyls_endtext']);
                    $completed .= "<br /><strong><font size='2' color='red'>" . $clang->gT("Did Not Save") . "</font></strong><br /><br />\n\n";
                    $completed .= $clang->gT("Your survey responses have not been recorded. This survey is not yet active.") . "<br /><br />\n";
                    if ($thissurvey['printanswers'] == 'Y') {
                        // 'Clear all' link is only relevant for survey with printanswers enabled
                        // in other cases the session is cleared at submit time
                        $completed .= "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/move/clearall") . "'>" . $clang->gT("Clear Responses") . "</a><br /><br />\n";
                    }
                } else {
                    if ($thissurvey['usecookie'] == "Y" && $tokensexist != 1) {
                        setcookie("LS_" . $surveyid . "_STATUS", "COMPLETE", time() + 31536000);
                        //Cookie will expire in 365 days
                    }
                    $content = '';
                    $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
                    //Check for assessments
                    if ($thissurvey['assessments'] == "Y") {
                        $assessments = doAssessment($surveyid);
                        if ($assessments) {
                            $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata);
                        }
                    }
                    //Update the token if needed and send a confirmation email
                    if (isset($clienttoken) && $clienttoken) {
                        submittokens();
                    }
                    //Send notifications
                    sendSubmitNotifications($surveyid);
                    $content = '';
                    $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
                    //echo $thissurvey['url'];
                    //Check for assessments
                    if ($thissurvey['assessments'] == "Y") {
                        $assessments = doAssessment($surveyid);
                        if ($assessments) {
                            $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata);
                        }
                    }
                    if (trim(strip_tags($thissurvey['surveyls_endtext'])) == '') {
                        $completed = "<br /><span class='success'>" . $clang->gT("Thank you!") . "</span><br /><br />\n\n" . $clang->gT("Your survey responses have been recorded.") . "<br /><br />\n";
                    } else {
                        $completed = templatereplace($thissurvey['surveyls_endtext']);
                    }
                    // Link to Print Answer Preview  **********
                    if ($thissurvey['printanswers'] == 'Y') {
                        $url = Yii::app()->getController()->createUrl("printanswers/view/surveyid/{$surveyid}");
                        $completed .= "<br /><br />" . "<a class='printlink' href='{$url}'  target='_blank'>" . $clang->gT("Print your answers.") . "</a><br />\n";
                    }
                    //*****************************************
                    if ($thissurvey['publicstatistics'] == 'Y' && $thissurvey['printanswers'] == 'Y') {
                        $completed .= '<br />' . $clang->gT("or");
                    }
                    // Link to Public statistics  **********
                    if ($thissurvey['publicstatistics'] == 'Y') {
                        $url = Yii::app()->getController()->createUrl("statistics_user/action/surveyid/{$surveyid}/language/" . $_SESSION[$LEMsessid]['s_lang']);
                        $completed .= "<br /><br />" . "<a class='publicstatisticslink' href='{$url}' target='_blank'>" . $clang->gT("View the statistics for this survey.") . "</a><br />\n";
                    }
                    //*****************************************
                    $_SESSION[$LEMsessid]['finished'] = true;
                    $_SESSION[$LEMsessid]['sid'] = $surveyid;
                    sendCacheHeaders();
                    if (isset($thissurvey['autoredirect']) && $thissurvey['autoredirect'] == "Y" && $thissurvey['surveyls_url']) {
                        //Automatically redirect the page to the "url" setting for the survey
                        header("Location: {$thissurvey['surveyls_url']}");
                    }
                    doHeader();
                    echo $content;
                }
                $redata['completed'] = $completed;
                echo templatereplace(file_get_contents($sTemplatePath . "completed.pstpl"), array('completed' => $completed), $redata);
                echo "\n<br />\n";
                if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
                    echo LimeExpressionManager::GetDebugTimingMessage();
                }
                if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                    echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
                }
                echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"));
                doFooter();
                // The session cannot be killed until the page is completely rendered
                if ($thissurvey['printanswers'] != 'Y') {
                    killSurveySession($surveyid);
                }
                exit;
            }
        }
        $redata = compact(array_keys(get_defined_vars()));
        // IF GOT THIS FAR, THEN DISPLAY THE ACTIVE GROUP OF QUESTIONSs
        //SEE IF $surveyid EXISTS ####################################################################
        if ($surveyExists < 1) {
            //SURVEY DOES NOT EXIST. POLITELY EXIT.
            echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
            echo "\t<center><br />\n";
            echo "\t" . $clang->gT("Sorry. There is no matching survey.") . "<br /></center>&nbsp;\n";
            echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
            doFooter();
            exit;
        }
        createFieldMap($surveyid, 'full', false, false, $_SESSION[$LEMsessid]['s_lang']);
        //GET GROUP DETAILS
        if ($surveyMode == 'group' && $previewgrp) {
            //            setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error
            $_gid = sanitize_int($param['gid']);
            LimeExpressionManager::StartSurvey($thissurvey['sid'], 'group', $surveyOptions, false, $LEMdebugLevel);
            $gseq = LimeExpressionManager::GetGroupSeq($_gid);
            if ($gseq == -1) {
                echo $clang->gT('Invalid group number for this survey: ') . $_gid;
                exit;
            }
            $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true);
            if (is_null($moveResult)) {
                echo $clang->gT('This group contains no questions.  You must add questions to this group before you can preview it');
                exit;
            }
            if (isset($moveResult)) {
                $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
                // step is index base 1?
            }
            $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
            $gid = $stepInfo['gid'];
            $groupname = $stepInfo['gname'];
            $groupdescription = $stepInfo['gtext'];
        } else {
            if ($show_empty_group || !isset($_SESSION[$LEMsessid]['grouplist'])) {
                $gid = -1;
                // Make sure the gid is unused. This will assure that the foreach (fieldarray as ia) has no effect.
                $groupname = $clang->gT("Submit your answers");
                $groupdescription = $clang->gT("There are no more questions. Please press the <Submit> button to finish this survey.");
            } else {
                if ($surveyMode != 'survey') {
                    if ($previewquestion) {
                        $_qid = sanitize_int($param['qid']);
                        LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel);
                        $qSec = LimeExpressionManager::GetQuestionSeq($_qid);
                        $moveResult = LimeExpressionManager::JumpTo($qSec + 1, true, false, true);
                        $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                    } else {
                        $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                    }
                    $gid = $stepInfo['gid'];
                    $groupname = $stepInfo['gname'];
                    $groupdescription = $stepInfo['gtext'];
                }
            }
        }
        if ($previewquestion) {
            $_SESSION[$LEMsessid]['step'] = 0;
            //maybe unset it after the question has been displayed?
        }
        if ($_SESSION[$LEMsessid]['step'] > $_SESSION[$LEMsessid]['maxstep']) {
            $_SESSION[$LEMsessid]['maxstep'] = $_SESSION[$LEMsessid]['step'];
        }
        // If the survey uses answer persistence and a srid is registered in SESSION
        // then loadanswers from this srid
        /* Only survey mode used this - should all?
           if ($thissurvey['tokenanswerspersistence'] == 'Y' &&
           $thissurvey['anonymized'] == "N" &&
           isset($_SESSION[$LEMsessid]['srid']) &&
           $thissurvey['active'] == "Y")
           {
           loadanswers();
           }
           */
        //******************************************************************************************************
        //PRESENT SURVEY
        //******************************************************************************************************
        $okToShowErrors = !$previewgrp && (isset($invalidLastPage) || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']);
        Yii::app()->getController()->loadHelper('qanda');
        setNoAnswerMode($thissurvey);
        //Iterate through the questions about to be displayed:
        $inputnames = array();
        foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
            $gid = $gl[0];
            $qnumber = 0;
            if ($surveyMode != 'survey') {
                $onlyThisGID = $stepInfo['gid'];
                if ($onlyThisGID != $gid) {
                    continue;
                }
            }
            // TMSW - could iterate through LEM::currentQset instead
            foreach ($_SESSION[$LEMsessid]['fieldarray'] as $key => $ia) {
                ++$qnumber;
                $ia[9] = $qnumber;
                // incremental question count;
                if (isset($ia[10]) && $ia[10] == $gid || !isset($ia[10]) && $ia[5] == $gid) {
                    if ($surveyMode == 'question' && $ia[0] != $stepInfo['qid']) {
                        continue;
                    }
                    $qidattributes = getQuestionAttributeValues($ia[0], $ia[4]);
                    if ($ia[4] != '*' && ($qidattributes === false || !isset($qidattributes['hidden']) || $qidattributes['hidden'] == 1)) {
                        continue;
                    }
                    //Get the answers/inputnames
                    // TMSW - can content of retrieveAnswers() be provided by LEM?  Review scope of what it provides.
                    // TODO - retrieveAnswers is slow - queries database separately for each question. May be fixed in _CI or _YII ports, so ignore for now
                    list($plus_qanda, $plus_inputnames) = retrieveAnswers($ia, $surveyid);
                    if ($plus_qanda) {
                        $plus_qanda[] = $ia[4];
                        $plus_qanda[] = $ia[6];
                        // adds madatory identifyer for adding mandatory class to question wrapping div
                        $qanda[] = $plus_qanda;
                    }
                    if ($plus_inputnames) {
                        $inputnames = addtoarray_single($inputnames, $plus_inputnames);
                    }
                    //Display the "mandatory" popup if necessary
                    // TMSW - get question-level error messages - don't call **_popup() directly
                    if ($okToShowErrors && $stepInfo['mandViolation']) {
                        list($mandatorypopup, $popup) = mandatory_popup($ia, $notanswered);
                    }
                    //Display the "validation" popup if necessary
                    if ($okToShowErrors && !$stepInfo['valid']) {
                        list($validationpopup, $vpopup) = validation_popup($ia, $notvalidated);
                    }
                    // Display the "file validation" popup if necessary
                    if ($okToShowErrors && isset($filenotvalidated)) {
                        list($filevalidationpopup, $fpopup) = file_validation_popup($ia, $filenotvalidated);
                    }
                }
                if ($ia[4] == "|") {
                    $upload_file = TRUE;
                }
            }
            //end iteration
        }
        if ($surveyMode != 'survey' && isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == 'Y') {
            if ($show_empty_group) {
                $percentcomplete = makegraph($_SESSION[$LEMsessid]['totalsteps'] + 1, $_SESSION[$LEMsessid]['totalsteps']);
            } else {
                $percentcomplete = makegraph($_SESSION[$LEMsessid]['step'], $_SESSION[$LEMsessid]['totalsteps']);
            }
        }
        if (!(isset($languagechanger) && strlen($languagechanger) > 0) && function_exists('makeLanguageChangerSurvey')) {
            $languagechanger = makeLanguageChangerSurvey($_SESSION[$LEMsessid]['s_lang']);
        }
        //READ TEMPLATES, INSERT DATA AND PRESENT PAGE
        sendCacheHeaders();
        doHeader();
        $redata = compact(array_keys(get_defined_vars()));
        echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
        //popup need jquery
        if (isset($popup)) {
            echo $popup;
        }
        if (isset($vpopup)) {
            echo $vpopup;
        }
        if (isset($fpopup)) {
            echo $fpopup;
        }
        //ALTER PAGE CLASS TO PROVIDE WHOLE-PAGE ALTERNATION
        if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep'] || isset($_SESSION[$LEMsessid]['stepno']) && $_SESSION[$LEMsessid]['stepno'] % 2) {
            if (!isset($_SESSION[$LEMsessid]['stepno'])) {
                $_SESSION[$LEMsessid]['stepno'] = 0;
            }
            if ($_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep']) {
                ++$_SESSION[$LEMsessid]['stepno'];
            }
            if ($_SESSION[$LEMsessid]['stepno'] % 2) {
                echo "<script type=\"text/javascript\">\n" . "  \$(\"body\").addClass(\"page-odd\");\n" . "</script>\n";
            }
        }
        $hiddenfieldnames = implode("|", $inputnames);
        if (isset($upload_file) && $upload_file) {
            echo CHtml::form(array("survey/index"), 'post', array('enctype' => 'multipart/form-data', 'id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
        } else {
            echo CHtml::form(array("survey/index"), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
        }
        echo sDefaultSubmitHandler();
        // <-- END FEATURE - SAVE
        if ($surveyMode == 'survey') {
            if (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
                //Hide the welcome screen if explicitly set
            } else {
                echo templatereplace(file_get_contents($sTemplatePath . "welcome.pstpl"), array(), $redata) . "\n";
            }
            if ($thissurvey['anonymized'] == "Y") {
                echo templatereplace(file_get_contents($sTemplatePath . "privacy.pstpl"), array(), $redata) . "\n";
            }
        }
        // <-- START THE SURVEY -->
        if ($surveyMode != 'survey') {
            echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata);
        }
        // the runonce element has been changed from a hidden to a text/display:none one
        // in order to workaround an not-reproduced issue #4453 (lemeur)
        echo "<input type='text' id='runonce' value='0' style='display: none;'/>\n        <!-- JAVASCRIPT FOR CONDITIONAL QUESTIONS -->\n        <script type='text/javascript'>\n        <!--\n";
        echo "var LEMradix='" . $radix . "';\n";
        echo "var numRegex = new RegExp('[^-' + LEMradix + '0-9]','g');\n";
        echo "var intRegex = new RegExp('[^-0-9]','g');\n";
        print <<<END
            function fixnum_checkconditions(value, name, type, evt_type, intonly)
            {
                newval = new String(value);
                if (typeof intonly !=='undefined' && intonly==1) {
                    newval = newval.replace(intRegex,'');
                }
                else {
                    newval = newval.replace(numRegex,'');
                }
                if (LEMradix === ',') {
                    newval = newval.split(',').join('.');
                }
                if (newval != '-' && newval != '.' && newval != '-.' && newval != parseFloat(newval)) {
                    newval = '';
                }
                displayVal = newval;
                if (LEMradix === ',') {
                    displayVal = displayVal.split('.').join(',');
                }
                if (name.match(/other\$/)) {
                    \$('#answer'+name+'text').val(displayVal);
                }
                \$('#answer'+name).val(displayVal);

                if (typeof evt_type === 'undefined')
                {
                    evt_type = 'onchange';
                }
                checkconditions(newval, name, type, evt_type);
            }

            function checkconditions(value, name, type, evt_type)
            {
                if (typeof evt_type === 'undefined')
                {
                    evt_type = 'onchange';
                }
                if (type == 'radio' || type == 'select-one')
                {
                    \$('#java'+name).val(value);
                }
                else if (type == 'checkbox')
                {
                    if (\$('#answer'+name).is(':checked'))
                    {
                        \$('#java'+name).val('Y');
                    } else
                    {
                        \$('#java'+name).val('');
                    }
                }
                else if (type == 'text' && name.match(/other\$/))
                {
                    \$('#java'+name).val(value);
                }
                ExprMgr_process_relevance_and_tailoring(evt_type,name,type);
END;
        if ($previewgrp) {
            // force the group to be visible, even if irrelevant - will not always work
            print <<<END
    \$('#relevanceG' + LEMgseq).val(1);
    \$(document).ready(function() {
        \$('#group-' + LEMgseq).show();
    });
    \$(document).change(function() {
        \$('#group-' + LEMgseq).show();
    });
    \$(document).bind('keydown',function(e) {
                if (e.keyCode == 9) {
                    \$('#group-' + LEMgseq).show();
                    return true;
                }
                return true;
            });

END;
        }
        print <<<END
            }
        // -->
        </script>
END;
        //Display the "mandatory" message on page if necessary
        if (isset($showpopups) && $showpopups == 0 && $stepInfo['mandViolation'] && $okToShowErrors) {
            echo "<p><span class='errormandatory'>" . $clang->gT("One or more mandatory questions have not been answered. You cannot proceed until these have been completed.") . "</span></p>";
        }
        //Display the "validation" message on page if necessary
        if (isset($showpopups) && $showpopups == 0 && !$stepInfo['valid'] && $okToShowErrors) {
            echo "<p><span class='errormandatory'>" . $clang->gT("One or more questions have not been answered in a valid manner. You cannot proceed until these answers are valid.") . "</span></p>";
        }
        //Display the "file validation" message on page if necessary
        if (isset($showpopups) && $showpopups == 0 && isset($filenotvalidated) && $filenotvalidated == true && $okToShowErrors) {
            echo "<p><span class='errormandatory'>" . $clang->gT("One or more uploaded files are not in proper format/size. You cannot proceed until these files are valid.") . "</span></p>";
        }
        $_gseq = -1;
        foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
            $gid = $gl[0];
            ++$_gseq;
            $groupname = $gl[1];
            $groupdescription = $gl[2];
            if ($surveyMode != 'survey' && $gid != $onlyThisGID) {
                continue;
            }
            $redata = compact(array_keys(get_defined_vars()));
            echo "\n\n<!-- START THE GROUP -->\n";
            echo "\n\n<div id='group-{$_gseq}'";
            $gnoshow = LimeExpressionManager::GroupIsIrrelevantOrHidden($_gseq);
            if ($gnoshow && !$previewgrp) {
                echo " style='display: none;'";
            }
            echo ">\n";
            echo templatereplace(file_get_contents($sTemplatePath . "startgroup.pstpl"), array(), $redata);
            echo "\n";
            if (!$previewquestion) {
                echo templatereplace(file_get_contents($sTemplatePath . "groupdescription.pstpl"), array(), $redata);
            }
            echo "\n";
            echo "\n\n<!-- PRESENT THE QUESTIONS -->\n";
            foreach ($qanda as $qa) {
                if ($gid != $qa[6]) {
                    continue;
                }
                $qid = $qa[4];
                $qinfo = LimeExpressionManager::GetQuestionStatus($qid);
                $lastgrouparray = explode("X", $qa[7]);
                $lastgroup = $lastgrouparray[0] . "X" . $lastgrouparray[1];
                // id of the last group, derived from question id
                $lastanswer = $qa[7];
                $q_class = getQuestionClass($qinfo['info']['type']);
                $man_class = '';
                if ($qinfo['info']['mandatory'] == 'Y') {
                    $man_class .= ' mandatory';
                }
                if ($qinfo['anyUnanswered'] && $_SESSION[$LEMsessid]['maxstep'] != $_SESSION[$LEMsessid]['step']) {
                    $man_class .= ' missing';
                }
                $n_q_display = '';
                if ($qinfo['hidden'] && $qinfo['info']['type'] != '*') {
                    continue;
                    // skip this one
                }
                if (!$qinfo['relevant'] || $qinfo['hidden'] && $qinfo['info']['type'] == '*') {
                    $n_q_display = ' style="display: none;"';
                }
                $question = $qa[0];
                //===================================================================
                // The following four variables offer the templating system the
                // capacity to fully control the HTML output for questions making the
                // above echo redundant if desired.
                $question['essentials'] = 'id="question' . $qa[4] . '"' . $n_q_display;
                $question['class'] = $q_class;
                $question['man_class'] = $man_class;
                $question['code'] = $qa[5];
                $question['sgq'] = $qa[7];
                $question['aid'] = !empty($qinfo['info']['aid']) ? $qinfo['info']['aid'] : 0;
                $question['sqid'] = !empty($qinfo['info']['sqid']) ? $qinfo['info']['sqid'] : 0;
                $question['type'] = $qinfo['info']['type'];
                //===================================================================
                $answer = $qa[1];
                $help = $qinfo['info']['help'];
                // $qa[2];
                $redata = compact(array_keys(get_defined_vars()));
                $question_template = file_get_contents($sTemplatePath . 'question.pstpl');
                if (preg_match('/\\{QUESTION_ESSENTIALS\\}/', $question_template) === false || preg_match('/\\{QUESTION_CLASS\\}/', $question_template) === false) {
                    // if {QUESTION_ESSENTIALS} is present in the template but not {QUESTION_CLASS} remove it because you don't want id="" and display="" duplicated.
                    $question_template = str_replace('{QUESTION_ESSENTIALS}', '', $question_template);
                    $question_template = str_replace('{QUESTION_CLASS}', '', $question_template);
                    echo '
                    <!-- NEW QUESTION -->
                    <div id="question' . $qa[4] . '" class="' . $q_class . $man_class . '"' . $n_q_display . '>';
                    echo templatereplace($question_template, array(), $redata, false, false, $qa[4]);
                    echo '</div>';
                } else {
                    // TMSW - eventually refactor so that only substitutes the QUESTION_** fields - doesn't need full power of template replace
                    // TMSW - also, want to return a string, and call templatereplace once on that result string once all done.
                    echo templatereplace($question_template, array(), $redata, false, false, $qa[4]);
                }
            }
            if ($surveyMode == 'group') {
                echo "<input type='hidden' name='lastgroup' value='{$lastgroup}' id='lastgroup' />\n";
                // for counting the time spent on each group
            }
            if ($surveyMode == 'question') {
                echo "<input type='hidden' name='lastanswer' value='{$lastanswer}' id='lastanswer' />\n";
            }
            echo "\n\n<!-- END THE GROUP -->\n";
            echo templatereplace(file_get_contents($sTemplatePath . "endgroup.pstpl"), array(), $redata);
            echo "\n\n</div>\n";
        }
        LimeExpressionManager::FinishProcessingGroup($LEMskipReprocessing);
        echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
        LimeExpressionManager::FinishProcessingPage();
        if (!$previewgrp && !$previewquestion) {
            $navigator = surveymover();
            //This gets globalised in the templatereplace function
            $redata = compact(array_keys(get_defined_vars()));
            echo "\n\n<!-- PRESENT THE NAVIGATOR -->\n";
            echo templatereplace(file_get_contents($sTemplatePath . "navigator.pstpl"), array(), $redata);
            echo "\n";
            if ($thissurvey['active'] != "Y") {
                echo "<p style='text-align:center' class='error'>" . $clang->gT("This survey is currently not active. You will not be able to save your responses.") . "</p>\n";
            }
            if ($surveyMode != 'survey' && $thissurvey['allowjumps'] == 'Y') {
                echo "\n\n<!-- PRESENT THE INDEX -->\n";
                echo '<div id="index"><div class="container"><h2>' . $clang->gT("Question index") . '</h2>';
                $stepIndex = LimeExpressionManager::GetStepIndexInfo();
                $lastGseq = -1;
                $gseq = -1;
                $grel = true;
                for ($v = 0, $n = 0; $n != $_SESSION[$LEMsessid]['maxstep']; ++$n) {
                    if (!isset($stepIndex[$n])) {
                        continue;
                        // this is an invalid group - skip it
                    }
                    $stepInfo = $stepIndex[$n];
                    if ($surveyMode == 'question') {
                        if ($lastGseq != $stepInfo['gseq']) {
                            // show the group label
                            ++$gseq;
                            $g = $_SESSION[$LEMsessid]['grouplist'][$gseq];
                            $grel = !LimeExpressionManager::GroupIsIrrelevantOrHidden($gseq);
                            if ($grel) {
                                $gtitle = LimeExpressionManager::ProcessString($g[1]);
                                echo '<h3>' . flattenText($gtitle) . "</h3>";
                            }
                            $lastGseq = $stepInfo['gseq'];
                        }
                        if (!$grel || !$stepInfo['show']) {
                            continue;
                        }
                        $q = $_SESSION[$LEMsessid]['fieldarray'][$n];
                    } else {
                        ++$gseq;
                        if (!$stepInfo['show']) {
                            continue;
                        }
                        $g = $_SESSION[$LEMsessid]['grouplist'][$gseq];
                    }
                    if ($surveyMode == 'group') {
                        $indexlabel = LimeExpressionManager::ProcessString($g[1]);
                    } else {
                        $indexlabel = LimeExpressionManager::ProcessString($q[3]);
                    }
                    $sText = $surveyMode == 'group' ? flattenText($indexlabel) : flattenText($indexlabel);
                    $bGAnsw = !$stepInfo['anyUnanswered'];
                    ++$v;
                    $class = $n == $_SESSION[$LEMsessid]['step'] - 1 ? 'current' : ($bGAnsw ? 'answer' : 'missing');
                    if ($v % 2) {
                        $class .= " odd";
                    }
                    $s = $n + 1;
                    echo "<div class=\"row {$class}\" onclick=\"javascript:document.limesurvey.move.value = '{$s}'; document.limesurvey.submit();\"><span class=\"hdr\">{$v}</span><span title=\"{$sText}\">{$sText}</span></div>";
                }
                if ($_SESSION[$LEMsessid]['maxstep'] == $_SESSION[$LEMsessid]['totalsteps']) {
                    echo "<input class='submit' type='submit' accesskey='l' onclick=\"javascript:document.limesurvey.move.value = 'movesubmit';\" value=' " . $clang->gT("Submit") . " ' name='move2' />\n";
                }
                echo '</div></div>';
                /* Can be replaced by php or in global js */
                echo "<script type=\"text/javascript\">\n" . "  \$(\".outerframe\").addClass(\"withindex\");\n" . "  var idx = \$(\"#index\");\n" . "  var row = \$(\"#index .row.current\");\n" . "  idx.scrollTop(row.position().top - idx.height() / 2 - row.height() / 2);\n" . "</script>\n";
                echo "\n";
            }
            echo "<input type='hidden' name='thisstep' value='{$_SESSION[$LEMsessid]['step']}' id='thisstep' />\n";
            echo "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
            echo "<input type='hidden' name='start_time' value='" . time() . "' id='start_time' />\n";
            $_SESSION[$LEMsessid]['LEMpostKey'] = mt_rand();
            echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION[$LEMsessid]['LEMpostKey']}' id='LEMpostKey' />\n";
            if (isset($token) && !empty($token)) {
                echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
            }
        }
        if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
            echo LimeExpressionManager::GetDebugTimingMessage();
        }
        if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
            echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
        }
        echo "</form>\n";
        echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
        echo "\n";
        doFooter();
    }
Esempio n. 9
0
 /**
  * dataentry::view()
  * view a dataentry
  * @param mixed $surveyid
  * @param mixed $lang
  * @return
  */
 public function view($surveyid, $lang = NULL)
 {
     $surveyid = sanitize_int($surveyid);
     $lang = isset($_GET['lang']) ? $_GET['lang'] : NULL;
     if (isset($lang)) {
         $lang = sanitize_languagecode($lang);
     }
     $aViewUrls = array();
     if (Permission::model()->hasSurveyPermission($surveyid, 'responses', 'create')) {
         $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language;
         $surveyinfo = getSurveyInfo($surveyid);
         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($slangs, $baselang);
         if (is_null($lang) || !in_array($lang, $slangs)) {
             $sDataEntryLanguage = $baselang;
         } else {
             $sDataEntryLanguage = $lang;
         }
         $langlistbox = languageDropdown($surveyid, $sDataEntryLanguage);
         $thissurvey = getSurveyInfo($surveyid);
         //This is the default, presenting a blank dataentry form
         LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $aData['thissurvey'] = $thissurvey;
         $aData['langlistbox'] = $langlistbox;
         $aData['surveyid'] = $surveyid;
         $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
         $aData['site_url'] = Yii::app()->homeUrl;
         LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl);
         // means that all variables are on the same page
         $aViewUrls[] = 'caption_view';
         Yii::app()->loadHelper('database');
         // SURVEY NAME AND DESCRIPTION TO GO HERE
         $degquery = "SELECT * FROM {{groups}} WHERE sid={$surveyid} AND language='{$sDataEntryLanguage}' ORDER BY {{groups}}.group_order";
         $degresult = dbExecuteAssoc($degquery);
         // GROUP NAME
         $aDataentryoutput = '';
         foreach ($degresult->readAll() as $degrow) {
             LimeExpressionManager::StartProcessingGroup($degrow['gid'], $thissurvey['anonymized'] != "N", $surveyid);
             $deqquery = "SELECT * FROM {{questions}} WHERE sid={$surveyid} AND parent_qid=0 AND gid={$degrow['gid']} AND language='{$sDataEntryLanguage}'";
             $deqrows = (array) dbExecuteAssoc($deqquery)->readAll();
             $aDataentryoutput .= "\t<tr class='info'>\n" . "<!-- Inside controller dataentry.php -->" . "<td colspan='3'><h4>" . flattenText($degrow['group_name'], true) . "</h4></td>\n" . "\t</tr>\n";
             $gid = $degrow['gid'];
             $aDataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n";
             // Perform a case insensitive natural sort on group name then question title of a multidimensional array
             usort($deqrows, 'groupOrderThenQuestionOrder');
             $bgc = 'odd';
             foreach ($deqrows as $deqrow) {
                 $cdata = array();
                 $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                 $cdata['qidattributes'] = $qidattributes;
                 $hidden = isset($qidattributes['hidden']) ? $qidattributes['hidden'] : 0;
                 // TODO - can questions be hidden?  Are JavaScript variables names used?  Consistently with everywhere else?
                 //                    LimeExpressionManager::ProcessRelevance($qidattributes['relevance'],$deqrow['qid'],NULL,$deqrow['type'],$hidden);
                 // TMSW Condition->Relevance:  Show relevance equation instead of conditions here - better yet, have data entry use survey-at-a-time but with different view
                 $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
                 $relevance = trim($qinfo['info']['relevance']);
                 $explanation = trim($qinfo['relEqn']);
                 $validation = trim($qinfo['prettyValidTip']);
                 $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                 $array_filter_help = flattenText($this->_array_filter_help($qidattributes, $sDataEntryLanguage, $surveyid));
                 if ($relevance != '' && $relevance != '1' || $validation != '' || $array_filter_help != '') {
                     $showme = '<div class="alert alert-warning col-sm-8 col-sm-offset-2" role="alert">';
                     if ($bgc == "even") {
                         $bgc = "odd";
                     } else {
                         $bgc = "even";
                     }
                     //Do no alternate on explanation row
                     if ($relevance != '' && $relevance != '1') {
                         $showme = '<strong>' . gT("Only answer this if the following conditions are met:", 'html', $sDataEntryLanguage) . "</strong><br />{$explanation}\n";
                     }
                     if ($validation != '') {
                         $showme .= '<strong>' . gT("The answer(s) must meet these validation criteria:", 'html', $sDataEntryLanguage) . "</strong><br />{$validation}\n";
                     }
                     if ($showme != '' && $array_filter_help != '') {
                         $showme .= '<br/>';
                     }
                     if ($array_filter_help != '') {
                         $showme .= '<strong>' . gT("The answer(s) must meet these array_filter criteria:", 'html', $sDataEntryLanguage) . "</strong><br />{$array_filter_help}\n";
                     }
                     $showme .= '</div>';
                     $cdata['explanation'] = "<tr class ='data-entry-explanation'><td class='data-entry-small-text' colspan='3' align='left'>{$showme}</td></tr>\n";
                 }
                 //END OF GETTING CONDITIONS
                 //Alternate bgcolor for different groups
                 if (!isset($bgc)) {
                     $bgc = "even";
                 }
                 if ($bgc == "even") {
                     $bgc = "odd";
                 } else {
                     $bgc = "even";
                 }
                 $qid = $deqrow['qid'];
                 $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
                 $cdata['bgc'] = $bgc;
                 $cdata['fieldname'] = $fieldname;
                 $cdata['deqrow'] = $deqrow;
                 $cdata['thissurvey'] = $thissurvey;
                 if ($deqrow['help']) {
                     $hh = addcslashes($deqrow['help'], "..'\"");
                     //Escape ASCII decimal 0-32 plus single and double quotes to make JavaScript happy.
                     $hh = htmlspecialchars($hh, ENT_QUOTES);
                     //Change & " ' < > to HTML entities to make HTML happy.
                     $cdata['hh'] = $hh;
                 }
                 switch ($deqrow['type']) {
                     case "Q":
                         //MULTIPLE SHORT TEXT
                     //MULTIPLE SHORT TEXT
                     case "K":
                         $deaquery = "SELECT question,title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         break;
                     case "1":
                         // multi scale^
                         $deaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$baselang}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$baselang}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery);
                         foreach ($oresult->readAll() as $orow) {
                             $cdata['fother'] = $orow['other'];
                         }
                         break;
                     case "L":
                         //LIST drop-down/radio-button list
                     //LIST drop-down/radio-button list
                     case "!":
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         if ($deqrow['type'] == '!' && trim($qidattributes['category_separator']) != '') {
                             $optCategorySeparator = $qidattributes['category_separator'];
                         } else {
                             unset($optCategorySeparator);
                         }
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname' class='form-control' >\n";
                         $aDatatemp = '';
                         if (!isset($optCategorySeparator)) {
                             foreach ($dearesult->readAll() as $dearow) {
                                 $aDatatemp .= "<option value='{$dearow['code']}'";
                                 //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$dearow['answer']}</option>\n";
                             }
                         } else {
                             $defaultopts = array();
                             $optgroups = array();
                             foreach ($dearesult->readAll() as $dearow) {
                                 list($categorytext, $answertext) = explode($optCategorySeparator, $dearow['answer']);
                                 if ($categorytext == '') {
                                     $defaultopts[] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 } else {
                                     $optgroups[$categorytext][] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 }
                             }
                             foreach ($optgroups as $categoryname => $optionlistarray) {
                                 $aDatatemp .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n";
                                 foreach ($optionlistarray as $optionarray) {
                                     $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                     //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                     $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                                 }
                                 $aDatatemp .= "</optgroup>\n";
                             }
                             foreach ($defaultopts as $optionarray) {
                                 $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                 //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                             }
                         }
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />");
                         foreach ($oresult->readAll() as $orow) {
                             $fother = $orow['other'];
                         }
                         $cdata['fother'] = $fother;
                         $cdata['defexists'] = $defexists;
                         $cdata['datatemp'] = $aDatatemp;
                         break;
                     case "O":
                         //LIST WITH COMMENT drop-down/radio-button list + textarea
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname'>\n";
                         $aDatatemp = '';
                         foreach ($dearesult->readAll() as $dearow) {
                             $aDatatemp .= "<option value='{$dearow['code']}'";
                             //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                             $aDatatemp .= ">{$dearow['answer']}</option>\n";
                         }
                         $cdata['datatemp'] = $aDatatemp;
                         $cdata['defexists'] = $defexists;
                         break;
                     case "R":
                         //RANKING TYPE QUESTION
                         $thisqid = $deqrow['qid'];
                         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$thisqid} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $ansresult = dbExecuteAssoc($ansquery);
                         $ansresult = $ansresult->readAll();
                         $anscount = count($ansresult);
                         $cdata['thisqid'] = $thisqid;
                         $cdata['anscount'] = $anscount;
                         $ansresult = Yii::app()->db->createCommand($ansquery)->query()->readAll();
                         //Checked
                         $anscount = count($ansresult);
                         $answers = array();
                         foreach ($ansresult as $ansrow) {
                             $answers[] = $ansrow;
                         }
                         $cdata['answers'] = $answers;
                         App()->getClientScript()->registerPackage('jquery-actual');
                         $this->registerScriptFile('SCRIPT_PATH', 'ranking.js');
                         $this->registerCssFile('PUBLIC', 'ranking.css');
                         unset($answers);
                         break;
                     case "M":
                         //Multiple choice checkbox (Quite tricky really!)
                         if (trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         $meacount = count($cdata['mearesult']);
                         $cdata['meacount'] = $meacount;
                         $cdata['dcols'] = $dcols;
                         break;
                     case "I":
                         //Language Switch
                         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                         $sbaselang = Survey::model()->findByPk($surveyid)->language;
                         array_unshift($slangs, $sbaselang);
                         $cdata['slangs'] = $slangs;
                         break;
                     case "P":
                         //Multiple choice with comments checkbox + text
                         //$aDataentryoutput .= "<table border='0'>\n";
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order, question";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "|":
                         //                            $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                         $cdata['qidattributes'] = $qidattributes;
                         $maxfiles = $qidattributes['max_num_of_files'];
                         $cdata['maxfiles'] = $maxfiles;
                         break;
                     case "A":
                         //ARRAY (5 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "B":
                         //ARRAY (10 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                     case "C":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "E":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ":":
                         //ARRAY (Multi Flexi)
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         $minvalue = 1;
                         $maxvalue = 10;
                         if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                             $maxvalue = $qidattributes['multiflexible_max'];
                             $minvalue = 1;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                             $minvalue = $qidattributes['multiflexible_min'];
                             $maxvalue = $qidattributes['multiflexible_min'] + 10;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                             if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                                 $minvalue = $qidattributes['multiflexible_min'];
                                 $maxvalue = $qidattributes['multiflexible_max'];
                             }
                         }
                         if (trim($qidattributes['multiflexible_step']) != '') {
                             $stepvalue = $qidattributes['multiflexible_step'];
                         } else {
                             $stepvalue = 1;
                         }
                         if ($qidattributes['multiflexible_checkbox'] != 0) {
                             $minvalue = 0;
                             $maxvalue = 1;
                             $stepvalue = 1;
                         }
                         $cdata['minvalue'] = $minvalue;
                         $cdata['maxvalue'] = $maxvalue;
                         $cdata['stepvalue'] = $stepvalue;
                         $lquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=1 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $lresult = dbExecuteAssoc($lquery);
                         if (!$lresult) {
                             $eMessage = "Couldn't get labels, Type \":\"<br />{$lquery}<br />";
                             Yii::app()->setFlashMessage($eMessage);
                             $this->getController()->redirect($this->getController()->createUrl("/admin/"));
                         }
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=0 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         if (!$mearesult) {
                             $eMessage = "Couldn't get answers, Type \":\"<br />{$meaquery}<br />";
                             Yii::app()->setFlashMessage($eMessage);
                             $this->getController()->redirect($this->getController()->createUrl("/admin/"));
                         }
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ";":
                         //ARRAY (Multi Flexi)
                         $lquery = "SELECT * FROM {{questions}} WHERE scale_id=1 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT * FROM {{questions}} WHERE scale_id=0 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "F":
                         //ARRAY (Flexible Labels)
                     //ARRAY (Flexible Labels)
                     case "H":
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         $fquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY sortorder, code";
                         $fresult = dbExecuteAssoc($fquery);
                         $cdata['fresult'] = $fresult->readAll();
                         break;
                 }
                 $cdata['sDataEntryLanguage'] = $sDataEntryLanguage;
                 $viewdata = $this->getController()->renderPartial("/admin/dataentry/content_view", $cdata, TRUE);
                 $viewdata_em = LimeExpressionManager::ProcessString($viewdata, $deqrow['qid'], NULL, false, 1, 1);
                 $aDataentryoutput .= $viewdata_em;
             }
             LimeExpressionManager::FinishProcessingGroup();
         }
         LimeExpressionManager::FinishProcessingPage();
         $aDataentryoutput .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
         $aViewUrls['output'] = $aDataentryoutput;
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $surveyid;
         $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
         if ($thissurvey['active'] == "Y" && $thissurvey['allowsave'] == "Y") {
             $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
             $sbaselang = Survey::model()->findByPk($surveyid)->language;
             array_unshift($slangs, $sbaselang);
             $aData['slangs'] = $slangs;
             $aData['baselang'] = $baselang;
         }
         $aViewUrls[] = 'active_html_view';
         $aData['sidemenu']['state'] = false;
         $aData['menu']['edition'] = true;
         $aData['menu']['save'] = true;
         $aData['menu']['close'] = true;
         $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData);
     }
 }
Esempio n. 10
0
function do_array_dual($ia)
{
    global $thissurvey;
    global $notanswered;
    $repeatheadings = Yii::app()->getConfig("repeatheadings");
    $minrepeatheadings = Yii::app()->getConfig("minrepeatheadings");
    $extraclass = "";
    $answertypeclass = "";
    // Maybe not
    $clang = Yii::app()->lang;
    $checkconditionFunction = "checkconditions";
    $inputnames = array();
    $labelans1 = array();
    $labelans = array();
    $qquery = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "'";
    $other = dbExecuteAssoc($qquery)->read();
    $other = reset($other);
    //Checked
    $lquery = "SELECT * FROM {{answers}} WHERE scale_id=0 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code";
    $lquery1 = "SELECT * FROM {{answers}} WHERE scale_id=1 AND qid={$ia[0]} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY sortorder, code";
    $aQuestionAttributes = getQuestionAttributeValues($ia[0], $ia[4]);
    if ($aQuestionAttributes['use_dropdown'] == 1) {
        $useDropdownLayout = true;
        $extraclass .= " dropdown-list";
        $answertypeclass .= " dropdown";
    } else {
        $useDropdownLayout = false;
        $extraclass .= " radio-list";
        $answertypeclass .= " radio";
    }
    if (ctype_digit(trim($aQuestionAttributes['repeat_headings'])) && trim($aQuestionAttributes['repeat_headings'] != "")) {
        $repeatheadings = intval($aQuestionAttributes['repeat_headings']);
        $minrepeatheadings = 0;
    }
    if (trim($aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $leftheader = $clang->gT($aQuestionAttributes['dualscale_headerA'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]);
    } else {
        $leftheader = '';
    }
    if (trim($aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
        $rightheader = $clang->gT($aQuestionAttributes['dualscale_headerB'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]);
    } else {
        $rightheader = '';
    }
    $lresult = dbExecuteAssoc($lquery);
    //Checked
    $aAnswersScale1 = $lresult->readAll();
    if ($useDropdownLayout === false && count($aAnswersScale1) > 0) {
        if (trim($aQuestionAttributes['answer_width']) != '') {
            $answerwidth = $aQuestionAttributes['answer_width'];
        } else {
            $answerwidth = 20;
        }
        $columnswidth = 100 - $answerwidth;
        foreach ($aAnswersScale1 as $lrow) {
            $labelans[] = $lrow['answer'];
            $labelcode[] = $lrow['code'];
        }
        $lresult1 = dbExecuteAssoc($lquery1);
        //Checked
        foreach ($lresult1->readAll() as $lrow1) {
            $labelans1[] = $lrow1['answer'];
            $labelcode1[] = $lrow1['code'];
        }
        $numrows = count($labelans) + count($labelans1);
        if ($ia[6] != "Y" && SHOW_NO_ANSWER == 1) {
            $numrows++;
        }
        $cellwidth = $columnswidth / $numrows;
        $cellwidth = sprintf("%02d", $cellwidth);
        $sQuery = "SELECT count(question) FROM {{questions}} WHERE parent_qid=" . $ia[0] . " and scale_id=0 AND question like '%|%'";
        $iCount = Yii::app()->db->createCommand($sQuery)->queryScalar();
        $right_exists = $iCount > 0;
        // $right_exists is a flag to find out if there are any right hand answer parts. If there aren't we can leave out the right td column
        if ($aQuestionAttributes['random_order'] == 1) {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom();
        } else {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY question_order";
        }
        $ansresult = dbExecuteAssoc($ansquery);
        //Checked
        $aQuestionsRight = $ansresult->readAll();
        $anscount = count($aQuestionsRight);
        $fn = 1;
        // unselect second scale when using "no answer"
        $answer = "<script type='text/javascript'>\n" . "<!--\n" . "function noanswer_checkconditions(value, name, type)\n" . "{\n" . "\tvar vname;\n" . "\tvname = name.replace(/#.*\$/,\"\");\n" . "\t\$('input[name^=\"' + vname + '\"]').attr('checked',false);\n" . "\t\$('input[id=\"answer' + vname + '#0-\"]').attr('checked',true);\n" . "\t\$('input[name^=\"java' + vname + '\"]').val('');\n" . "\t{$checkconditionFunction}(value, name, type);\n" . "}\n" . "function secondlabel_checkconditions(value, name, type)\n" . "{\n" . "\tvar vname;\n" . "\tvname = \"answer\"+name.replace(/#1/g,\"#0-\");\n" . "\tif(document.getElementById(vname))\n" . "\t{\n" . "\tdocument.getElementById(vname).checked=false;\n" . "\t}\n" . "\t{$checkconditionFunction}(value, name, type);\n" . "}\n" . " //-->\n" . " </script>\n";
        // Header row and colgroups
        $mycolumns = "\t<colgroup class=\"col-responses group-1\">\n" . "\t<col class=\"col-answers\" width=\"{$answerwidth}%\" />\n";
        $answer_head_line = "\t<th class=\"header_answer_text\">&nbsp;</th>\n\n";
        $odd_even = '';
        foreach ($labelans as $ld) {
            $answer_head_line .= "\t<th>" . $ld . "</th>\n";
            $odd_even = alternation($odd_even);
            $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n";
        }
        $mycolumns .= "\t</colgroup>\n";
        if (count($labelans1) > 0) {
            $mycolumns .= "\t<colgroup class=\"col-responses group-2\">\n" . "\t<col class=\"seperator\" />\n";
            $answer_head_line .= "\n\t<td class=\"header_separator\">&nbsp;</td>\n\n";
            // Separator
            foreach ($labelans1 as $ld) {
                $answer_head_line .= "\t<th>" . $ld . "</th>\n";
                $odd_even = alternation($odd_even);
                $mycolumns .= "<col class=\"{$odd_even}\" width=\"{$cellwidth}%\" />\n";
            }
        }
        if ($right_exists) {
            $answer_head_line .= "\t<td class=\"header_answer_text_right\">&nbsp;</td>\n";
            $mycolumns .= "\n\t<col class=\"answertextright\" />\n\n";
        }
        if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
            $answer_head_line .= "\t<td class=\"header_separator\">&nbsp;</td>\n";
            // Separator
            $answer_head_line .= "\t<th class=\"header_no_answer\">" . $clang->gT('No answer') . "</th>\n";
            $odd_even = alternation($odd_even);
            $mycolumns .= "\n\t<col class=\"seperator\" />\n\n";
            $mycolumns .= "\t<col class=\"col-no-answer {$odd_even}\" width=\"{$cellwidth}%\" />\n";
        }
        $mycolumns .= "\t</colgroup>\n";
        $answer_head2 = "\n<tr class=\"array1 header_row\">\n" . $answer_head_line . "</tr>\n";
        // build first row of header if needed
        if ($leftheader != '' || $rightheader != '') {
            $answer_head1 = "<tr class=\"array1 groups header_row\">\n" . "\t<th class=\"header_answer_text\">&nbsp;</th>\n" . "\t<th colspan=\"" . count($labelans) . "\" class=\"dsheader\">{$leftheader}</th>\n";
            if (count($labelans1) > 0) {
                $answer_head1 .= "\t<td class=\"header_separator\">&nbsp;</td>\n" . "\t<th colspan=\"" . count($labelans1) . "\" class=\"dsheader\">{$rightheader}</th>\n";
            }
            if ($right_exists) {
                $answer_head1 .= "\t<td class=\"header_answer_text_right\">&nbsp;</td>\n";
            }
            if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
                $answer_head1 .= "\t<td class=\"header_separator\">&nbsp;</td>\n";
                // Separator
                $answer_head1 .= "\t<th class=\"header_no_answer\">&nbsp;</th>\n";
            }
            $answer_head1 .= "</tr>\n";
        } else {
            $answer_head1 = '';
        }
        $answer .= "\n<table class=\"question subquestions-list questions-list\" summary=\"" . str_replace('"', '', strip_tags($ia[3])) . " - a dual array type question\">\n" . $mycolumns . "\n\t<thead>\n" . $answer_head1 . $answer_head2 . "\n\t</thead>\n" . "<tbody>\n";
        $trbc = '';
        foreach ($aQuestionsRight as $ansrow) {
            // Build repeat headings if needed
            if (isset($repeatheadings) && $repeatheadings > 0 && $fn - 1 > 0 && ($fn - 1) % $repeatheadings == 0) {
                if ($anscount - $fn + 1 >= $minrepeatheadings) {
                    $answer .= "</tbody>\n<tbody>";
                    // Close actual body and open another one
                    //$answer .= $answer_head1;
                    $answer .= "\n<tr class=\"repeat headings\">\n" . $answer_head_line . "</tr>\n";
                }
            }
            $trbc = alternation($trbc, 'row');
            $answertext = dTexts__run($ansrow['question']);
            $answertextsave = $answertext;
            $dualgroup = 0;
            $myfname0 = $ia[1] . $ansrow['title'];
            $myfname = $ia[1] . $ansrow['title'] . '#0';
            $myfname1 = $ia[1] . $ansrow['title'] . '#1';
            // new multi-scale-answer
            /* Check if this item has not been answered: the 'notanswered' variable must be an array,
               containing a list of unanswered questions, the current question must be in the array,
               and there must be no answer available for the item in this session. */
            if ($ia[6] == 'Y' && is_array($notanswered) && (array_search($myfname, $notanswered) !== FALSE || array_search($myfname1, $notanswered) !== FALSE) && ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '' || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == '')) {
                $answertext = "<span class='errormandatory'>{$answertext}</span>";
            }
            // Get array_filter stuff
            list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname0, $trbc, $myfname, "tr", "{$trbc} answers-list radio-list");
            $answer .= $htmltbody2;
            if (strpos($answertext, '|')) {
                $answertext = substr($answertext, 0, strpos($answertext, '|'));
            }
            array_push($inputnames, $myfname);
            $answer .= "\t<th class=\"answertext\">\n" . $hiddenfield . "{$answertext}\n" . "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\"";
            if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
            }
            $answer .= "\" />\n\t</th>\n";
            $hiddenanswers = '';
            $thiskey = 0;
            foreach ($labelcode as $ld) {
                $answer .= "\t<td class=\"answer_cell_1_00{$ld} answer-item {$answertypeclass}-item\">\n" . "<label for=\"answer{$myfname}-{$ld}\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname}\" value=\"{$ld}\" id=\"answer{$myfname}-{$ld}\" title=\"" . HTMLEscape(strip_tags($labelans[$thiskey])) . '"';
                if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $ld) {
                    $answer .= CHECKED;
                }
                // --> START NEW FEATURE - SAVE
                $answer .= " onclick=\"{$checkconditionFunction}(this.value, this.name, this.type)\" />\n</label>\n";
                // --> END NEW FEATURE - SAVE
                $answer .= "\n\t</td>\n";
                $thiskey++;
            }
            if (count($labelans1) > 0) {
                $dualgroup++;
                $hiddenanswers = '';
                $answer .= "\t<td class=\"dual_scale_separator information-item\">&nbsp;</td>\n";
                // separator
                array_push($inputnames, $myfname1);
                $hiddenanswers .= "<input type=\"hidden\" name=\"java{$myfname1}\" id=\"java{$myfname1}\" value=\"";
                if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1])) {
                    $hiddenanswers .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1];
                }
                $hiddenanswers .= "\" />\n";
                $thiskey = 0;
                foreach ($labelcode1 as $ld) {
                    $answer .= "\t<td class=\"answer_cell_2_00{$ld}  answer-item radio-item\">\n";
                    if ($hiddenanswers != '') {
                        $answer .= $hiddenanswers;
                        $hiddenanswers = '';
                    }
                    $answer .= "<label for=\"answer{$myfname1}-{$ld}\">\n" . "\t<input class=\"radio\" type=\"radio\" name=\"{$myfname1}\" value=\"{$ld}\" id=\"answer{$myfname1}-{$ld}\" title=\"" . HTMLEscape(strip_tags($labelans1[$thiskey])) . '"';
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == $ld) {
                        $answer .= CHECKED;
                    }
                    // --> START NEW FEATURE - SAVE
                    $answer .= " onclick=\"secondlabel_checkconditions(this.value, this.name, this.type)\" />\n</label>\n";
                    // --> END NEW FEATURE - SAVE
                    $answer .= "\t</td>\n";
                    $thiskey++;
                }
            }
            if (strpos($answertextsave, '|')) {
                $answertext = substr($answertextsave, strpos($answertextsave, '|') + 1);
                $answer .= "\t<td class=\"answertextright\">{$answertext}</td>\n";
                $hiddenanswers = '';
            } elseif ($right_exists) {
                $answer .= "\t<td class=\"answertextright\">&nbsp;</td>\n";
            }
            if ($ia[6] != "Y" && SHOW_NO_ANSWER == 1) {
                $answer .= "\t<td class=\"dual_scale_separator information-item\">&nbsp;</td>\n";
                // separator
                $answer .= "\t<td class=\"dual_scale_no_answer answer-item radio-item noanswer-item\">\n" . "<label for='answer{$myfname}-'>\n" . "\t<input class='radio' type='radio' name='{$myfname}' value='' id='answer{$myfname}-' title='" . $clang->gT("No answer") . "'";
                if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == "") {
                    $answer .= CHECKED;
                }
                // --> START NEW FEATURE - SAVE
                $answer .= " onclick=\"noanswer_checkconditions(this.value, this.name, this.type)\" />\n" . "</label>\n" . "\t</td>\n";
                // --> END NEW FEATURE - SAVE
            }
            $answer .= "</tr>\n";
            // $inputnames[]=$myfname;
            //IF a MULTIPLE of flexi-redisplay figure, repeat the headings
            $fn++;
        }
        $answer .= "\t</tbody>\n";
        $answer .= "</table>\n";
    } elseif ($useDropdownLayout === true && count($aAnswersScale1) > 0) {
        if (trim($aQuestionAttributes['answer_width']) != '') {
            $answerwidth = $aQuestionAttributes['answer_width'];
        } else {
            $answerwidth = 20;
        }
        $separatorwidth = (100 - $answerwidth) / 10;
        $columnswidth = 100 - $answerwidth - $separatorwidth * 2;
        $answer = "";
        // Get Answers
        //question atribute random_order set?
        if ($aQuestionAttributes['random_order'] == 1) {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} and scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY " . dbRandom();
        } else {
            $ansquery = "SELECT * FROM {{questions}} WHERE parent_qid={$ia['0']} and scale_id=0 AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ORDER BY question_order";
        }
        $ansresult = dbExecuteAssoc($ansquery);
        $aSubquestions = $ansresult->readAll();
        //Checked
        $anscount = count($aSubquestions);
        if ($anscount == 0) {
            $inputnames = array();
            $answer .= "\n<p class=\"error\">" . $clang->gT('Error: This question has no answers.') . "</p>\n";
        } else {
            //already done $lresult = dbExecuteAssoc($lquery);
            foreach ($aAnswersScale1 as $lrow) {
                $labels0[] = array('code' => $lrow['code'], 'title' => $lrow['answer']);
            }
            $lresult1 = dbExecuteAssoc($lquery1);
            //Checked
            foreach ($lresult1->readAll() as $lrow1) {
                $labels1[] = array('code' => $lrow1['code'], 'title' => $lrow1['answer']);
            }
            // Get attributes for Headers and Prefix/Suffix
            if (trim($aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
                list($ddprefix, $ddsuffix) = explode("|", $aQuestionAttributes['dropdown_prepostfix'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]);
                $ddprefix = $ddprefix;
                $ddsuffix = $ddsuffix;
            } else {
                $ddprefix = '';
                $ddsuffix = '';
            }
            if (trim($aQuestionAttributes['dropdown_separators']) != '') {
                list($postanswSep, $interddSep) = explode('|', $aQuestionAttributes['dropdown_separators']);
                $postanswSep = $postanswSep;
                $interddSep = $interddSep;
            } else {
                $postanswSep = '';
                $interddSep = '';
            }
            $colspan_1 = '';
            $colspan_2 = '';
            $suffix_cell = '';
            $answer .= "\n<table class=\"question subquestion-list questions-list dropdown-list\" summary=\"" . str_replace('"', '', strip_tags($ia[3])) . " - an dual array type question\">\n\n" . "\t<col class=\"answertext\" width=\"{$answerwidth}%\" />\n";
            if ($ddprefix != '') {
                $answer .= "\t<col class=\"ddprefix\" />\n";
                $colspan_1 = ' colspan="2"';
            }
            $answer .= "\t<col class=\"dsheader\" />\n";
            if ($ddsuffix != '') {
                $answer .= "\t<col class=\"ddsuffix\" />\n";
                if (!empty($colspan_1)) {
                    $colspan_2 = ' colspan="3"';
                }
                $suffix_cell = "\t<td>&nbsp;</td>\n";
                // suffix
            }
            $answer .= "\t<col class=\"ddarrayseparator\" width=\"{$separatorwidth}%\" />\n";
            if ($ddprefix != '') {
                $answer .= "\t<col class=\"ddprefix\" />\n";
            }
            $answer .= "\t<col class=\"dsheader\" />\n";
            if ($ddsuffix != '') {
                $answer .= "\t<col class=\"ddsuffix\" />\n";
            }
            // headers
            $answer .= "\n\t<thead>\n" . "<tr>\n" . "\t<td{$colspan_1}>&nbsp;</td>\n" . "\n" . "\t<th>{$leftheader}</th>\n" . "\n" . "\t<td{$colspan_2}>&nbsp;</td>\n" . "\t<th>{$rightheader}</th>\n" . $suffix_cell . "</tr>\n" . "\t</thead>\n\n";
            $answer .= "\n<tbody>\n";
            $trbc = '';
            foreach ($aSubquestions as $ansrow) {
                $rowname = $ia[1] . $ansrow['title'];
                $dualgroup = 0;
                $myfname = $ia[1] . $ansrow['title'] . "#" . $dualgroup;
                $dualgroup1 = 1;
                $myfname1 = $ia[1] . $ansrow['title'] . "#" . $dualgroup1;
                if ($ia[6] == 'Y' && is_array($notanswered) && (array_search($myfname, $notanswered) !== FALSE || array_search($myfname1, $notanswered) !== FALSE) && ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '' || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == '')) {
                    $answertext = "<span class='errormandatory'>" . dTexts__run($ansrow['question']) . "</span>";
                } else {
                    $answertext = dTexts__run($ansrow['question']);
                }
                $trbc = alternation($trbc, 'row');
                // Get array_filter stuff
                list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $rowname, $trbc, $myfname, "tr", "{$trbc} subquestion-list questions-list dropdown-list");
                $answer .= $htmltbody2;
                $answer .= "\t<th class=\"answertext\">\n" . "<label for=\"answer{$rowname}\">\n" . $hiddenfield . "{$answertext}\n" . "</label>\n" . "\t</th>\n";
                // Label0
                // prefix
                if ($ddprefix != '') {
                    $answer .= "\t<td class=\"ddprefix information-item\">{$ddprefix}</td>\n";
                }
                $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<select name=\"{$myfname}\" id=\"answer{$myfname}\" onchange=\"array_dual_dd_checkconditions(this.value, this.name, this.type,{$dualgroup},{$checkconditionFunction});\">\n";
                if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') {
                    $answer .= "\t<option value=\"\" " . SELECTED . '>' . $clang->gT('Please choose...') . "</option>\n";
                }
                foreach ($labels0 as $lrow) {
                    $answer .= "\t<option value=\"" . $lrow['code'] . '" ';
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == $lrow['code']) {
                        $answer .= SELECTED;
                    }
                    $answer .= '>' . flattenText($lrow['title']) . "</option>\n";
                }
                // If not mandatory and showanswer, show no ans
                if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
                    $answer .= "\t<option class=\"noanswer-item\" value=\"\" ";
                    if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == '') {
                        $answer .= SELECTED;
                    }
                    $answer .= '>' . $clang->gT('No answer') . "</option>\n";
                }
                $answer .= "</select>\n";
                // suffix
                if ($ddsuffix != '') {
                    $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n";
                }
                $answer .= "<input type=\"hidden\" name=\"java{$myfname}\" id=\"java{$myfname}\" value=\"";
                if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                    $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
                }
                $answer .= "\" />\n" . "\t</td>\n";
                $inputnames[] = $myfname;
                $answer .= "\t<td class=\"ddarrayseparator information-item\">{$interddSep}</td>\n";
                //Separator
                // Label1
                // prefix
                if ($ddprefix != '') {
                    $answer .= "\t<td class='ddprefix information-item'>{$ddprefix}</td>\n";
                }
                //				$answer .= "\t<td align='left' width='$columnswidth%'>\n"
                $answer .= "\t<td class=\"answer-item dropdown-item\">\n" . "<select name=\"{$myfname1}\" id=\"answer{$myfname1}\" onchange=\"array_dual_dd_checkconditions(this.value, this.name, this.type,{$dualgroup1},{$checkconditionFunction});\">\n";
                if (empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                    $answer .= "\t<option value=\"\"" . SELECTED . '>' . $clang->gT('Please choose...') . "</option>\n";
                }
                foreach ($labels1 as $lrow1) {
                    $answer .= "\t<option value=\"" . $lrow1['code'] . '" ';
                    if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1]) && $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1] == $lrow1['code']) {
                        $answer .= SELECTED;
                    }
                    $answer .= '>' . flattenText($lrow1['title']) . "</option>\n";
                }
                // If not mandatory and showanswer, show no ans
                if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
                    $answer .= "\t<option class=\"noanswer-item\" value='' ";
                    if (empty($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
                        $answer .= SELECTED;
                    }
                    $answer .= ">" . $clang->gT('No answer') . "</option>\n";
                }
                $answer .= "</select>\n";
                // suffix
                if ($ddsuffix != '') {
                    $answer .= "\t<td class=\"ddsuffix information-item\">{$ddsuffix}</td>\n";
                }
                $answer .= "<input type=\"hidden\" name=\"java{$myfname1}\" id=\"java{$myfname1}\" value=\"";
                if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1])) {
                    $answer .= $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname1];
                }
                $answer .= "\" />\n" . "\t</td>\n";
                $inputnames[] = $myfname1;
                $answer .= "</tr>\n";
            }
        }
        // End there are answers
        $answer .= "\t</tbody>\n";
        $answer .= "</table>\n";
    } else {
        $answer = "<p class='error'>" . $clang->gT("Error: There are no answer options for this question and/or they don't exist in this language.") . "</p>\n";
        $inputnames = "";
    }
    return array($answer, $inputnames);
}
Esempio n. 11
0
 function browse($iSurveyID)
 {
     $aData = $this->_getData($iSurveyID);
     extract($aData);
     $aViewUrls = array();
     $oBrowseLanguage = new Limesurvey_lang($aData['language']);
     //Delete Individual answer using inrow delete buttons/links - checked
     if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') != '' && Yii::app()->request->getPost('deleteanswer') != 'marked' && hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
         $iResponseID = (int) Yii::app()->request->getPost('deleteanswer');
         // sanitize the value
         // delete the files
         $this->_deleteFiles($iSurveyID, array($iResponseID), $aData['language']);
         // delete the row
         Survey_dynamic::model($iSurveyID)->deleteByPk($iResponseID);
         // delete timings if savetimings is set
         if ($aData['surveyinfo']['savetimings'] == "Y") {
             Survey_timings::model($iSurveyID)->deleteByPk($iResponseID);
         }
         Yii::app()->session['flashmessage'] = sprintf($clang->gT("Response ID %s was successfully deleted."), $iResponseID);
     }
     // Marked responses -> deal with the whole batch of marked responses
     if (Yii::app()->request->getPost('markedresponses') && count(Yii::app()->request->getPost('markedresponses')) > 0) {
         // Delete the marked responses - checked
         if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') === 'marked' && hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
             $this->_deleteFiles($iSurveyID, Yii::app()->request->getPost('markedresponses'), $aData['language']);
             foreach (Yii::app()->request->getPost('markedresponses') as $iResponseID) {
                 $iResponseID = (int) $iResponseID;
                 Survey_dynamic::model($iSurveyID)->deleteByPk($iResponseID);
                 // delete timings if savetimings is set
                 if ($aData['surveyinfo']['savetimings'] == "Y") {
                     Survey_timings::model($iSurveyID)->deleteByPk($iResponseID);
                 }
             }
             Yii::app()->session['flashmessage'] = sprintf($clang->ngT("%s response was successfully deleted.", "%s responses were successfully deleted.", count(Yii::app()->request->getPost('markedresponses'))), count(Yii::app()->request->getPost('markedresponses')));
         } else {
             if (Yii::app()->request->getPost('downloadfile') && Yii::app()->request->getPost('downloadfile') === 'marked') {
                 // Now, zip all the files in the filelist
                 $zipfilename = "Responses_for_survey_{$iSurveyID}.zip";
                 $this->_zipFiles($iSurveyID, Yii::app()->request->getPost('markedresponses'), $zipfilename, $aData['language']);
             }
         }
     } else {
         if (Yii::app()->request->getPost('downloadfile') && Yii::app()->request->getPost('downloadfile') != '' && Yii::app()->request->getPost('downloadfile') !== true) {
             // Now, zip all the files in the filelist
             $zipfilename = "Files_for_responses_" . Yii::app()->request->getPost('downloadfile') . ".zip";
             $this->_zipFiles($iSurveyID, Yii::app()->request->getPost('downloadfile'), $zipfilename, $aData['language']);
         } else {
             if (Yii::app()->request->getPost('downloadindividualfile') != '') {
                 $iId = (int) Yii::app()->request->getPost('id');
                 $downloadindividualfile = Yii::app()->request->getPost('downloadindividualfile');
                 $fieldname = Yii::app()->request->getPost('fieldname');
                 $oRow = Survey_dynamic::model($iSurveyID)->findByAttributes(array('id' => $iId));
                 $phparray = json_decode_ls($oRow->{$fieldname});
                 for ($i = 0; $i < count($phparray); $i++) {
                     if ($phparray[$i]['name'] == $downloadindividualfile) {
                         $file = Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files/" . $phparray[$i]['filename'];
                         if (file_exists($file)) {
                             header('Content-Description: File Transfer');
                             header('Content-Type: application/octet-stream');
                             header('Content-Disposition: attachment; filename="' . rawurldecode($phparray[$i]['name']) . '"');
                             header('Content-Transfer-Encoding: binary');
                             header('Expires: 0');
                             header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                             header('Pragma: public');
                             header('Content-Length: ' . filesize($file));
                             ob_clean();
                             flush();
                             readfile($file);
                             exit;
                         }
                         break;
                     }
                 }
             }
         }
     }
     /**
      * fnames is used as informational array
      * it containts
      *             $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
      */
     if (Yii::app()->request->getPost('sql')) {
         $aViewUrls[] = 'browseallfiltered_view';
     }
     //add token to top of list if survey is not private
     if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID)) {
         $fnames[] = array("token", "Token", $clang->gT("Token ID"), 0);
         $fnames[] = array("firstname", "First name", $clang->gT("First name"), 0);
         $fnames[] = array("lastname", "Last name", $clang->gT("Last name"), 0);
         $fnames[] = array("email", "Email", $clang->gT("Email"), 0);
     }
     $fnames[] = array("submitdate", $clang->gT("Completed"), $clang->gT("Completed"), "0", 'D');
     $fields = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
     foreach ($fields as $fielddetails) {
         if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate') {
             continue;
         }
         $question = $fielddetails['question'];
         if ($fielddetails['type'] != "|") {
             if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate' || $fielddetails['fieldname'] == 'token') {
                 continue;
             }
             // no headers for time data
             if ($fielddetails['type'] == 'interview_time') {
                 continue;
             }
             if ($fielddetails['type'] == 'page_time') {
                 continue;
             }
             if ($fielddetails['type'] == 'answer_time') {
                 continue;
             }
             if (isset($fielddetails['subquestion']) && $fielddetails['subquestion'] != '') {
                 $question .= ' (' . $fielddetails['subquestion'] . ')';
             }
             if (isset($fielddetails['subquestion1']) && isset($fielddetails['subquestion2'])) {
                 $question .= ' (' . $fielddetails['subquestion1'] . ':' . $fielddetails['subquestion2'] . ')';
             }
             if (isset($fielddetails['scale_id'])) {
                 $question .= '[' . $fielddetails['scale'] . ']';
             }
             $fnames[] = array($fielddetails['fieldname'], $question);
         } else {
             if ($fielddetails['aid'] !== 'filecount') {
                 $qidattributes = getQuestionAttributeValues($fielddetails['qid']);
                 for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++) {
                     if ($qidattributes['show_title'] == 1) {
                         $fnames[] = array($fielddetails['fieldname'], "File " . ($i + 1) . " - " . $fielddetails['question'] . "(Title)", "type" => "|", "metadata" => "title", "index" => $i);
                     }
                     if ($qidattributes['show_comment'] == 1) {
                         $fnames[] = array($fielddetails['fieldname'], "File " . ($i + 1) . " - " . $fielddetails['question'] . "(Comment)", "type" => "|", "metadata" => "comment", "index" => $i);
                     }
                     $fnames[] = array($fielddetails['fieldname'], "File " . ($i + 1) . " - " . $fielddetails['question'] . "(File name)", "type" => "|", "metadata" => "name", "index" => $i);
                     $fnames[] = array($fielddetails['fieldname'], "File " . ($i + 1) . " - " . $fielddetails['question'] . "(File size)", "type" => "|", "metadata" => "size", "index" => $i);
                     //$fnames[] = array($fielddetails['fieldname'], "File ".($i+1)." - ".$fielddetails['question']."(extension)", "type"=>"|", "metadata"=>"ext",     "index"=>$i);
                 }
             } else {
                 $fnames[] = array($fielddetails['fieldname'], "File count");
             }
         }
     }
     $fncount = count($fnames);
     $start = Yii::app()->request->getParam('start', 0);
     $limit = Yii::app()->request->getParam('limit', 50);
     if (!$limit) {
         $limit = 50;
     }
     $oCriteria = new CDbCriteria();
     //Create the query
     if ($aData['surveyinfo']['anonymized'] == "N" && tableExists("{{tokens_{$iSurveyID}}}")) {
         $oCriteria = Survey_dynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
     }
     if (incompleteAnsFilterState() == "incomplete") {
         $oCriteria->addCondition("submitdate IS NULL");
     } elseif (incompleteAnsFilterState() == "complete") {
         $oCriteria->addCondition("submitdate IS NOT NULL");
     }
     $dtcount = Survey_dynamic::model($iSurveyID)->count($oCriteria);
     // or die("Couldn't get response data<br />");
     if ($limit > $dtcount) {
         $limit = $dtcount;
     }
     //NOW LETS SHOW THE DATA
     if (Yii::app()->request->getPost('sql') && stripcslashes(Yii::app()->request->getPost('sql')) !== "" && Yii::app()->request->getPost('sql') != "NULL") {
         $oCriteria->addCondition(stripcslashes(Yii::app()->request->getPost('sql')));
     }
     $oCriteria->order = 'id ' . (Yii::app()->request->getParam('order') == 'desc' ? 'desc' : 'asc');
     $oCriteria->offset = $start;
     $oCriteria->limit = $limit;
     $dtresult = Survey_dynamic::model($iSurveyID)->findAllAsArray($oCriteria);
     $dtcount2 = count($dtresult);
     $cells = $fncount + 1;
     //CONTROL MENUBAR
     $last = $start - $limit;
     $next = $start + $limit;
     $end = $dtcount - $limit;
     if ($end < 0) {
         $end = 0;
     }
     if ($last < 0) {
         $last = 0;
     }
     if ($next >= $dtcount) {
         $next = $dtcount - $limit;
     }
     if ($end < 0) {
         $end = 0;
     }
     $aData['dtcount2'] = $dtcount2;
     $aData['sCompletionStateValue'] = incompleteAnsFilterState();
     $aData['start'] = $start;
     $aData['limit'] = $limit;
     $aData['last'] = $last;
     $aData['next'] = $next;
     $aData['end'] = $end;
     $aData['fncount'] = $fncount;
     $aData['fnames'] = $fnames;
     $aViewUrls[] = 'browseallheader_view';
     $bgcc = 'even';
     foreach ($dtresult as $dtrow) {
         if ($bgcc == "even") {
             $bgcc = "odd";
         } else {
             $bgcc = "even";
         }
         $aData['dtrow'] = $dtrow;
         $aData['bgcc'] = $bgcc;
         $aData['oBrowseLanguage'] = $oBrowseLanguage;
         $aViewUrls['browseallrow_view'][] = $aData;
     }
     $aViewUrls[] = 'browseallfooter_view';
     $this->_renderWrappedTemplate('', $aViewUrls, $aData);
 }
Esempio n. 12
0
 /**
  * Returns the full answer for the question that matches $fieldName
  * and the answer that matches the $answerCode.  If a match cannot
  * be made then false is returned.
  *
  * The name of the variable $answerCode is not strictly an answerCode
  * but could also be a comment entered by a participant.
  *
  * @param string $fieldName
  * @param string $answerCode
  * @param Translator $translator
  * @param string $sLanguageCode
  * @return string (or false)
  */
 public function getFullAnswer($fieldName, $answerCode, Translator $translator, $sLanguageCode)
 {
     $fullAnswer = null;
     $fieldType = $this->fieldMap[$fieldName]['type'];
     $question = $this->fieldMap[$fieldName];
     $questionId = $question['qid'];
     $answer = null;
     if ($questionId) {
         $answers = $this->getAnswers($questionId);
         if (isset($answers[$answerCode])) {
             $answer = $answers[$answerCode]['answer'];
         }
     }
     //echo "\n$fieldName: $fieldType = $answerCode";
     switch ($fieldType) {
         case 'K':
         case 'N':
             $fullAnswer = $answerCode;
             if (trim($fullAnswer) != '') {
                 if (strpos($fullAnswer, ".") !== false) {
                     $fullAnswer = rtrim(rtrim($fullAnswer, "0"), ".");
                 }
                 $qidattributes = getQuestionAttributeValues($questionId);
                 if (isset($qidattributes['num_value_int_only']) && $qidattributes['num_value_int_only']) {
                     $fullAnswer = number_format($fullAnswer, 0, '', '');
                 }
             }
             break;
         case 'R':
             //RANKING TYPE
             $fullAnswer = $answer;
             break;
         case '1':
             //Array dual scale
             if (mb_substr($fieldName, -1) == 0) {
                 $answers = $this->getAnswers($questionId, 0);
             } else {
                 $answers = $this->getAnswers($questionId, 1);
             }
             if (array_key_exists($answerCode, $answers)) {
                 $fullAnswer = $answers[$answerCode]['answer'];
             } else {
                 $fullAnswer = null;
             }
             break;
         case 'L':
             //DROPDOWN LIST
         //DROPDOWN LIST
         case '!':
             if (mb_substr($fieldName, -5, 5) == 'other') {
                 $fullAnswer = $answerCode;
             } else {
                 if ($answerCode == '-oth-') {
                     $fullAnswer = $translator->translate('Other', $sLanguageCode);
                 } else {
                     $fullAnswer = $answer;
                 }
             }
             break;
         case 'O':
             //DROPDOWN LIST WITH COMMENT
             if (isset($answer)) {
                 //This is one of the dropdown list options.
                 $fullAnswer = $answer;
             } else {
                 //This is a comment.
                 $fullAnswer = $answerCode;
             }
             break;
         case 'Y':
             //YES/NO
             switch ($answerCode) {
                 case 'Y':
                     $fullAnswer = $translator->translate('Yes', $sLanguageCode);
                     break;
                 case 'N':
                     $fullAnswer = $translator->translate('No', $sLanguageCode);
                     break;
                 default:
                     $fullAnswer = $translator->translate('N/A', $sLanguageCode);
             }
             break;
         case 'G':
             switch ($answerCode) {
                 case 'M':
                     $fullAnswer = $translator->translate('Male', $sLanguageCode);
                     break;
                 case 'F':
                     $fullAnswer = $translator->translate('Female', $sLanguageCode);
                     break;
                 default:
                     $fullAnswer = $translator->translate('N/A', $sLanguageCode);
             }
             break;
         case 'M':
             //MULTIOPTION
         //MULTIOPTION
         case 'P':
             if (mb_substr($fieldName, -5, 5) == 'other' || mb_substr($fieldName, -7, 7) == 'comment') {
                 //echo "\n -- Branch 1 --";
                 $fullAnswer = $answerCode;
             } else {
                 if ($answerCode == 'Y') {
                     $fullAnswer = $translator->translate('Yes', $sLanguageCode);
                 } elseif ($answerCode == 'N' || $answerCode === '') {
                     $fullAnswer = $translator->translate('No', $sLanguageCode);
                 } else {
                     $fullAnswer = $translator->translate('N/A', $sLanguageCode);
                 }
             }
             break;
         case 'C':
             switch ($answerCode) {
                 case 'Y':
                     $fullAnswer = $translator->translate('Yes', $sLanguageCode);
                     break;
                 case 'N':
                     $fullAnswer = $translator->translate('No', $sLanguageCode);
                     break;
                 case 'U':
                     $fullAnswer = $translator->translate('Uncertain', $sLanguageCode);
                     break;
             }
             break;
         case 'E':
             switch ($answerCode) {
                 case 'I':
                     $fullAnswer = $translator->translate('Increase', $sLanguageCode);
                     break;
                 case 'S':
                     $fullAnswer = $translator->translate('Same', $sLanguageCode);
                     break;
                 case 'D':
                     $fullAnswer = $translator->translate('Decrease', $sLanguageCode);
                     break;
             }
             break;
         case 'F':
         case 'H':
             $answers = $this->getAnswers($questionId, 0);
             $fullAnswer = isset($answers[$answerCode]) ? $answers[$answerCode]['answer'] : "";
             break;
         default:
             $fullAnswer .= $answerCode;
     }
     return $fullAnswer;
 }
Esempio n. 13
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);
 }
 /**
  * This function returns an array of the advanced attributes for the particular question
  * including their values set in the database
  *
  * @access public
  * @param int $iQuestionID  The question ID - if 0 then all settings will use the default value
  * @param string $sQuestionType  The question type
  * @param int $iSurveyID
  * @param string $sLanguage  If you give a language then only the attributes for that language are returned
  * @return array
  */
 public function getAdvancedSettingsWithValues($iQuestionID, $sQuestionType, $iSurveyID, $sLanguage = null)
 {
     if (is_null($sLanguage)) {
         $aLanguages = array_merge(array(Survey::model()->findByPk($iSurveyID)->language), Survey::model()->findByPk($iSurveyID)->additionalLanguages);
     } else {
         $aLanguages = array($sLanguage);
     }
     if ($iQuestionID != 0) {
         $aAttributeValues = getQuestionAttributeValues($iQuestionID, $sQuestionType);
     }
     $aAttributeNames = questionAttributes();
     $aAttributeNames = $aAttributeNames[$sQuestionType];
     uasort($aAttributeNames, 'categorySort');
     foreach ($aAttributeNames as $iKey => $aAttribute) {
         if ($aAttribute['i18n'] == false) {
             if (isset($aAttributeValues[$aAttribute['name']])) {
                 $aAttributeNames[$iKey]['value'] = $aAttributeValues[$aAttribute['name']];
             } else {
                 $aAttributeNames[$iKey]['value'] = $aAttribute['default'];
             }
         } else {
             foreach ($aLanguages as $sLanguage) {
                 if (isset($aAttributeValues[$aAttribute['name']][$sLanguage])) {
                     $aAttributeNames[$iKey][$sLanguage]['value'] = $aAttributeValues[$aAttribute['name']][$sLanguage];
                 } else {
                     $aAttributeNames[$iKey][$sLanguage]['value'] = $aAttribute['default'];
                 }
             }
         }
     }
     return $aAttributeNames;
 }
Esempio n. 15
0
function do_multiplechoice($ia)
{
    //// Init variables
    // General variables
    global $thissurvey;
    $kpclass = testKeypad($thissurvey['nokeyboard']);
    // Virtual keyboard (probably obsolete today)
    $inputnames = array();
    // TODO : check if really used
    $checkconditionFunction = "checkconditions";
    // name of the function to check condition TODO : check is used more than once
    $iSurveyId = Yii::app()->getConfig('surveyID');
    // survey id
    $sSurveyLang = $_SESSION['survey_' . $iSurveyId]['s_lang'];
    // survey language
    // Question attribute variables
    $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
    // Question attributes
    $othertext = trim($aQuestionAttributes['other_replace_text'][$sSurveyLang]) != '' ? $aQuestionAttributes['other_replace_text'][$sSurveyLang] : gT('Other:');
    // text for 'other'
    $iNbCols = trim($aQuestionAttributes['display_columns']) != '' ? $aQuestionAttributes['display_columns'] : 1;
    // number of columns
    if ($aQuestionAttributes['other_numbers_only'] == 1) {
        $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
        $sSeparator = $sSeparator['separator'];
        $oth_checkconditionFunction = "fixnum_checkconditions";
    } else {
        $oth_checkconditionFunction = "checkconditions";
    }
    //// Retrieving datas
    // Getting question
    $oQuestion = Question::model()->findByPk(array('qid' => $ia[0], 'language' => $sSurveyLang));
    $other = $oQuestion->other;
    // Getting answers
    $ansresult = $oQuestion->getOrderedSubQuestions($aQuestionAttributes['random_order'], $aQuestionAttributes['exclude_all_others']);
    $anscount = count($ansresult);
    $anscount = $other == 'Y' ? $anscount + 1 : $anscount;
    //COUNT OTHER AS AN ANSWER FOR MANDATORY CHECKING!
    //// Columns containing answer rows, set by user in question attribute
    /// TODO : move to a dedicated function
    // setting variables
    $iMaxRowsByColumn = 0;
    // How many answer rows by column
    $iRowCount = 0;
    $isOpen = false;
    // Is a column opened
    // TODO: check if still used
    if ($iNbCols > 1) {
        // First we calculate the width of each column
        // Max number of column is 12 http://getbootstrap.com/css/#grid
        $iColumnWidth = round(12 / $iNbCols);
        $iColumnWidth = $iColumnWidth >= 1 ? $iColumnWidth : 1;
        $iColumnWidth = $iColumnWidth <= 12 ? $iColumnWidth : 12;
        // Then, we calculate how many answer rows in each column
        $iMaxRowsByColumn = ceil($anscount / $iNbCols);
        $first = true;
        // The very first item will open a bootstrap row containing the columns
    }
    /// Generate answer rows
    $i = 0;
    $sRows = '';
    foreach ($ansresult as $ansrow) {
        $i++;
        // general count of loop, to check if the item is the last one for column process. Never reset.
        $iRowCount++;
        // counter of number of row by column. Is reset to zero each time a column is full.
        $myfname = $ia[1] . $ansrow['title'];
        $extra_class = "";
        /* Check for array_filter */
        $sDisplayStyle = return_display_style($ia, $aQuestionAttributes, $thissurvey, $myfname);
        $checkedState = '';
        /* If the question has already been ticked, check the checkbox */
        if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
            if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] == 'Y') {
                $checkedState = 'CHECKED';
            }
        }
        $sCheckconditionFunction = $checkconditionFunction . '(this.value, this.name, this.type)';
        $sValue = isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) ? $sValue = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname] : '';
        $inputnames[] = $myfname;
        ////
        // Open Column
        // The column is opened if user set more than one column in question attribute
        // and if this is the first answer row, or if the column has been closed and the row count reset before.
        if ($iNbCols > 1 && $iRowCount == 1) {
            $sRows .= doRender('/survey/questions/multiplechoice/columns/column_header', array('iColumnWidth' => isset($iColumnWidth) ? $iColumnWidth : '', 'first' => isset($first) ? $first : ''), true);
            $isOpen = true;
            // If a column is not closed, it will be closed at the end of the process
            $first = false;
            // The row containing the column has been opened at the first call.
        }
        ////
        // Insert row
        // Display the answer row
        $sRows .= doRender('/survey/questions/multiplechoice/rows/answer_row', array('extra_class' => $extra_class, 'sDisplayStyle' => $sDisplayStyle, 'name' => $ia[1], 'title' => $ansrow['title'], 'question' => $ansrow['question'], 'ansrow' => $ansrow, 'checkedState' => $checkedState, 'sCheckconditionFunction' => $sCheckconditionFunction, 'myfname' => $myfname, 'sValue' => $sValue), true);
        ////
        // Close column
        // The column is closed if the user set more than one column in question attribute
        // and if the max answer rows by column is reached.
        // If max answer rows by column is not reached while there is no more answer,
        // the column will remain opened, and it will be closed by 'other' answer row if set or at the end of the process
        if ($iNbCols > 1 && $iRowCount == $iMaxRowsByColumn) {
            $last = $i == $anscount ? true : false;
            // If this loop count equal to the number of answers, then this answer is the last one.
            $sRows .= doRender('/survey/questions/multiplechoice/columns/column_footer', array('last' => $last), true);
            $iRowCount = 0;
            $isOpen = false;
        }
    }
    //==>  rows
    if ($other == 'Y') {
        $iRowCount++;
        $myfname = $ia[1] . 'other';
        $checkedState = '';
        // othercbox can be not display, because only input text goes to database
        if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) && trim($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname]) != '') {
            $checkedState = 'CHECKED';
        }
        $sValue = '';
        if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
            $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
            if ($aQuestionAttributes['other_numbers_only'] == 1) {
                $dispVal = str_replace('.', $sSeparator, $dispVal);
            }
            $sValue .= htmlspecialchars($dispVal, ENT_QUOTES);
        }
        // TODO : check if $sValueHidden === $sValue
        $sValueHidden = '';
        if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname])) {
            $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$myfname];
            if ($aQuestionAttributes['other_numbers_only'] == 1) {
                $dispVal = str_replace('.', $sSeparator, $dispVal);
            }
            $sValueHidden = htmlspecialchars($dispVal, ENT_QUOTES);
        }
        $inputnames[] = $myfname;
        ++$anscount;
        ////
        // Open Column
        // The column is opened if user set more than one column in question attribute
        // and if this is the first answer row (should never happen for 'other'),
        // or if the column has been closed and the row count reset before.
        if ($iNbCols > 1 && $iRowCount == 1) {
            $sRows .= doRender('/survey/questions/multiplechoice/columns/column_header', array('iColumnWidth' => $iColumnWidth, 'first' => false), true);
        }
        ////
        // Insert row
        // Display the answer row
        $sRows .= doRender('/survey/questions/multiplechoice/rows/answer_row_other', array('myfname' => $myfname, 'sDisplayStyle' => isset($sDisplayStyle) ? $sDisplayStyle : '', 'othertext' => $othertext, 'checkedState' => $checkedState, 'kpclass' => $kpclass, 'sValue' => $sValue, 'oth_checkconditionFunction' => $oth_checkconditionFunction, 'checkconditionFunction' => $checkconditionFunction, 'sValueHidden' => $sValueHidden), true);
        ////
        // Close column
        // The column is closed if the user set more than one column in question attribute
        // Other is always the last answer, so it's always closing the col and the bootstrap row containing the columns
        if ($iNbCols > 1) {
            $sRows .= doRender('/survey/questions/multiplechoice/columns/column_footer', array('last' => true), true);
            $iRowCount = 0;
            $isOpen = false;
        }
    }
    ////
    // Close column
    // The column is closed if the user set more than one column in question attribute
    // and if on column has been opened and not closed
    // That can happen only when no 'other' option is set, and the maximum answer rows has not been reached in the last question
    if ($iNbCols > 1 && $isOpen) {
        $sRows .= doRender('/survey/questions/multiplechoice/columns/column_footer', array('last' => true), true);
        $iRowCount = 0;
    }
    // ==> answer
    $answer = doRender('/survey/questions/multiplechoice/answer', array('sRows' => $sRows, 'name' => $ia[1], 'anscount' => $anscount), true);
    return array($answer, $inputnames);
}
Esempio n. 16
0
 /**
  * Main function
  *
  * @param mixed $surveyid
  * @param mixed $args
  */
 function run($surveyid, $args)
 {
     global $errormsg;
     extract($args);
     if (!$thissurvey) {
         $thissurvey = getSurveyInfo($surveyid);
     }
     $LEMsessid = 'survey_' . $surveyid;
     $this->setJavascriptVar($surveyid, isset($clang->langcode) ? $clang->langcode : $thissurvey['language']);
     $sTemplatePath = getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR;
     if (isset($_SESSION['survey_' . $surveyid]['templatepath'])) {
         $sTemplatePath = $_SESSION['survey_' . $surveyid]['templatepath'];
     }
     // $LEMdebugLevel - customizable debugging for Lime Expression Manager
     $LEMdebugLevel = 0;
     // LEM_DEBUG_TIMING;    // (LEM_DEBUG_TIMING + LEM_DEBUG_VALIDATION_SUMMARY + LEM_DEBUG_VALIDATION_DETAIL);
     $LEMskipReprocessing = false;
     // true if used GetLastMoveResult to avoid generation of unneeded extra JavaScript
     switch ($thissurvey['format']) {
         case "A":
             //All in one
             $surveyMode = 'survey';
             break;
         default:
         case "S":
             //One at a time
             $surveyMode = 'question';
             break;
         case "G":
             //Group at a time
             $surveyMode = 'group';
             break;
     }
     $radix = getRadixPointData($thissurvey['surveyls_numberformat']);
     $radix = $radix['separator'];
     $surveyOptions = array('active' => $thissurvey['active'] == 'Y', 'allowsave' => $thissurvey['allowsave'] == 'Y', 'anonymized' => $thissurvey['anonymized'] != 'N', 'assessments' => $thissurvey['assessments'] == 'Y', 'datestamp' => $thissurvey['datestamp'] == 'Y', 'deletenonvalues' => Yii::app()->getConfig('deletenonvalues'), 'hyperlinkSyntaxHighlighting' => ($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY, 'ipaddr' => $thissurvey['ipaddr'] == 'Y', 'radix' => $radix, 'refurl' => $thissurvey['refurl'] == "Y" && isset($_SESSION[$LEMsessid]['refurl']) ? $_SESSION[$LEMsessid]['refurl'] : NULL, 'savetimings' => $thissurvey['savetimings'] == "Y", 'surveyls_dateformat' => isset($thissurvey['surveyls_dateformat']) ? $thissurvey['surveyls_dateformat'] : 1, 'startlanguage' => isset($clang->langcode) ? $clang->langcode : $thissurvey['language'], 'target' => Yii::app()->getConfig('uploaddir') . DIRECTORY_SEPARATOR . 'surveys' . DIRECTORY_SEPARATOR . $thissurvey['sid'] . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR, 'tempdir' => Yii::app()->getConfig('tempdir') . DIRECTORY_SEPARATOR, 'timeadjust' => isset($timeadjust) ? $timeadjust : 0, 'token' => isset($clienttoken) ? $clienttoken : NULL);
     //Security Checked: POST, GET, SESSION, REQUEST, returnGlobal, DB
     $previewgrp = false;
     if ($surveyMode == 'group' && isset($param['action']) && $param['action'] == 'previewgroup') {
         $previewgrp = true;
     }
     $previewquestion = false;
     if ($surveyMode == 'question' && isset($param['action']) && $param['action'] == 'previewquestion') {
         $previewquestion = true;
     }
     //        if (isset($param['newtest']) && $param['newtest'] == "Y")
     //            setcookie("limesurvey_timers", "0");   //@todo fix - sometimes results in headers already sent error
     $show_empty_group = false;
     if ($previewgrp || $previewquestion) {
         $_SESSION[$LEMsessid]['prevstep'] = 2;
         $_SESSION[$LEMsessid]['maxstep'] = 0;
     } else {
         //RUN THIS IF THIS IS THE FIRST TIME , OR THE FIRST PAGE ########################################
         if (!isset($_SESSION[$LEMsessid]['step'])) {
             buildsurveysession($surveyid);
             $sTemplatePath = $_SESSION[$LEMsessid]['templatepath'];
             if ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
                 LimeExpressionManager::SetDirtyFlag();
             }
             LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
             $_SESSION[$LEMsessid]['step'] = 0;
             if ($surveyMode == 'survey') {
                 LimeExpressionManager::JumpTo(1, false, false, true);
             } elseif (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
                 $moveResult = LimeExpressionManager::JumpTo(1, false, false, true);
                 $_SESSION[$LEMsessid]['step'] = 1;
             }
         } elseif ($surveyid != LimeExpressionManager::getLEMsurveyId()) {
             LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions, false, $LEMdebugLevel);
             LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
         }
         $totalquestions = $_SESSION['survey_' . $surveyid]['totalquestions'];
         if (!isset($_SESSION[$LEMsessid]['totalsteps'])) {
             $_SESSION[$LEMsessid]['totalsteps'] = 0;
         }
         if (!isset($_SESSION[$LEMsessid]['maxstep'])) {
             $_SESSION[$LEMsessid]['maxstep'] = 0;
         }
         if (isset($_SESSION[$LEMsessid]['LEMpostKey']) && isset($_POST['LEMpostKey']) && $_POST['LEMpostKey'] != $_SESSION[$LEMsessid]['LEMpostKey']) {
             // then trying to resubmit (e.g. Next, Previous, Submit) from a cached copy of the page
             // Does not try to save anything from the page to the database
             $moveResult = LimeExpressionManager::GetLastMoveResult(true);
             if (isset($_POST['thisstep']) && isset($moveResult['seq']) && $_POST['thisstep'] == $moveResult['seq']) {
                 // then pressing F5 or otherwise refreshing the current page, which is OK
                 $LEMskipReprocessing = true;
                 $move = "movenext";
                 // so will re-display the survey
             } else {
                 // trying to use browser back buttons, which may be disallowed if no 'previous' button is present
                 $LEMskipReprocessing = true;
                 $move = "movenext";
                 // so will re-display the survey
                 $invalidLastPage = true;
                 $backpopup = $clang->gT("Please use the LimeSurvey navigation buttons or index.  It appears you attempted to use the browser back button to re-submit a page.");
             }
         }
         if (isset($move) && $move == "clearcancel") {
             $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, false, true);
             //$backpopup=$clang->gT("Clear all need confirmation.");
         }
         if (!(isset($_POST['saveall']) || isset($_POST['saveprompt']) || isset($_GET['sid']) || $LEMskipReprocessing || isset($move) && preg_match('/^changelang_/', $move))) {
             $_SESSION[$LEMsessid]['prevstep'] = $_SESSION[$LEMsessid]['step'];
         }
         if (!isset($_SESSION[$LEMsessid]['prevstep'])) {
             $_SESSION[$LEMsessid]['prevstep'] = -1;
             // this only happens on re-load
         }
         if (isset($_SESSION[$LEMsessid]['LEMtokenResume'])) {
             LimeExpressionManager::StartSurvey($thissurvey['sid'], $surveyMode, $surveyOptions, false, $LEMdebugLevel);
             if (isset($_SESSION[$LEMsessid]['maxstep']) && $_SESSION[$LEMsessid]['maxstep'] > $_SESSION[$LEMsessid]['step']) {
                 LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['maxstep'], false, false);
             }
             $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, false);
             // if late in the survey, will re-validate contents, which may be overkill
             unset($_SESSION[$LEMsessid]['LEMtokenResume']);
         } else {
             if (!$LEMskipReprocessing) {
                 //Move current step ###########################################################################
                 if (isset($move) && $move == 'moveprev' && ($thissurvey['allowprev'] == 'Y' || $thissurvey['questionindex'] > 0)) {
                     $moveResult = LimeExpressionManager::NavigateBackwards();
                     if ($moveResult['at_start']) {
                         $_SESSION[$LEMsessid]['step'] = 0;
                         unset($moveResult);
                         // so display welcome page again
                     }
                 }
                 if (isset($move) && $move == "movenext") {
                     $moveResult = LimeExpressionManager::NavigateForwards();
                 }
                 if (isset($move) && $move == 'movesubmit') {
                     if ($surveyMode == 'survey') {
                         $moveResult = LimeExpressionManager::NavigateForwards();
                     } else {
                         // may be submitting from the navigation bar, in which case need to process all intervening questions
                         // in order to update equations and ensure there are no intervening relevant mandatory or relevant invalid questions
                         $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false);
                     }
                 }
                 if (isset($move) && $move == 'changelang') {
                     // jump to current step using new language, processing POST values
                     $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false, true, true, true);
                     // do process the POST data
                 }
                 if (isset($move) && isNumericInt($move) && $thissurvey['questionindex'] == 1) {
                     $move = (int) $move;
                     if ($move > 0 && ($move <= $_SESSION[$LEMsessid]['step'] || isset($_SESSION[$LEMsessid]['maxstep']) && $move <= $_SESSION[$LEMsessid]['maxstep'])) {
                         $moveResult = LimeExpressionManager::JumpTo($move, false);
                     }
                 } elseif (isset($move) && isNumericInt($move) && $thissurvey['questionindex'] == 2) {
                     $move = (int) $move;
                     $moveResult = LimeExpressionManager::JumpTo($move, false, true, true);
                 }
                 if (!isset($moveResult) && !($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0)) {
                     // Just in case not set via any other means, but don't do this if it is the welcome page
                     $moveResult = LimeExpressionManager::GetLastMoveResult(true);
                     $LEMskipReprocessing = true;
                 }
             }
         }
         if (isset($moveResult) && isset($moveResult['seq'])) {
             // With complete index, we need to revalidate whole group bug #08806. It's actually the only mode where we JumpTo with force
             if ($moveResult['finished'] == true && $thissurvey['questionindex'] == 2) {
                 //LimeExpressionManager::JumpTo(-1, false, false, true);
                 LimeExpressionManager::StartSurvey($surveyid, $surveyMode, $surveyOptions);
                 $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['totalsteps'] + 1, false, false, false);
                 // no preview, no save data and NO force
                 if (!$moveResult['mandViolation'] && $moveResult['valid'] && empty($moveResult['invalidSQs'])) {
                     $moveResult['finished'] = true;
                 }
             }
             if ($moveResult['finished'] == true) {
                 $move = 'movesubmit';
             } else {
                 $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
                 // step is index base 1
                 $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
             }
             if ($move == "movesubmit" && $moveResult['finished'] == false) {
                 // then there are errors, so don't finalize the survey
                 $move = "movenext";
                 // so will re-display the survey
                 $invalidLastPage = true;
             }
         }
         // We do not keep the participant session anymore when the same browser is used to answer a second time a survey (let's think of a library PC for instance).
         // Previously we used to keep the session and redirect the user to the
         // submit page.
         if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] == 0) {
             $_SESSION[$LEMsessid]['test'] = time();
             display_first_page();
             Yii::app()->end();
             // So we can still see debug messages
         }
         // TODO FIXME
         if ($thissurvey['active'] == "Y") {
             Yii::import("application.libraries.Save");
             $cSave = new Save();
         }
         if ($thissurvey['active'] == "Y" && Yii::app()->request->getPost('saveall')) {
             $bTokenAnswerPersitance = $thissurvey['tokenanswerspersistence'] == 'Y' && isset($surveyid) && tableExists('tokens_' . $surveyid);
             // must do this here to process the POSTed values
             $moveResult = LimeExpressionManager::JumpTo($_SESSION[$LEMsessid]['step'], false);
             // by jumping to current step, saves data so far
             if (!isset($_SESSION[$LEMsessid]['scid']) && !$bTokenAnswerPersitance) {
                 $cSave->showsaveform();
                 // generates a form and exits, awaiting input
             } else {
                 // Intentional retest of all conditions to be true, to make sure we do have tokens and surveyid
                 // Now update lastpage to $_SESSION[$LEMsessid]['step'] in SurveyDynamic, otherwise we land on
                 // the previous page when we return.
                 $iResponseID = $_SESSION[$LEMsessid]['srid'];
                 $oResponse = SurveyDynamic::model($surveyid)->findByPk($iResponseID);
                 $oResponse->lastpage = $_SESSION[$LEMsessid]['step'];
                 $oResponse->save();
             }
         }
         if ($thissurvey['active'] == "Y" && Yii::app()->request->getParam('savesubmit')) {
             // The response from the save form
             // CREATE SAVED CONTROL RECORD USING SAVE FORM INFORMATION
             $popup = $cSave->savedcontrol();
             if (isset($errormsg) && $errormsg != "") {
                 $cSave->showsaveform();
                 // reshow the form if there is an error
             }
             $moveResult = LimeExpressionManager::GetLastMoveResult(true);
             $LEMskipReprocessing = true;
             // TODO - does this work automatically for token answer persistence? Used to be savedsilent()
         }
         //Now, we check mandatory questions if necessary
         //CHECK IF ALL CONDITIONAL MANDATORY QUESTIONS THAT APPLY HAVE BEEN ANSWERED
         global $notanswered;
         if (isset($moveResult) && !$moveResult['finished']) {
             $unansweredSQList = $moveResult['unansweredSQs'];
             if (strlen($unansweredSQList) > 0) {
                 $notanswered = explode('|', $unansweredSQList);
             } else {
                 $notanswered = array();
             }
             //CHECK INPUT
             $invalidSQList = $moveResult['invalidSQs'];
             if (strlen($invalidSQList) > 0) {
                 $notvalidated = explode('|', $invalidSQList);
             } else {
                 $notvalidated = array();
             }
         }
         // CHECK UPLOADED FILES
         // TMSW - Move this into LEM::NavigateForwards?
         $filenotvalidated = checkUploadedFileValidity($surveyid, $move);
         //SEE IF THIS GROUP SHOULD DISPLAY
         $show_empty_group = false;
         if ($_SESSION[$LEMsessid]['step'] == 0) {
             $show_empty_group = true;
         }
         $redata = compact(array_keys(get_defined_vars()));
         //SUBMIT ###############################################################################
         if (isset($move) && $move == "movesubmit") {
             //                setcookie("limesurvey_timers", "", time() - 3600); // remove the timers cookies   //@todo fix - sometimes results in headers already sent error
             if ($thissurvey['refurl'] == "Y") {
                 if (!in_array("refurl", $_SESSION[$LEMsessid]['insertarray'])) {
                     $_SESSION[$LEMsessid]['insertarray'][] = "refurl";
                 }
             }
             resetTimers();
             //Before doing the "templatereplace()" function, check the $thissurvey['url']
             //field for limereplace stuff, and do transformations!
             $thissurvey['surveyls_url'] = passthruReplace($thissurvey['surveyls_url'], $thissurvey);
             $thissurvey['surveyls_url'] = templatereplace($thissurvey['surveyls_url'], array(), $redata, 'URLReplace', false, NULL, array(), true);
             // to do INSERTANS substitutions
             //END PAGE - COMMIT CHANGES TO DATABASE
             if ($thissurvey['active'] != "Y") {
                 if ($thissurvey['assessments'] == "Y") {
                     $assessments = doAssessment($surveyid);
                 }
                 sendCacheHeaders();
                 doHeader();
                 echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'SubmitStartpageI', false, NULL, array(), true);
                 //Check for assessments
                 if ($thissurvey['assessments'] == "Y" && $assessments) {
                     echo templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata, 'SubmitAssessmentI', false, NULL, array(), true);
                 }
                 // fetch all filenames from $_SESSIONS['files'] and delete them all
                 // from the /upload/tmp/ directory
                 /* echo "<pre>";print_r($_SESSION);echo "</pre>";
                    for($i = 1; isset($_SESSION[$LEMsessid]['files'][$i]); $i++)
                    {
                    unlink('upload/tmp/'.$_SESSION[$LEMsessid]['files'][$i]['filename']);
                    }
                    */
                 // can't kill session before end message, otherwise INSERTANS doesn't work.
                 $completed = templatereplace($thissurvey['surveyls_endtext'], array(), $redata, 'SubmitEndtextI', false, NULL, array(), true);
                 $completed .= "<br /><strong><font size='2' color='red'>" . $clang->gT("Did Not Save") . "</font></strong><br /><br />\n\n";
                 $completed .= $clang->gT("Your survey responses have not been recorded. This survey is not yet active.") . "<br /><br />\n";
                 if ($thissurvey['printanswers'] == 'Y') {
                     // 'Clear all' link is only relevant for survey with printanswers enabled
                     // in other cases the session is cleared at submit time
                     $completed .= "<a href='" . Yii::app()->getController()->createUrl("survey/index/sid/{$surveyid}/move/clearall") . "'>" . $clang->gT("Clear Responses") . "</a><br /><br />\n";
                 }
             } else {
                 if ($thissurvey['usecookie'] == "Y" && $tokensexist != 1) {
                     setcookie("LS_" . $surveyid . "_STATUS", "COMPLETE", time() + 31536000);
                     //Cookie will expire in 365 days
                 }
                 $content = '';
                 $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'SubmitStartpage', false, NULL, array(), true);
                 //Check for assessments
                 if ($thissurvey['assessments'] == "Y") {
                     $assessments = doAssessment($surveyid);
                     if ($assessments) {
                         $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata, 'SubmitAssessment', false, NULL, array(), true);
                     }
                 }
                 //Update the token if needed and send a confirmation email
                 if (isset($_SESSION['survey_' . $surveyid]['token'])) {
                     submittokens();
                 }
                 //Send notifications
                 sendSubmitNotifications($surveyid);
                 $content = '';
                 $content .= templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata, 'SubmitStartpage', false, NULL, array(), true);
                 //echo $thissurvey['url'];
                 //Check for assessments
                 if ($thissurvey['assessments'] == "Y") {
                     $assessments = doAssessment($surveyid);
                     if ($assessments) {
                         $content .= templatereplace(file_get_contents($sTemplatePath . "assessment.pstpl"), array(), $redata, 'SubmitAssessment', false, NULL, array(), true);
                     }
                 }
                 if (trim(str_replace(array('<p>', '</p>'), '', $thissurvey['surveyls_endtext'])) == '') {
                     $completed = "<br /><span class='success'>" . $clang->gT("Thank you!") . "</span><br /><br />\n\n" . $clang->gT("Your survey responses have been recorded.") . "<br /><br />\n";
                 } else {
                     $completed = templatereplace($thissurvey['surveyls_endtext'], array(), $redata, 'SubmitAssessment', false, NULL, array(), true);
                 }
                 // Link to Print Answer Preview  **********
                 if ($thissurvey['printanswers'] == 'Y') {
                     $url = Yii::app()->getController()->createUrl("/printanswers/view/surveyid/{$surveyid}");
                     $completed .= "<br /><br />" . "<a class='printlink' href='{$url}'  target='_blank'>" . $clang->gT("Print your answers.") . "</a><br />\n";
                 }
                 //*****************************************
                 if ($thissurvey['publicstatistics'] == 'Y' && $thissurvey['printanswers'] == 'Y') {
                     $completed .= '<br />' . $clang->gT("or");
                 }
                 // Link to Public statistics  **********
                 if ($thissurvey['publicstatistics'] == 'Y') {
                     $url = Yii::app()->getController()->createUrl("/statistics_user/action/surveyid/{$surveyid}/language/" . $_SESSION[$LEMsessid]['s_lang']);
                     $completed .= "<br /><br />" . "<a class='publicstatisticslink' href='{$url}' target='_blank'>" . $clang->gT("View the statistics for this survey.") . "</a><br />\n";
                 }
                 //*****************************************
                 $_SESSION[$LEMsessid]['finished'] = true;
                 $_SESSION[$LEMsessid]['sid'] = $surveyid;
                 sendCacheHeaders();
                 if (isset($thissurvey['autoredirect']) && $thissurvey['autoredirect'] == "Y" && $thissurvey['surveyls_url']) {
                     //Automatically redirect the page to the "url" setting for the survey
                     header("Location: {$thissurvey['surveyls_url']}");
                 }
                 doHeader();
                 echo $content;
             }
             $redata['completed'] = $completed;
             // @todo Remove direct session access.
             $event = new PluginEvent('afterSurveyComplete');
             if (isset($_SESSION[$LEMsessid]['srid'])) {
                 $event->set('responseId', $_SESSION[$LEMsessid]['srid']);
             }
             $event->set('surveyId', $surveyid);
             App()->getPluginManager()->dispatchEvent($event);
             $blocks = array();
             foreach ($event->getAllContent() as $blockData) {
                 /* @var $blockData PluginEventContent */
                 $blocks[] = CHtml::tag('div', array('id' => $blockData->getCssId(), 'class' => $blockData->getCssClass()), $blockData->getContent());
             }
             $redata['completed'] = implode("\n", $blocks) . "\n" . $redata['completed'];
             $redata['thissurvey']['surveyls_url'] = $thissurvey['surveyls_url'];
             echo templatereplace(file_get_contents($sTemplatePath . "completed.pstpl"), array('completed' => $completed), $redata, 'SubmitCompleted', false, NULL, array(), true);
             echo "\n";
             if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
                 echo LimeExpressionManager::GetDebugTimingMessage();
             }
             if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
                 echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
             }
             echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata, 'SubmitEndpage', false, NULL, array(), true);
             doFooter();
             // The session cannot be killed until the page is completely rendered
             if ($thissurvey['printanswers'] != 'Y') {
                 killSurveySession($surveyid);
             }
             exit;
         }
     }
     $redata = compact(array_keys(get_defined_vars()));
     // IF GOT THIS FAR, THEN DISPLAY THE ACTIVE GROUP OF QUESTIONSs
     //SEE IF $surveyid EXISTS ####################################################################
     if ($surveyExists < 1) {
         //SURVEY DOES NOT EXIST. POLITELY EXIT.
         echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
         echo "\t<center><br />\n";
         echo "\t" . $clang->gT("Sorry. There is no matching survey.") . "<br /></center>&nbsp;\n";
         echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
         doFooter();
         exit;
     }
     createFieldMap($surveyid, 'full', false, false, $_SESSION[$LEMsessid]['s_lang']);
     //GET GROUP DETAILS
     if ($surveyMode == 'group' && $previewgrp) {
         //            setcookie("limesurvey_timers", "0"); //@todo fix - sometimes results in headers already sent error
         $_gid = sanitize_int($param['gid']);
         LimeExpressionManager::StartSurvey($thissurvey['sid'], 'group', $surveyOptions, false, $LEMdebugLevel);
         $gseq = LimeExpressionManager::GetGroupSeq($_gid);
         if ($gseq == -1) {
             echo $clang->gT('Invalid group number for this survey: ') . $_gid;
             exit;
         }
         $moveResult = LimeExpressionManager::JumpTo($gseq + 1, true);
         if (is_null($moveResult)) {
             echo $clang->gT('This group contains no questions.  You must add questions to this group before you can preview it');
             exit;
         }
         if (isset($moveResult)) {
             $_SESSION[$LEMsessid]['step'] = $moveResult['seq'] + 1;
             // step is index base 1?
         }
         $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
         $gid = $stepInfo['gid'];
         $groupname = $stepInfo['gname'];
         $groupdescription = $stepInfo['gtext'];
     } else {
         if ($show_empty_group || !isset($_SESSION[$LEMsessid]['grouplist'])) {
             $gid = -1;
             // Make sure the gid is unused. This will assure that the foreach (fieldarray as ia) has no effect.
             $groupname = $clang->gT("Submit your answers");
             $groupdescription = $clang->gT("There are no more questions. Please press the <Submit> button to finish this survey.");
         } else {
             if ($surveyMode != 'survey') {
                 if ($previewquestion) {
                     $_qid = sanitize_int($param['qid']);
                     LimeExpressionManager::StartSurvey($surveyid, 'question', $surveyOptions, false, $LEMdebugLevel);
                     $qSec = LimeExpressionManager::GetQuestionSeq($_qid);
                     $moveResult = LimeExpressionManager::JumpTo($qSec + 1, true, false, true);
                     $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                 } else {
                     $stepInfo = LimeExpressionManager::GetStepIndexInfo($moveResult['seq']);
                 }
                 $gid = $stepInfo['gid'];
                 $groupname = $stepInfo['gname'];
                 $groupdescription = $stepInfo['gtext'];
             }
         }
     }
     if ($previewquestion) {
         $_SESSION[$LEMsessid]['step'] = 0;
         //maybe unset it after the question has been displayed?
     }
     if ($_SESSION[$LEMsessid]['step'] > $_SESSION[$LEMsessid]['maxstep']) {
         $_SESSION[$LEMsessid]['maxstep'] = $_SESSION[$LEMsessid]['step'];
     }
     // If the survey uses answer persistence and a srid is registered in SESSION
     // then loadanswers from this srid
     /* Only survey mode used this - should all?
        if ($thissurvey['tokenanswerspersistence'] == 'Y' &&
        $thissurvey['anonymized'] == "N" &&
        isset($_SESSION[$LEMsessid]['srid']) &&
        $thissurvey['active'] == "Y")
        {
        loadanswers();
        }
        */
     //******************************************************************************************************
     //PRESENT SURVEY
     //******************************************************************************************************
     $okToShowErrors = !$previewgrp && (isset($invalidLastPage) || $_SESSION[$LEMsessid]['prevstep'] == $_SESSION[$LEMsessid]['step']);
     Yii::app()->getController()->loadHelper('qanda');
     setNoAnswerMode($thissurvey);
     //Iterate through the questions about to be displayed:
     $inputnames = array();
     foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
         $gid = $gl['gid'];
         $qnumber = 0;
         if ($surveyMode != 'survey') {
             $onlyThisGID = $stepInfo['gid'];
             if ($onlyThisGID != $gid) {
                 continue;
             }
         }
         // TMSW - could iterate through LEM::currentQset instead
         foreach ($_SESSION[$LEMsessid]['fieldarray'] as $key => $ia) {
             ++$qnumber;
             $ia[9] = $qnumber;
             // incremental question count;
             if (isset($ia[10]) && $ia[10] == $gid || !isset($ia[10]) && $ia[5] == $gid) {
                 if ($surveyMode == 'question' && $ia[0] != $stepInfo['qid']) {
                     continue;
                 }
                 $qidattributes = getQuestionAttributeValues($ia[0], $ia[4]);
                 if ($ia[4] != '*' && ($qidattributes === false || !isset($qidattributes['hidden']) || $qidattributes['hidden'] == 1)) {
                     continue;
                 }
                 //Get the answers/inputnames
                 // TMSW - can content of retrieveAnswers() be provided by LEM?  Review scope of what it provides.
                 // TODO - retrieveAnswers is slow - queries database separately for each question. May be fixed in _CI or _YII ports, so ignore for now
                 list($plus_qanda, $plus_inputnames) = retrieveAnswers($ia, $surveyid);
                 if ($plus_qanda) {
                     $plus_qanda[] = $ia[4];
                     $plus_qanda[] = $ia[6];
                     // adds madatory identifyer for adding mandatory class to question wrapping div
                     // Add a finalgroup in qa array , needed for random attribute : TODO: find a way to have it in new quanda_helper in 2.1
                     if (isset($ia[10])) {
                         $plus_qanda['finalgroup'] = $ia[10];
                     } else {
                         $plus_qanda['finalgroup'] = $ia[5];
                     }
                     $qanda[] = $plus_qanda;
                 }
                 if ($plus_inputnames) {
                     $inputnames = addtoarray_single($inputnames, $plus_inputnames);
                 }
                 //Display the "mandatory" popup if necessary
                 // TMSW - get question-level error messages - don't call **_popup() directly
                 if ($okToShowErrors && $stepInfo['mandViolation']) {
                     list($mandatorypopup, $popup) = mandatory_popup($ia, $notanswered);
                 }
                 //Display the "validation" popup if necessary
                 if ($okToShowErrors && !$stepInfo['valid']) {
                     list($validationpopup, $vpopup) = validation_popup($ia, $notvalidated);
                 }
                 // Display the "file validation" popup if necessary
                 if ($okToShowErrors && isset($filenotvalidated)) {
                     list($filevalidationpopup, $fpopup) = file_validation_popup($ia, $filenotvalidated);
                 }
             }
             if ($ia[4] == "|") {
                 $upload_file = TRUE;
             }
         }
         //end iteration
     }
     if ($surveyMode != 'survey' && isset($thissurvey['showprogress']) && $thissurvey['showprogress'] == 'Y') {
         if ($show_empty_group) {
             $percentcomplete = makegraph($_SESSION[$LEMsessid]['totalsteps'] + 1, $_SESSION[$LEMsessid]['totalsteps']);
         } else {
             $percentcomplete = makegraph($_SESSION[$LEMsessid]['step'], $_SESSION[$LEMsessid]['totalsteps']);
         }
     }
     if (!(isset($languagechanger) && strlen($languagechanger) > 0) && function_exists('makeLanguageChangerSurvey')) {
         $languagechanger = makeLanguageChangerSurvey($_SESSION[$LEMsessid]['s_lang']);
     }
     //READ TEMPLATES, INSERT DATA AND PRESENT PAGE
     sendCacheHeaders();
     doHeader();
     $redata = compact(array_keys(get_defined_vars()));
     echo templatereplace(file_get_contents($sTemplatePath . "startpage.pstpl"), array(), $redata);
     $aPopup = array();
     // We can move this part where we want now
     if (isset($backpopup)) {
         $aPopup[] = $backpopup;
         // If user click reload: no need other popup
     } else {
         if (isset($popup)) {
             $aPopup[] = $popup;
         }
         if (isset($vpopup)) {
             $aPopup[] = $vpopup;
         }
         if (isset($fpopup)) {
             $aPopup[] = $fpopup;
         }
     }
     Yii::app()->clientScript->registerScript("showpopup", "showpopup=" . (int) Yii::app()->getConfig('showpopups') . ";", CClientScript::POS_HEAD);
     //if(count($aPopup))
     Yii::app()->clientScript->registerScript('startPopup', "startPopups=" . json_encode($aPopup) . ";", CClientScript::POS_HEAD);
     //ALTER PAGE CLASS TO PROVIDE WHOLE-PAGE ALTERNATION
     if ($surveyMode != 'survey' && $_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep'] || isset($_SESSION[$LEMsessid]['stepno']) && $_SESSION[$LEMsessid]['stepno'] % 2) {
         if (!isset($_SESSION[$LEMsessid]['stepno'])) {
             $_SESSION[$LEMsessid]['stepno'] = 0;
         }
         if ($_SESSION[$LEMsessid]['step'] != $_SESSION[$LEMsessid]['prevstep']) {
             ++$_SESSION[$LEMsessid]['stepno'];
         }
         if ($_SESSION[$LEMsessid]['stepno'] % 2) {
             echo "<script type=\"text/javascript\">\n" . "  \$(\"body\").addClass(\"page-odd\");\n" . "</script>\n";
         }
     }
     $hiddenfieldnames = implode("|", $inputnames);
     if (isset($upload_file) && $upload_file) {
         echo CHtml::form(array("survey/index"), 'post', array('enctype' => 'multipart/form-data', 'id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
     } else {
         echo CHtml::form(array("survey/index"), 'post', array('id' => 'limesurvey', 'name' => 'limesurvey', 'autocomplete' => 'off')) . "\n\n            <!-- INPUT NAMES -->\n            <input type='hidden' name='fieldnames' value='{$hiddenfieldnames}' id='fieldnames' />\n";
     }
     // <-- END FEATURE - SAVE
     // The default submit button
     echo CHtml::htmlButton("default", array('type' => 'submit', 'id' => "defaultbtn", 'value' => "default", 'name' => 'move', 'class' => "submit noview", 'style' => 'display:none'));
     if ($surveyMode == 'survey') {
         if (isset($thissurvey['showwelcome']) && $thissurvey['showwelcome'] == 'N') {
             //Hide the welcome screen if explicitly set
         } else {
             echo templatereplace(file_get_contents($sTemplatePath . "welcome.pstpl"), array(), $redata) . "\n";
         }
         if ($thissurvey['anonymized'] == "Y") {
             echo templatereplace(file_get_contents($sTemplatePath . "privacy.pstpl"), array(), $redata) . "\n";
         }
     }
     // <-- START THE SURVEY -->
     if ($surveyMode != 'survey') {
         echo templatereplace(file_get_contents($sTemplatePath . "survey.pstpl"), array(), $redata);
     }
     // runonce element has been changed from a hidden to a text/display:none one. In order to workaround an not-reproduced issue #4453 (lemeur)
     // We don't need runonce actually (140228): the script was updated and replaced by EM see #08783 (grep show no other runonce)
     // echo "<input type='text' id='runonce' value='0' style='display: none;'/>";
     $showpopups = Yii::app()->getConfig('showpopups');
     //Display the "mandatory" message on page if necessary
     if (!$showpopups && $stepInfo['mandViolation'] && $okToShowErrors) {
         echo "<p class='errormandatory'>" . $clang->gT("One or more mandatory questions have not been answered. You cannot proceed until these have been completed.") . "</p>";
     }
     //Display the "validation" message on page if necessary
     if (!$showpopups && !$stepInfo['valid'] && $okToShowErrors) {
         echo "<p class='errormandatory'>" . $clang->gT("One or more questions have not been answered in a valid manner. You cannot proceed until these answers are valid.") . "</p>";
     }
     //Display the "file validation" message on page if necessary
     if (!$showpopups && isset($filenotvalidated) && $filenotvalidated == true && $okToShowErrors) {
         echo "<p class='errormandatory'>" . $clang->gT("One or more uploaded files are not in proper format/size. You cannot proceed until these files are valid.") . "</p>";
     }
     $_gseq = -1;
     foreach ($_SESSION[$LEMsessid]['grouplist'] as $gl) {
         $gid = $gl['gid'];
         ++$_gseq;
         $groupname = $gl['group_name'];
         $groupdescription = $gl['description'];
         if ($surveyMode != 'survey' && $gid != $onlyThisGID) {
             continue;
         }
         $redata = compact(array_keys(get_defined_vars()));
         Yii::app()->setConfig('gid', $gid);
         // To be used in templaterplace in whole group. Attention : it's the actual GID (not the GID of the question)
         echo "\n\n<!-- START THE GROUP -->\n";
         echo "\n\n<div id='group-{$_gseq}'";
         $gnoshow = LimeExpressionManager::GroupIsIrrelevantOrHidden($_gseq);
         if ($gnoshow && !$previewgrp) {
             echo " style='display: none;'";
         }
         echo ">\n";
         echo templatereplace(file_get_contents($sTemplatePath . "startgroup.pstpl"), array(), $redata);
         echo "\n";
         if (!$previewquestion) {
             echo templatereplace(file_get_contents($sTemplatePath . "groupdescription.pstpl"), array(), $redata);
         }
         echo "\n";
         echo "\n\n<!-- PRESENT THE QUESTIONS -->\n";
         foreach ($qanda as $qa) {
             // Test if finalgroup is in this qid (for all in one survey, else we do only qanda for needed question (in one by one or group by goup)
             if ($gid != $qa['finalgroup']) {
                 continue;
             }
             $qid = $qa[4];
             $qinfo = LimeExpressionManager::GetQuestionStatus($qid);
             $lastgrouparray = explode("X", $qa[7]);
             $lastgroup = $lastgrouparray[0] . "X" . $lastgrouparray[1];
             // id of the last group, derived from question id
             $lastanswer = $qa[7];
             $q_class = getQuestionClass($qinfo['info']['type']);
             $man_class = '';
             if ($qinfo['info']['mandatory'] == 'Y') {
                 $man_class .= ' mandatory';
             }
             if ($qinfo['anyUnanswered'] && $_SESSION[$LEMsessid]['maxstep'] != $_SESSION[$LEMsessid]['step']) {
                 $man_class .= ' missing';
             }
             $n_q_display = '';
             if ($qinfo['hidden'] && $qinfo['info']['type'] != '*') {
                 continue;
                 // skip this one
             }
             if (!$qinfo['relevant'] || $qinfo['hidden'] && $qinfo['info']['type'] == '*') {
                 $n_q_display = ' style="display: none;"';
             }
             $question = $qa[0];
             //===================================================================
             // The following four variables offer the templating system the
             // capacity to fully control the HTML output for questions making the
             // above echo redundant if desired.
             $question['essentials'] = 'id="question' . $qa[4] . '"' . $n_q_display;
             $question['class'] = $q_class;
             $question['man_class'] = $man_class;
             $question['code'] = $qa[5];
             $question['sgq'] = $qa[7];
             $question['aid'] = !empty($qinfo['info']['aid']) ? $qinfo['info']['aid'] : 0;
             $question['sqid'] = !empty($qinfo['info']['sqid']) ? $qinfo['info']['sqid'] : 0;
             $question['type'] = $qinfo['info']['type'];
             //===================================================================
             $answer = $qa[1];
             $help = $qinfo['info']['help'];
             // $qa[2];
             $redata = compact(array_keys(get_defined_vars()));
             $question_template = file_get_contents($sTemplatePath . 'question.pstpl');
             if (preg_match('/\\{QUESTION_ESSENTIALS\\}/', $question_template) === false || preg_match('/\\{QUESTION_CLASS\\}/', $question_template) === false) {
                 // if {QUESTION_ESSENTIALS} is present in the template but not {QUESTION_CLASS} remove it because you don't want id="" and display="" duplicated.
                 $question_template = str_replace('{QUESTION_ESSENTIALS}', '', $question_template);
                 $question_template = str_replace('{QUESTION_CLASS}', '', $question_template);
                 echo '
                 <!-- NEW QUESTION -->
                 <div id="question' . $qa[4] . '" class="' . $q_class . $man_class . '"' . $n_q_display . '>';
                 echo templatereplace($question_template, array(), $redata, false, false, $qa[4]);
                 echo '</div>';
             } else {
                 // TMSW - eventually refactor so that only substitutes the QUESTION_** fields - doesn't need full power of template replace
                 // TMSW - also, want to return a string, and call templatereplace once on that result string once all done.
                 echo templatereplace($question_template, array(), $redata, false, false, $qa[4]);
             }
         }
         if ($surveyMode == 'group') {
             echo "<input type='hidden' name='lastgroup' value='{$lastgroup}' id='lastgroup' />\n";
             // for counting the time spent on each group
         }
         if ($surveyMode == 'question') {
             echo "<input type='hidden' name='lastanswer' value='{$lastanswer}' id='lastanswer' />\n";
         }
         echo "\n\n<!-- END THE GROUP -->\n";
         echo templatereplace(file_get_contents($sTemplatePath . "endgroup.pstpl"), array(), $redata);
         echo "\n\n</div>\n";
         Yii::app()->setConfig('gid', '');
     }
     LimeExpressionManager::FinishProcessingGroup($LEMskipReprocessing);
     echo LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
     LimeExpressionManager::FinishProcessingPage();
     if (!$previewgrp && !$previewquestion) {
         $navigator = surveymover();
         //This gets globalised in the templatereplace function
         $redata = compact(array_keys(get_defined_vars()));
         echo "\n\n<!-- PRESENT THE NAVIGATOR -->\n";
         echo templatereplace(file_get_contents($sTemplatePath . "navigator.pstpl"), array(), $redata);
         echo "\n";
         if ($thissurvey['active'] != "Y") {
             echo "<p style='text-align:center' class='error'>" . $clang->gT("This survey is currently not active. You will not be able to save your responses.") . "</p>\n";
         }
         if ($surveyMode != 'survey' && $thissurvey['questionindex'] == 1) {
             $this->createIncrementalQuestionIndex($LEMsessid, $surveyMode);
         } elseif ($surveyMode != 'survey' && $thissurvey['questionindex'] == 2) {
             $this->createFullQuestionIndex($LEMsessid, $surveyMode);
         }
         echo "<input type='hidden' name='thisstep' value='{$_SESSION[$LEMsessid]['step']}' id='thisstep' />\n";
         echo "<input type='hidden' name='sid' value='{$surveyid}' id='sid' />\n";
         echo "<input type='hidden' name='start_time' value='" . time() . "' id='start_time' />\n";
         $_SESSION[$LEMsessid]['LEMpostKey'] = mt_rand();
         echo "<input type='hidden' name='LEMpostKey' value='{$_SESSION[$LEMsessid]['LEMpostKey']}' id='LEMpostKey' />\n";
         if (isset($token) && !empty($token)) {
             echo "\n<input type='hidden' name='token' value='{$token}' id='token' />\n";
         }
     }
     if (($LEMdebugLevel & LEM_DEBUG_TIMING) == LEM_DEBUG_TIMING) {
         echo LimeExpressionManager::GetDebugTimingMessage();
     }
     if (($LEMdebugLevel & LEM_DEBUG_VALIDATION_SUMMARY) == LEM_DEBUG_VALIDATION_SUMMARY) {
         echo "<table><tr><td align='left'><b>Group/Question Validation Results:</b>" . $moveResult['message'] . "</td></tr></table>\n";
     }
     echo "</form>\n";
     echo templatereplace(file_get_contents($sTemplatePath . "endpage.pstpl"), array(), $redata);
     echo "\n";
     doFooter();
 }
Esempio n. 17
0
 /**
  * @deprecated
  * */
 function oldbrowse($iSurveyID)
 {
     $aData = $this->_getData($iSurveyID);
     extract($aData);
     $aViewUrls = array();
     $sBrowseLanguage = $aData['language'];
     $tokenRequest = Yii::app()->request->getParam('token', null);
     /**
      * fnames is used as informational array
      * it containts
      *             $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
      */
     if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
         if (Yii::app()->request->getPost('sql')) {
             $aViewUrls[] = 'browseallfiltered_view';
         }
         //add token to top of list if survey is not private
         if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID)) {
             if (Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
                 $fnames[] = array("token", gT("Token ID"), 'code' => 'token');
                 $fnames[] = array("firstname", gT("First name"), 'code' => 'firstname');
                 // or token:firstname ?
                 $fnames[] = array("lastname", gT("Last name"), 'code' => 'lastname');
                 $fnames[] = array("email", gT("Email"), 'code' => 'email');
             }
         }
         $fnames[] = array("submitdate", gT("Completed"), gT("Completed"), "0", 'D');
         $fields = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
         foreach ($fields as $fielddetails) {
             if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate') {
                 continue;
             }
             $question = $fielddetails['question'];
             if ($fielddetails['type'] != "|") {
                 if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate' || $fielddetails['fieldname'] == 'token') {
                     continue;
                 }
                 // no headers for time data
                 if ($fielddetails['type'] == 'interview_time') {
                     continue;
                 }
                 if ($fielddetails['type'] == 'page_time') {
                     continue;
                 }
                 if ($fielddetails['type'] == 'answer_time') {
                     continue;
                 }
                 $fnames[] = array($fielddetails['fieldname'], viewHelper::getFieldText($fielddetails), 'code' => viewHelper::getFieldCode($fielddetails, array('LEMcompat' => true)));
             } elseif ($fielddetails['aid'] !== 'filecount') {
                 $qidattributes = getQuestionAttributeValues($fielddetails['qid']);
                 for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++) {
                     $filenum = sprintf(gT("File %s"), $i + 1);
                     if ($qidattributes['show_title'] == 1) {
                         $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . gT('Title') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(title)', "type" => "|", "metadata" => "title", "index" => $i);
                     }
                     if ($qidattributes['show_comment'] == 1) {
                         $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . gT('Comment') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(comment)', "type" => "|", "metadata" => "comment", "index" => $i);
                     }
                     $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . gT('File name') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(name)', "type" => "|", "metadata" => "name", "index" => $i);
                     $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . gT('File size') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(size)', "type" => "|", "metadata" => "size", "index" => $i);
                     //$fnames[] = array($fielddetails['fieldname'], "File ".($i+1)." - ".$fielddetails['question']."(extension)", "type"=>"|", "metadata"=>"ext",     "index"=>$i);
                 }
             } else {
                 $fnames[] = array($fielddetails['fieldname'], gT("File count"), 'code' => viewHelper::getFieldCode($fielddetails));
             }
         }
         $fncount = count($fnames);
         $start = (int) Yii::app()->request->getParam('start', 0);
         $limit = (int) Yii::app()->request->getParam('limit', 50);
         $order = Yii::app()->request->getParam('order', 'asc');
         if (!$limit) {
             $limit = 50;
         }
         $oCriteria = new CDbCriteria();
         //Create the query
         if ($aData['surveyinfo']['anonymized'] == "N" && tableExists("{{tokens_{$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
             $oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
         }
         if (incompleteAnsFilterState() == "incomplete") {
             $oCriteria->addCondition("submitdate IS NULL");
         } elseif (incompleteAnsFilterState() == "complete") {
             $oCriteria->addCondition("submitdate IS NOT NULL");
         }
         $dtcount = SurveyDynamic::model($iSurveyID)->count($oCriteria);
         // or die("Couldn't get response data<br />");
         if ($limit > $dtcount) {
             $limit = $dtcount;
         }
         //NOW LETS SHOW THE DATA
         if (Yii::app()->request->getPost('sql') && stripcslashes(Yii::app()->request->getPost('sql')) !== "" && Yii::app()->request->getPost('sql') != "NULL") {
             $oCriteria->addCondition(stripcslashes(Yii::app()->request->getPost('sql')));
         }
         if (!is_null($tokenRequest)) {
             $oCriteria->addCondition('t.token = ' . Yii::app()->db->quoteValue($tokenRequest));
         }
         $oCriteria->order = 'id ' . ($order == 'desc' ? 'desc' : 'asc');
         $oCriteria->offset = $start;
         $oCriteria->limit = $limit;
         $dtresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
         $dtcount2 = count($dtresult);
         $cells = $fncount + 1;
         // Fix start if order is desc, only if actual start is 0
         if ($order == 'desc' && $start == 0) {
             $start = $dtcount - count($dtresult);
         }
         //CONTROL MENUBAR
         $last = $start - $limit;
         $next = $start + $limit;
         $end = $dtcount - $limit;
         if ($end < 0) {
             $end = 0;
         }
         if ($last < 0) {
             $last = 0;
         }
         if ($next >= $dtcount) {
             $next = $dtcount - $limit;
         }
         if ($end < 0) {
             $end = 0;
         }
         $aData['dtcount2'] = $dtcount2;
         $aData['sCompletionStateValue'] = incompleteAnsFilterState();
         $aData['start'] = $start;
         $aData['limit'] = $limit;
         $aData['last'] = $last;
         $aData['next'] = $next;
         $aData['end'] = $end;
         $aData['fncount'] = $fncount;
         $aData['fnames'] = $fnames;
         $aData['bHasFileUploadQuestion'] = hasFileUploadQuestion($iSurveyID);
         $aViewUrls[] = 'browseallheader_view';
         $bgcc = 'even';
         foreach ($dtresult as $dtrow) {
             if ($bgcc == "even") {
                 $bgcc = "odd";
             } else {
                 $bgcc = "even";
             }
             $aData['dtrow'] = $dtrow;
             $aData['bgcc'] = $bgcc;
             $aData['sBrowseLanguage'] = $sBrowseLanguage;
             $aViewUrls['browseallrow_view'][] = $aData;
         }
         $aViewUrls[] = 'browseallfooter_view';
         $this->_renderWrappedTemplate('', $aViewUrls, $aData);
     } else {
         $aData['surveyid'] = $iSurveyID;
         $message['title'] = gT('Access denied!');
         $message['message'] = gT('You do not have sufficient rights to access this page.');
         $message['class'] = "error";
         $this->_renderWrappedTemplate('survey', array("message" => $message), $aData);
     }
 }
Esempio n. 18
0
 /**
  * Render satistics for users
  */
 public function simpleStatistics($surveyid)
 {
     $usegraph = 1;
     $iSurveyId = sanitize_int($surveyid);
     $aData['surveyid'] = $iSurveyId;
     $showcombinedresults = 0;
     $maxchars = 50;
     $statisticsoutput = '';
     $cr_statisticsoutput = '';
     // Set language for questions and answers to base language of this survey
     $language = Survey::model()->findByPk($surveyid)->language;
     $summary = array();
     $summary[0] = "datestampE";
     $summary[1] = "datestampG";
     $summary[2] = "datestampL";
     $summary[3] = "idG";
     $summary[4] = "idL";
     // 1: Get list of questions from survey
     $rows = Question::model()->getQuestionList($surveyid, $language);
     //SORT IN NATURAL ORDER!
     usort($rows, 'groupOrderThenQuestionOrder');
     // The questions to display (all question)
     foreach ($rows as $row) {
         $type = $row['type'];
         if ($type == "T" || $type == "N") {
             $summary[] = $type . $iSurveyId . 'X' . $row['gid'] . 'X' . $row['qid'];
         }
         switch ($type) {
             // Double scale cases
             case ":":
                 $qidattributes = getQuestionAttributeValues($row['qid']);
                 if (!$qidattributes['input_boxes']) {
                     $qid = $row['qid'];
                     $results = Question::model()->getQuestionsForStatistics('*', "parent_qid='{$qid}' AND language = '{$language}' AND scale_id = 0", 'question_order, title');
                     $fresults = Question::model()->getQuestionsForStatistics('*', "parent_qid='{$qid}' AND language = '{$language}' AND scale_id = 1", 'question_order, title');
                     foreach ($results as $row1) {
                         foreach ($fresults as $row2) {
                             $summary[] = $iSurveyId . 'X' . $row['gid'] . 'X' . $row['qid'] . $row1['title'] . '_' . $row2['title'];
                         }
                     }
                 }
                 break;
             case "1":
                 $qid = $row['qid'];
                 $results = Question::model()->getQuestionsForStatistics('*', "parent_qid='{$qid}' AND language = '{$language}'", 'question_order, title');
                 foreach ($results as $row1) {
                     $summary[] = $iSurveyId . 'X' . $row['gid'] . 'X' . $row['qid'] . $row1['title'] . '#0';
                     $summary[] = $iSurveyId . 'X' . $row['gid'] . 'X' . $row['qid'] . $row1['title'] . '#1';
                 }
                 break;
             case "R":
                 //RANKING
                 $qid = $row['qid'];
                 $results = Question::model()->getQuestionsForStatistics('title, question', "parent_qid='{$qid}' AND language = '{$language}'", 'question_order');
                 $count = count($results);
                 //loop through all answers. if there are 3 items to rate there will be 3 statistics
                 for ($i = 1; $i <= $count; $i++) {
                     $summary[] = $type . $iSurveyId . 'X' . $row['gid'] . 'X' . $row['qid'] . '-' . $i;
                 }
                 break;
                 // Cases with subquestions
             // Cases with subquestions
             case "A":
             case "F":
                 // FlEXIBLE ARRAY
             // FlEXIBLE ARRAY
             case "H":
                 // ARRAY (By Column)
             // ARRAY (By Column)
             case "E":
             case "B":
             case "C":
                 //loop through all answers. if there are 3 items to rate there will be 3 statistics
                 $qid = $row['qid'];
                 $results = Question::model()->getQuestionsForStatistics('title, question', "parent_qid='{$qid}' AND language = '{$language}'", 'question_order');
                 foreach ($results as $row1) {
                     $summary[] = $iSurveyId . 'X' . $row['gid'] . 'X' . $row['qid'] . $row1['title'];
                 }
                 break;
                 // Cases with subanwsers, need a question type as first letter
             // Cases with subanwsers, need a question type as first letter
             case "P":
                 //P - Multiple choice with comments
             //P - Multiple choice with comments
             case "M":
                 //M - Multiple choice
             //M - Multiple choice
             case "S":
                 $summary[] = $type . $iSurveyId . 'X' . $row['gid'] . 'X' . $row['qid'];
                 break;
                 // Not shown (else would only show 'no answer' )
             // Not shown (else would only show 'no answer' )
             case "K":
             case "*":
             case "D":
             case "T":
                 // Long free text
             // Long free text
             case "U":
                 // Huge free text
             // Huge free text
             case "|":
                 // File Upload, we don't show it
             // File Upload, we don't show it
             case "N":
             case "Q":
             case ';':
                 break;
             default:
                 $summary[] = $iSurveyId . 'X' . $row['gid'] . 'X' . $row['qid'];
                 break;
         }
     }
     // ----------------------------------- END FILTER FORM ---------------------------------------
     Yii::app()->loadHelper('admin/statistics');
     $helper = new statistics_helper();
     $showtextinline = isset($_POST['showtextinline']) ? 1 : 0;
     $aData['showtextinline'] = $showtextinline;
     //Show Summary results
     $aData['usegraph'] = $usegraph;
     $outputType = 'html';
     $statlang = returnGlobal('statlang');
     $statisticsoutput .= $helper->generate_simple_statistics($surveyid, $summary, $summary, $usegraph, $outputType, 'DD', $statlang);
     $aData['sStatisticsLanguage'] = $statlang;
     $aData['output'] = $statisticsoutput;
     $aData['summary'] = $summary;
     $aData['oStatisticsHelper'] = $helper;
     $aData['menu']['expertstats'] = true;
     //Call the javascript file
     App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(ADMIN_SCRIPT_PATH . 'statistics.js'));
     App()->getClientScript()->registerScriptFile(App()->getAssetManager()->publish(ADMIN_SCRIPT_PATH . 'json-js/json2.min.js'));
     echo $this->_renderWrappedTemplate('export', 'statistics_user_view', $aData);
 }
Esempio n. 19
0
 /**
  * Show printable survey
  */
 function index($surveyid, $lang = null)
 {
     $surveyid = sanitize_int($surveyid);
     if (!Permission::model()->hasSurveyPermission($surveyid, 'surveycontent', 'read')) {
         $aData['surveyid'] = $surveyid;
         App()->getClientScript()->registerPackage('jquery-superfish');
         $message['title'] = gT('Access denied!');
         $message['message'] = gT('You do not have sufficient rights to access this page.');
         $message['class'] = "error";
         $this->_renderWrappedTemplate('survey', array("message" => $message), $aData);
     } else {
         $aSurveyInfo = getSurveyInfo($surveyid, $lang);
         if (!$aSurveyInfo) {
             $this->getController()->error('Invalid survey ID');
         }
         SetSurveyLanguage($surveyid, $lang);
         $sLanguageCode = App()->language;
         $templatename = $aSurveyInfo['template'];
         $welcome = $aSurveyInfo['surveyls_welcometext'];
         $end = $aSurveyInfo['surveyls_endtext'];
         $surveyname = $aSurveyInfo['surveyls_title'];
         $surveydesc = $aSurveyInfo['surveyls_description'];
         $surveyactive = $aSurveyInfo['active'];
         $surveytable = "{{survey_" . $aSurveyInfo['sid'] . "}}";
         $surveyexpirydate = $aSurveyInfo['expires'];
         $surveyfaxto = $aSurveyInfo['faxto'];
         $dateformattype = $aSurveyInfo['surveyls_dateformat'];
         Yii::app()->loadHelper('surveytranslator');
         if (!is_null($surveyexpirydate)) {
             $dformat = getDateFormatData($dateformattype);
             $dformat = $dformat['phpdate'];
             $expirytimestamp = strtotime($surveyexpirydate);
             $expirytimeofday_h = date('H', $expirytimestamp);
             $expirytimeofday_m = date('i', $expirytimestamp);
             $surveyexpirydate = date($dformat, $expirytimestamp);
             if (!empty($expirytimeofday_h) || !empty($expirytimeofday_m)) {
                 $surveyexpirydate .= ' &ndash; ' . $expirytimeofday_h . ':' . $expirytimeofday_m;
             }
             sprintf(gT("Please submit by %s"), $surveyexpirydate);
         } else {
             $surveyexpirydate = '';
         }
         //Fix $templatename : control if print_survey.pstpl exist
         if (is_file(getTemplatePath($templatename) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
             $templatename = $templatename;
             // Change nothing
         } elseif (is_file(getTemplatePath(Yii::app()->getConfig("defaulttemplate")) . DIRECTORY_SEPARATOR . 'print_survey.pstpl')) {
             $templatename = Yii::app()->getConfig("defaulttemplate");
         } else {
             $templatename = "default";
         }
         $sFullTemplatePath = getTemplatePath($templatename) . DIRECTORY_SEPARATOR;
         $sFullTemplateUrl = getTemplateURL($templatename) . "/";
         define('PRINT_TEMPLATE_DIR', $sFullTemplatePath, true);
         define('PRINT_TEMPLATE_URL', $sFullTemplateUrl, true);
         LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $condition = "sid = '{$surveyid}' AND language = '{$sLanguageCode}'";
         $degresult = QuestionGroup::model()->getAllGroups($condition, array('group_order'));
         //xiao,
         if (!isset($surveyfaxto) || !$surveyfaxto and isset($surveyfaxnumber)) {
             $surveyfaxto = $surveyfaxnumber;
             //Use system fax number if none is set in survey.
         }
         $headelements = getPrintableHeader();
         //if $showsgqacode is enabled at config.php show table name for reference
         $showsgqacode = Yii::app()->getConfig("showsgqacode");
         if (isset($showsgqacode) && $showsgqacode == true) {
             $surveyname = $surveyname . "<br />[" . gT('Database') . " " . gT('table') . ": {$surveytable}]";
         } else {
             $surveyname = $surveyname;
         }
         $survey_output = array('SITENAME' => Yii::app()->getConfig("sitename"), 'SURVEYNAME' => $surveyname, 'SURVEYDESCRIPTION' => $surveydesc, 'WELCOME' => $welcome, 'END' => $end, 'THEREAREXQUESTIONS' => 0, 'SUBMIT_TEXT' => gT("Submit Your Survey."), 'SUBMIT_BY' => $surveyexpirydate, 'THANKS' => gT("Thank you for completing this survey."), 'HEADELEMENTS' => $headelements, 'TEMPLATEURL' => PRINT_TEMPLATE_URL, 'FAXTO' => $surveyfaxto, 'PRIVACY' => '', 'GROUPS' => '');
         $survey_output['FAX_TO'] = '';
         if (!empty($surveyfaxto) && $surveyfaxto != '000-00000000') {
             $survey_output['FAX_TO'] = gT("Please fax your completed survey to:") . " {$surveyfaxto}";
         }
         $total_questions = 0;
         $mapquestionsNumbers = array();
         $answertext = '';
         // otherwise can throw an error on line 1617
         $fieldmap = createFieldMap($surveyid, 'full', false, false, $sLanguageCode);
         // =========================================================
         // START doin the business:
         foreach ($degresult->readAll() as $degrow) {
             // ---------------------------------------------------
             // START doing groups
             $deqresult = Question::model()->getQuestions($surveyid, $degrow['gid'], $sLanguageCode, 0, '"I"');
             $deqrows = array();
             //Create an empty array in case FetchRow does not return any rows
             foreach ($deqresult->readAll() as $deqrow) {
                 $deqrows[] = $deqrow;
             }
             // Get table output into array
             // Perform a case insensitive natural sort on group name then question title of a multidimensional array
             usort($deqrows, 'groupOrderThenQuestionOrder');
             if ($degrow['description']) {
                 $group_desc = $degrow['description'];
             } else {
                 $group_desc = '';
             }
             $group = array('GROUPNAME' => $degrow['group_name'], 'GROUPDESCRIPTION' => $group_desc, 'QUESTIONS' => '');
             // A group can have only hidden questions. In that case you don't want to see the group's header/description either.
             $bGroupHasVisibleQuestions = false;
             $gid = $degrow['gid'];
             //Alternate bgcolor for different groups
             if (!isset($group['ODD_EVEN']) || $group['ODD_EVEN'] == ' g-row-even') {
                 $group['ODD_EVEN'] = ' g-row-odd';
             } else {
                 $group['ODD_EVEN'] = ' g-row-even';
             }
             //Loop through questions
             foreach ($deqrows as $deqrow) {
                 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
                 // START doing questions
                 $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
                 if ($qidattributes['hidden'] == 1 && $deqrow['type'] != '*') {
                     continue;
                 }
                 $bGroupHasVisibleQuestions = true;
                 //GET ANY CONDITIONS THAT APPLY TO THIS QUESTION
                 $printablesurveyoutput = '';
                 $sExplanation = '';
                 //reset conditions explanation
                 $s = 0;
                 // TMSW Condition->Relevance:  show relevance instead of this whole section to create $explanation
                 $scenarioresult = Condition::model()->getScenarios($deqrow['qid']);
                 $scenarioresult = $scenarioresult->readAll();
                 //Loop through distinct scenarios, thus grouping them together.
                 foreach ($scenarioresult as $scenariorow) {
                     if ($s == 0 && count($scenarioresult) > 1) {
                         $sExplanation .= '<p class="scenario">' . " -------- Scenario {$scenariorow['scenario']} --------</p>\n\n";
                     }
                     if ($s > 0) {
                         $sExplanation .= '<p class="scenario">' . ' -------- ' . gT("or") . " Scenario {$scenariorow['scenario']} --------</p>\n\n";
                     }
                     $x = 0;
                     $conditions1 = "qid={$deqrow['qid']} AND scenario={$scenariorow['scenario']}";
                     $distinctresult = Condition::model()->getSomeConditions(array('cqid', 'method', 'cfieldname'), $conditions1, array('cqid'), array('cqid', 'method', 'cfieldname'));
                     //Loop through each condition for a particular scenario.
                     foreach ($distinctresult->readAll() as $distinctrow) {
                         $condition = "qid = '{$distinctrow['cqid']}' AND parent_qid = 0 AND language = '{$sLanguageCode}'";
                         $subresult = Question::model()->find($condition);
                         if ($x > 0) {
                             $sExplanation .= ' <em class="scenario-and-separator">' . gT('and') . '</em> ';
                         }
                         if (trim($distinctrow['method']) == '') {
                             $distinctrow['method'] = '==';
                         }
                         if ($distinctrow['cqid']) {
                             // cqid != 0  ==> previous answer match
                             if ($distinctrow['method'] == '==') {
                                 $sExplanation .= gT("Answer was") . " ";
                             } elseif ($distinctrow['method'] == '!=') {
                                 $sExplanation .= gT("Answer was NOT") . " ";
                             } elseif ($distinctrow['method'] == '<') {
                                 $sExplanation .= gT("Answer was less than") . " ";
                             } elseif ($distinctrow['method'] == '<=') {
                                 $sExplanation .= gT("Answer was less than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>=') {
                                 $sExplanation .= gT("Answer was greater than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>') {
                                 $sExplanation .= gT("Answer was greater than") . " ";
                             } elseif ($distinctrow['method'] == 'RX') {
                                 $sExplanation .= gT("Answer matched (regexp)") . " ";
                             } else {
                                 $sExplanation .= gT("Answer was") . " ";
                             }
                         }
                         if (!$distinctrow['cqid']) {
                             // cqid == 0  ==> token attribute match
                             $tokenData = getTokenFieldsAndNames($surveyid);
                             preg_match('/^{TOKEN:([^}]*)}$/', $distinctrow['cfieldname'], $extractedTokenAttr);
                             $sExplanation .= "Your " . $tokenData[strtolower($extractedTokenAttr[1])]['description'] . " ";
                             if ($distinctrow['method'] == '==') {
                                 $sExplanation .= gT("is") . " ";
                             } elseif ($distinctrow['method'] == '!=') {
                                 $sExplanation .= gT("is NOT") . " ";
                             } elseif ($distinctrow['method'] == '<') {
                                 $sExplanation .= gT("is less than") . " ";
                             } elseif ($distinctrow['method'] == '<=') {
                                 $sExplanation .= gT("is less than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>=') {
                                 $sExplanation .= gT("is greater than or equal to") . " ";
                             } elseif ($distinctrow['method'] == '>') {
                                 $sExplanation .= gT("is greater than") . " ";
                             } elseif ($distinctrow['method'] == 'RX') {
                                 $sExplanation .= gT("is matched (regexp)") . " ";
                             } else {
                                 $sExplanation .= gT("is") . " ";
                             }
                             $answer_section = ' ' . $distinctrow['value'] . ' ';
                         }
                         $conresult = Condition::model()->getConditionsQuestions($distinctrow['cqid'], $deqrow['qid'], $scenariorow['scenario'], $sLanguageCode);
                         $conditions = array();
                         foreach ($conresult->readAll() as $conrow) {
                             $postans = "";
                             $value = $conrow['value'];
                             switch ($conrow['type']) {
                                 case "Y":
                                     switch ($conrow['value']) {
                                         case "Y":
                                             $conditions[] = gT("Yes");
                                             break;
                                         case "N":
                                             $conditions[] = gT("No");
                                             break;
                                     }
                                     break;
                                 case "G":
                                     switch ($conrow['value']) {
                                         case "M":
                                             $conditions[] = gT("Male");
                                             break;
                                         case "F":
                                             $conditions[] = gT("Female");
                                             break;
                                     }
                                     // switch
                                     break;
                                 case "A":
                                 case "B":
                                 case ":":
                                 case ";":
                                 case "5":
                                     $conditions[] = $conrow['value'];
                                     break;
                                 case "C":
                                     switch ($conrow['value']) {
                                         case "Y":
                                             $conditions[] = gT("Yes");
                                             break;
                                         case "U":
                                             $conditions[] = gT("Uncertain");
                                             break;
                                         case "N":
                                             $conditions[] = gT("No");
                                             break;
                                     }
                                     // switch
                                     break;
                                 case "E":
                                     switch ($conrow['value']) {
                                         case "I":
                                             $conditions[] = gT("Increase");
                                             break;
                                         case "D":
                                             $conditions[] = gT("Decrease");
                                             break;
                                         case "S":
                                             $conditions[] = gT("Same");
                                             break;
                                     }
                                 case "1":
                                     $labelIndex = preg_match("/^[^#]+#([01]{1})\$/", $conrow['cfieldname']);
                                     if ($labelIndex == 0) {
                                         // TIBO
                                         $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=0 AND language='{$sLanguageCode}'";
                                         $fresult = Answer::model()->getAllRecords($condition);
                                         foreach ($fresult->readAll() as $frow) {
                                             $postans = $frow['answer'];
                                             $conditions[] = $frow['answer'];
                                         }
                                         // while
                                     } elseif ($labelIndex == 1) {
                                         $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND scale_id=1 AND language='{$sLanguageCode}'";
                                         $fresult = Answer::model()->getAllRecords($condition);
                                         foreach ($fresult->readAll() as $frow) {
                                             $postans = $frow['answer'];
                                             $conditions[] = $frow['answer'];
                                         }
                                         // while
                                     }
                                     break;
                                 case "L":
                                 case "!":
                                 case "O":
                                 case "R":
                                     $condition = "qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Answer::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $conditions[] = $ansrow['answer'];
                                     }
                                     if ($conrow['value'] == "-oth-") {
                                         $conditions[] = gT("Other");
                                     }
                                     $conditions = array_unique($conditions);
                                     break;
                                 case "M":
                                 case "P":
                                     $condition = " parent_qid='{$conrow['cqid']}' AND title='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $conditions[] = $ansrow['question'];
                                     }
                                     $conditions = array_unique($conditions);
                                     break;
                                 case "N":
                                 case "K":
                                     $conditions[] = $value;
                                     break;
                                 case "F":
                                 case "H":
                                 default:
                                     $value = substr($conrow['cfieldname'], strpos($conrow['cfieldname'], "X" . $conrow['cqid']) + strlen("X" . $conrow['cqid']), strlen($conrow['cfieldname']));
                                     $condition = " qid='{$conrow['cqid']}' AND code='{$conrow['value']}' AND language='{$sLanguageCode}'";
                                     $fresult = Answer::model()->getAllRecords($condition);
                                     foreach ($fresult->readAll() as $frow) {
                                         $postans = $frow['answer'];
                                         $conditions[] = $frow['answer'];
                                     }
                                     // while
                                     break;
                             }
                             // switch
                             // Now let's complete the answer text with the answer_section
                             $answer_section = "";
                             switch ($conrow['type']) {
                                 case "A":
                                 case "B":
                                 case "C":
                                 case "E":
                                 case "F":
                                 case "H":
                                 case "K":
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $answer_section = " (" . $ansrow['question'] . ")";
                                     }
                                     break;
                                 case "1":
                                     // dual: (Label 1), (Label 2)
                                     $labelIndex = substr($conrow['cfieldname'], -1);
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     $cqidattributes = getQuestionAttributeValues($conrow['cqid']);
                                     if ($labelIndex == 0) {
                                         if (trim($cqidattributes['dualscale_headerA'][$sLanguageCode]) != '') {
                                             $header = gT($cqidattributes['dualscale_headerA'][$sLanguageCode]);
                                         } else {
                                             $header = '1';
                                         }
                                     } elseif ($labelIndex == 1) {
                                         if (trim($cqidattributes['dualscale_headerB'][$sLanguageCode]) != '') {
                                             $header = gT($cqidattributes['dualscale_headerB'][$sLanguageCode]);
                                         } else {
                                             $header = '2';
                                         }
                                     }
                                     foreach ($ansresult as $ansrow) {
                                         $answer_section = " (" . $ansrow->question . " " . sprintf(gT("Label %s"), $header) . ")";
                                     }
                                     break;
                                 case ":":
                                 case ";":
                                     //multi flexi: ( answer [label] )
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $condition = "parent_qid='{$conrow['cqid']}' AND title='{$thiscquestion['aid']}' AND language='{$sLanguageCode}'";
                                     $ansresult = Question::model()->findAll($condition);
                                     foreach ($ansresult as $ansrow) {
                                         $condition = "qid = '{$conrow['cqid']}' AND code = '{$conrow['value']}' AND language= '{$sLanguageCode}'";
                                         $fresult = Answer::model()->findAll($condition);
                                         foreach ($fresult as $frow) {
                                             //$conditions[]=$frow['title'];
                                             $answer_section = " (" . $ansrow->question . "[" . $frow['answer'] . "])";
                                         }
                                         // while
                                     }
                                     break;
                                 case "R":
                                     // (Rank 1), (Rank 2)... TIBO
                                     $thiscquestion = $fieldmap[$conrow['cfieldname']];
                                     $rankid = $thiscquestion['aid'];
                                     $answer_section = " (" . gT("RANK") . " {$rankid})";
                                     break;
                                 default:
                                     // nothing to add
                                     break;
                             }
                         }
                         if (count($conditions) > 1) {
                             $sExplanation .= "'" . implode("' <em class='scenario-or-separator'>" . gT("or") . "</em> '", $conditions) . "'";
                         } elseif (count($conditions) == 1) {
                             $sExplanation .= "'" . $conditions[0] . "'";
                         }
                         unset($conditions);
                         // Following line commented out because answer_section  was lost, but is required for some question types
                         //$explanation .= " ".gT("to question")." '".$mapquestionsNumbers[$distinctrow['cqid']]."' $answer_section ";
                         if ($distinctrow['cqid']) {
                             $sExplanation .= " <span class='scenario-at-separator'>" . gT("at question") . "</span> '" . $mapquestionsNumbers[$distinctrow['cqid']] . " [" . $subresult['title'] . "]' (" . strip_tags($subresult['question']) . "{$answer_section})";
                         } else {
                             $sExplanation .= " " . $distinctrow['value'];
                         }
                         //$distinctrow
                         $x++;
                     }
                     $s++;
                 }
                 $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
                 $relevance = trim($qinfo['info']['relevance']);
                 $sEquation = $qinfo['relEqn'];
                 if (trim($relevance) != '' && trim($relevance) != '1') {
                     if (isset($qidattributes['printable_help'][$sLanguageCode]) && $qidattributes['printable_help'][$sLanguageCode] != '') {
                         $sExplanation = $qidattributes['printable_help'][$sLanguageCode];
                     } elseif ($sExplanation == '') {
                         $sExplanation = $sEquation;
                         $sEquation = '&nbsp;';
                         // No need to show it twice
                     }
                     $sExplanation = "<b>" . gT('Only answer this question if the following conditions are met:') . "</b><br/> " . $sExplanation;
                     if (Yii::app()->getConfig('showrelevance')) {
                         $sExplanation .= "<span class='printable_equation'><br>" . $sEquation . "</span>";
                     }
                 } else {
                     $sExplanation = '';
                 }
                 ++$total_questions;
                 //TIBO map question qid to their q number
                 $mapquestionsNumbers[$deqrow['qid']] = $total_questions;
                 //END OF GETTING CONDITIONS
                 $qid = $deqrow['qid'];
                 $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
                 if (isset($showsgqacode) && $showsgqacode == true) {
                     $deqrow['question'] = $deqrow['question'] . "<br />" . gT("ID:") . " {$fieldname} <br />" . gT("Question code:") . " " . $deqrow['title'];
                 }
                 $question = array('QUESTION_NUMBER' => $total_questions, 'QUESTION_CODE' => $deqrow['title'], 'QUESTION_TEXT' => preg_replace('/(?:<br ?\\/?>|<\\/(?:p|h[1-6])>)$/is', '', $deqrow['question']), 'QUESTION_SCENARIO' => $sExplanation, 'QUESTION_MANDATORY' => '', 'QUESTION_ID' => $deqrow['qid'], 'QUESTION_CLASS' => getQuestionClass($deqrow['type']), 'QUESTION_TYPE_HELP' => $qinfo['validTip'], 'QUESTION_MAN_MESSAGE' => '', 'QUESTION_VALID_MESSAGE' => '', 'QUESTION_FILE_VALID_MESSAGE' => '', 'QUESTIONHELP' => '', 'ANSWER' => '');
                 $showqnumcode = Yii::app()->getConfig('showqnumcode');
                 if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'N' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'number' || $showqnumcode == 'none') {
                     $question['QUESTION_CODE'] = '';
                 }
                 if ($showqnumcode == 'choose' && ($aSurveyInfo['showqnumcode'] == 'C' || $aSurveyInfo['showqnumcode'] == 'X') || $showqnumcode == 'code' || $showqnumcode == 'none') {
                     $question['QUESTION_NUMBER'] = '';
                 }
                 if ($question['QUESTION_TYPE_HELP'] != "") {
                     $question['QUESTION_TYPE_HELP'] .= "<br />\n";
                 }
                 if ($deqrow['mandatory'] == 'Y') {
                     $question['QUESTION_MANDATORY'] = gT('*');
                     $question['QUESTION_CLASS'] .= ' mandatory';
                 }
                 //DIFFERENT TYPES OF DATA FIELD HERE
                 if ($deqrow['help']) {
                     $question['QUESTIONHELP'] = $deqrow['help'];
                 }
                 if (!empty($qidattributes['page_break'])) {
                     $question['QUESTION_CLASS'] .= ' breakbefore ';
                 }
                 if (isset($qidattributes['maximum_chars']) && $qidattributes['maximum_chars'] != '') {
                     $question['QUESTION_CLASS'] = "max-chars-{$qidattributes['maximum_chars']} " . $question['QUESTION_CLASS'];
                 }
                 switch ($deqrow['type']) {
                     // ==================================================================
                     case "5":
                         //5 POINT CHOICE
                         $question['QUESTION_TYPE_HELP'] .= gT('Please choose *only one* of the following:');
                         $question['ANSWER'] .= "\n\t<ul>\n";
                         for ($i = 1; $i <= 5; $i++) {
                             $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $i) . "\n\t\t\t{$i} " . self::_addsgqacode("({$i})") . "\n\t\t</li>\n";
                         }
                         $question['ANSWER'] .= "\t</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "D":
                         //DATE
                         $question['QUESTION_TYPE_HELP'] .= gT('Please enter a date:');
                         $question['ANSWER'] .= "\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 30, 1);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "G":
                         //GENDER
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['ANSWER'] .= "\n\t<ul>\n";
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Female")) . "\n\t\t\t" . gT("Female") . " " . self::_addsgqacode("(F)") . "\n\t\t</li>\n";
                         $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', gT("Male")) . "\n\t\t\t" . gT("Male") . " " . self::_addsgqacode("(M)") . "\n\t\t</li>\n";
                         $question['ANSWER'] .= "\t</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "L":
                         //LIST drop-down/radio-button list
                         // ==================================================================
                     //LIST drop-down/radio-button list
                     // ==================================================================
                     case "!":
                         //List - dropdown
                         if (isset($qidattributes['display_columns']) && trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         if (isset($qidattributes['category_separator']) && trim($qidattributes['category_separator']) != '') {
                             $optCategorySeparator = $qidattributes['category_separator'];
                         } else {
                             unset($optCategorySeparator);
                         }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('sortorder', 'answer'));
                         $dearesult = $dearesult->readAll();
                         $deacount = count($dearesult);
                         if ($deqrow['other'] == "Y") {
                             $deacount++;
                         }
                         $wrapper = setupColumns(0, $deacount);
                         $question['ANSWER'] = $wrapper['whole-start'];
                         $rowcounter = 0;
                         $colcounter = 1;
                         foreach ($dearesult as $dearow) {
                             if (isset($optCategorySeparator)) {
                                 list($category, $answer) = explode($optCategorySeparator, $dearow['answer']);
                                 if ($category != '') {
                                     $dearow['answer'] = "({$category}) {$answer} " . self::_addsgqacode("(" . $dearow['code'] . ")");
                                 } else {
                                     $dearow['answer'] = $answer . self::_addsgqacode(" (" . $dearow['code'] . ")");
                                 }
                                 $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . "\n" . $wrapper['item-end'];
                             } else {
                                 $question['ANSWER'] .= "\t" . $wrapper['item-start'] . "\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n" . $wrapper['item-end'];
                             }
                             ++$rowcounter;
                             if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                                 if ($colcounter == $wrapper['cols'] - 1) {
                                     $question['ANSWER'] .= $wrapper['col-devide-last'];
                                 } else {
                                     $question['ANSWER'] .= $wrapper['col-devide'];
                                 }
                                 $rowcounter = 0;
                                 ++$colcounter;
                             }
                         }
                         if ($deqrow['other'] == 'Y') {
                             if (trim($qidattributes["other_replace_text"][$sLanguageCode]) == '') {
                                 $qidattributes["other_replace_text"][$sLanguageCode] = gT("Other");
                             }
                             //                    $printablesurveyoutput .="\t".$wrapper['item-start']."\t\t".self::_input_type_image('radio' , gT("Other"))."\n\t\t\t".gT("Other")."\n\t\t\t<input type='text' size='30' readonly='readonly' />\n".$wrapper['item-end'];
                             $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('radio', gT($qidattributes["other_replace_text"][$sLanguageCode])) . ' ' . gT($qidattributes["other_replace_text"][$sLanguageCode]) . self::_addsgqacode(" (-oth-)") . "\n\t\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "other)") . "\n" . $wrapper['item-end'];
                         }
                         $question['ANSWER'] .= $wrapper['whole-end'];
                         //Let's break the presentation into columns.
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "O":
                         //LIST WITH COMMENT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $dearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer'));
                         $question['ANSWER'] = "\t<ul>\n";
                         foreach ($dearesult->readAll() as $dearow) {
                             $question['ANSWER'] .= "\t\t<li>\n\t\t\t" . self::_input_type_image('radio', $dearow['answer']) . "\n\t\t\t" . $dearow['answer'] . self::_addsgqacode(" (" . $dearow['code'] . ")") . "\n\t\t</li>\n";
                         }
                         $question['ANSWER'] .= "\t</ul>\n";
                         $question['ANSWER'] .= "\t<p class=\"comment\">\n\t\t" . gT("Make a comment on your choice here:") . "\n";
                         $question['ANSWER'] .= "\t\t" . self::_input_type_image('textarea', gT("Make a comment on your choice here:"), 50, 8) . self::_addsgqacode(" (" . $deqrow['sid'] . "X" . $deqrow['gid'] . "X" . $deqrow['qid'] . "comment)") . "\n\t</p>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "R":
                         //RANKING Type Question
                         $rearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('sortorder', 'answer'));
                         $rearesult = $rearesult->readAll();
                         $reacount = count($rearesult);
                         $question['QUESTION_TYPE_HELP'] .= gT("Please number each box in order of preference from 1 to") . " {$reacount}";
                         $question['QUESTION_TYPE_HELP'] .= self::_min_max_answers_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = "\n<ul>\n";
                         foreach ($rearesult as $rearow) {
                             $question['ANSWER'] .= "\t<li>\n\t" . self::_input_type_image('rank', '', 4, 1) . "\n\t\t&nbsp;" . $rearow['answer'] . self::_addsgqacode(" (" . $fieldname . $rearow['code'] . ")") . "\n\t</li>\n";
                         }
                         $question['ANSWER'] .= "\n</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "M":
                         //Multiple choice (Quite tricky really!)
                         if (trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *all* that apply:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order'));
                         $mearesult = $mearesult->readAll();
                         $meacount = count($mearesult);
                         if ($deqrow['other'] == 'Y') {
                             $meacount++;
                         }
                         $wrapper = setupColumns($dcols, $meacount);
                         $question['ANSWER'] = $wrapper['whole-start'];
                         $rowcounter = 0;
                         $colcounter = 1;
                         foreach ($mearesult as $mearow) {
                             $question['ANSWER'] .= $wrapper['item-start'] . self::_input_type_image('checkbox', $mearow['question']) . "\n\t\t" . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . $wrapper['item-end'];
                             ++$rowcounter;
                             if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols']) {
                                 if ($colcounter == $wrapper['cols'] - 1) {
                                     $question['ANSWER'] .= $wrapper['col-devide-last'];
                                 } else {
                                     $question['ANSWER'] .= $wrapper['col-devide'];
                                 }
                                 $rowcounter = 0;
                                 ++$colcounter;
                             }
                         }
                         if ($deqrow['other'] == "Y") {
                             if (trim($qidattributes['other_replace_text'][$sLanguageCode]) == '') {
                                 $qidattributes["other_replace_text"][$sLanguageCode] = "Other";
                             }
                             if (!isset($mearow['answer'])) {
                                 $mearow['answer'] = "";
                             }
                             $question['ANSWER'] .= $wrapper['item-start-other'] . self::_input_type_image('checkbox', $mearow['answer']) . gT($qidattributes["other_replace_text"][$sLanguageCode]) . ":\n\t\t" . self::_input_type_image('other') . self::_addsgqacode(" (" . $fieldname . "other) ") . $wrapper['item-end'];
                         }
                         $question['ANSWER'] .= $wrapper['whole-end'];
                         //                }
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "P":
                         //Multiple choice with comments
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose all that apply and provide a comment:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}'", array('question_order'));
                         //                $printablesurveyoutput .="\t\t\t<u>".gT("Please choose all that apply and provide a comment:")."</u><br />\n";
                         $j = 0;
                         $longest_string = 0;
                         foreach ($mearesult->readAll() as $mearow) {
                             $longest_string = longestString($mearow['question'], $longest_string);
                             $question['ANSWER'] .= "\t<li><span>\n\t\t" . self::_input_type_image('checkbox', $mearow['question']) . $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "</span>\n\t\t" . self::_input_type_image('text', 'comment box', 60) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "comment) ") . "\n\t</li>\n";
                             $j++;
                         }
                         if ($deqrow['other'] == "Y") {
                             $question['ANSWER'] .= "\t<li class=\"other\">\n\t\t<div class=\"other-replacetext\">" . gT('Other:') . self::_input_type_image('other', '', 1) . "</div>" . self::_input_type_image('othercomment', 'comment box', 50) . self::_addsgqacode(" (" . $fieldname . "other) ") . "\n\t</li>\n";
                             $j++;
                         }
                         $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "Q":
                         //MULTIPLE SHORT TEXT
                         $width = 60;
                         // ==================================================================
                     // ==================================================================
                     case "K":
                         //MULTIPLE NUMERICAL
                         $question['QUESTION_TYPE_HELP'] = "";
                         $width = isset($width) ? $width : 16;
                         //                            if (!empty($qidattributes['equals_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= "* ".sprintf(gT('Total of all entries must equal %d'),$qidattributes['equals_num_value'])."<br />\n";
                         //                            }
                         //                            if (!empty($qidattributes['max_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must not exceed %d'), $qidattributes['max_num_value'])."<br />\n";
                         //                            }
                         //                            if (!empty($qidattributes['min_num_value']))
                         //                            {
                         //                                $question['QUESTION_TYPE_HELP'] .= sprintf(gT('Total of all entries must be at least %s'),$qidattributes['min_num_value'])."<br />\n";
                         //                            }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer(s) here:");
                         $longest_string = 0;
                         $mearesult = Question::model()->getAllRecords("parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}'", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $longest_string = longestString($mearow['question'], $longest_string);
                             if (isset($qidattributes['slider_layout']) && $qidattributes['slider_layout'] == 1) {
                                 $mearow['question'] = explode(':', $mearow['question']);
                                 $mearow['question'] = $mearow['question'][0];
                             }
                             $question['ANSWER'] .= "\t<li>\n\t\t<span>" . $mearow['question'] . "</span>\n\t\t" . self::_input_type_image('text', $mearow['question'], $width) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ") ") . "\n\t</li>\n";
                         }
                         $question['ANSWER'] = "\n<ul>\n" . $question['ANSWER'] . "</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "S":
                         //SHORT TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 50);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "T":
                         //LONG TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 8);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "U":
                         //HUGE TEXT
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = self::_input_type_image('textarea', $question['QUESTION_TYPE_HELP'], '100%', 30);
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "N":
                         //NUMERICAL
                         $prefix = "";
                         $suffix = "";
                         if ($qidattributes['prefix'][$sLanguageCode] != "") {
                             $prefix = $qidattributes['prefix'][$sLanguageCode];
                         }
                         if ($qidattributes['suffix'][$sLanguageCode] != "") {
                             $suffix = $qidattributes['suffix'][$sLanguageCode];
                         }
                         $question['QUESTION_TYPE_HELP'] .= gT("Please write your answer here:");
                         $question['ANSWER'] = "<ul>\n\t<li>\n\t\t<span>{$prefix}</span>\n\t\t" . self::_input_type_image('text', $question['QUESTION_TYPE_HELP'], 20) . "\n\t\t<span>{$suffix}</span>\n\t\t</li>\n\t</ul>";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "Y":
                         //YES/NO
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose *only one* of the following:");
                         $question['ANSWER'] = "\n<ul>\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('Yes')) . "\n\t\t" . gT('Yes') . self::_addsgqacode(" (Y)") . "\n\t</li>\n";
                         $question['ANSWER'] .= "\n\t<li>\n\t\t" . self::_input_type_image('radio', gT('No')) . "\n\t\t" . gT('No') . self::_addsgqacode(" (N)") . "\n\t</li>\n</ul>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "A":
                         //ARRAY (5 POINT CHOICE)
                         $condition = "parent_qid = '{$deqrow['qid']}'  AND language= '{$sLanguageCode}'";
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = "\n            <table>\n                <thead>\n                    <tr>\n                        <td>&nbsp;</td>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>1&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (1)") . "</th>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>2&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (2)") . "</th>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>3&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (3)") . "</th>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>4&nbsp;&nbsp;&nbsp;&nbsp;" . self::_addsgqacode(" (4)") . "</th>\n                        <th style='font-family:Arial,helvetica,sans-serif;font-weight:normal;'>5" . self::_addsgqacode(" (5)") . "</th>\n                    </tr>\n                </thead>\n                <tbody>";
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords($condition, array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " ";
                             } else {
                                 $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")");
                             }
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= 5; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             }
                             $answertext .= $mearow['question'];
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "B":
                         //ARRAY (10 POINT CHOICE)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         for ($i = 1; $i <= 10; $i++) {
                             $question['ANSWER'] .= "\t\t\t<th>{$i}" . self::_addsgqacode(" ({$i})") . "</th>\n";
                         }
                         $question['ANSWER'] .= "\t</thead>\n\n\t<tbody>\n";
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                             $rowclass = alternation($rowclass, 'row');
                             for ($i = 1; $i <= 10; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', $i) . "</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "C":
                         //ARRAY (YES/UNCERTAIN/NO)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = '
         <table>
             <thead>
                 <tr>
                     <td>&nbsp;</td>
                     <th>' . gT("Yes") . self::_addsgqacode(" (Y)") . '</th>
                     <th>' . gT("Uncertain") . self::_addsgqacode(" (U)") . '</th>
                     <th>' . gT("No") . self::_addsgqacode(" (N)") . '</th>
                 </tr>
             </thead>
             <tbody>
         ';
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Yes")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Uncertain")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("No")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                             $rowclass = alternation($rowclass, 'row');
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                     case "E":
                         //ARRAY (Increase/Same/Decrease)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] = '
         <table>
             <thead>
                 <tr>
                     <td>&nbsp;</td>
                     <th>' . gT("Increase") . self::_addsgqacode(" (I)") . '</th>
                     <th>' . gT("Same") . self::_addsgqacode(" (S)") . '</th>
                     <th>' . gT("Decrease") . self::_addsgqacode(" (D)") . '</th>
                 </tr>
             </thead>
             <tbody>
         ';
                         $j = 0;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['question']}" . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . "</th>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Increase")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Same")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio', gT("Decrease")) . "</td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $j++;
                             $rowclass = alternation($rowclass, 'row');
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case ":":
                         //ARRAY (Multi Flexible) (Numbers)
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                             $maxvalue = $qidattributes['multiflexible_max'];
                             $minvalue = 1;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                             $minvalue = $qidattributes['multiflexible_min'];
                             $maxvalue = $qidattributes['multiflexible_min'] + 10;
                         }
                         if (trim($qidattributes['multiflexible_min']) == '' && trim($qidattributes['multiflexible_max']) == '') {
                             $minvalue = 1;
                             $maxvalue = 10;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                             if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                                 $minvalue = $qidattributes['multiflexible_min'];
                                 $maxvalue = $qidattributes['multiflexible_max'];
                             }
                         }
                         if (trim($qidattributes['multiflexible_step']) != '') {
                             $stepvalue = $qidattributes['multiflexible_step'];
                         } else {
                             $stepvalue = 1;
                         }
                         if ($qidattributes['multiflexible_checkbox'] != 0) {
                             $checkboxlayout = true;
                         } else {
                             $checkboxlayout = false;
                         }
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=1 AND language='{$sLanguageCode}' ", array('question_order'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         //array to temporary store X axis question codes
                         $xaxisarray = array();
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                             $i++;
                             //add current question code
                             $xaxisarray[$i] = $frow['title'];
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $a = 1;
                         //Counter for pdfoutput
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' and scale_id=0 AND language='{$sLanguageCode}' ", array('question_order'));
                         $result = $mearesult->readAll();
                         foreach ($result as $frow) {
                             $question['ANSWER'] .= "\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $answertext = $frow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, 0, strpos($answertext, '|'));
                             }
                             $question['ANSWER'] .= "\t\t\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             //$printablesurveyoutput .="\t\t\t\t\t<td>";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>\n";
                                 if ($checkboxlayout === false) {
                                     $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 4) . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 } else {
                                     $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('checkbox') . self::_addsgqacode(" (" . $fieldname . $frow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 }
                                 $question['ANSWER'] .= "\t\t\t</td>\n";
                             }
                             $answertext = $frow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, strpos($answertext, '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case ";":
                         //ARRAY (Multi Flexible) (text)
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('question_order'));
                         $mearesult = $mearesult->readAll();
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fresult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND scale_id=1 AND language='{$sLanguageCode}' ", array('question_order'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         //array to temporary store X axis question codes
                         $xaxisarray = array();
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}</th>\n";
                             $i++;
                             //add current question code
                             $xaxisarray[$i] = $frow['title'];
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n<tbody>\n";
                         $a = 1;
                         $rowclass = 'array1';
                         foreach ($mearesult as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $answertext = $mearow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, 0, strpos($answertext, '|'));
                             }
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>\n";
                                 $question['ANSWER'] .= "\t\t\t\t" . self::_input_type_image('text', '', 23) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "_" . $xaxisarray[$i] . ") ") . "\n";
                                 $question['ANSWER'] .= "\t\t\t</td>\n";
                             }
                             $answertext = $mearow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, strpos($answertext, '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "F":
                         //ARRAY (Flexible Labels)
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $fresult = Answer::model()->getAllRecords(" scale_id=0 AND qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}'", array('sortorder', 'code'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 1;
                         $column_headings = array();
                         foreach ($fresult as $frow) {
                             $column_headings[] = $frow['answer'] . self::_addsgqacode(" (" . $frow['code'] . ")");
                         }
                         if (trim($qidattributes['answer_width']) != '') {
                             $iAnswerWidth = 100 - $qidattributes['answer_width'];
                         } else {
                             $iAnswerWidth = 80;
                         }
                         if (count($column_headings) > 0) {
                             $col_width = round($iAnswerWidth / count($column_headings));
                         } else {
                             $heading = '';
                         }
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n";
                         $question['ANSWER'] .= "\t\t\t<td>&nbsp;</td>\n";
                         foreach ($column_headings as $heading) {
                             $question['ANSWER'] .= "\t\t\t<th style=\"width:{$col_width}%;\">{$heading}</th>\n";
                         }
                         $i++;
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $counter = 1;
                         $rowclass = 'array1';
                         $mearesult = Question::model()->getAllRecords(" parent_qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             if (trim($answertext) == '') {
                                 $answertext = '&nbsp;';
                             }
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext = substr($mearow['question'], 0, strpos($mearow['question'], '|')) . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")") . " ";
                             } else {
                                 $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . ")");
                             }
                             if (trim($qidattributes['answer_width']) != '') {
                                 $sInsertStyle = ' style="width:' . $qidattributes['answer_width'] . '%" ';
                             } else {
                                 $sInsertStyle = '';
                             }
                             $question['ANSWER'] .= "\t\t\t<th {$sInsertStyle} class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             $counter++;
                             $answertext = $mearow['question'];
                             //semantic differential question type?
                             if (strpos($mearow['question'], '|')) {
                                 $answertext2 = substr($mearow['question'], strpos($mearow['question'], '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext2}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "1":
                         //ARRAY (Flexible Labels) multi scale
                         $leftheader = $qidattributes['dualscale_headerA'][$sLanguageCode];
                         $rightheader = $qidattributes['dualscale_headerB'][$sLanguageCode];
                         $headstyle = 'style="padding-left: 20px; padding-right: 7px"';
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['QUESTION_TYPE_HELP'] .= self::_array_filter_help($qidattributes, $sLanguageCode, $surveyid);
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n";
                         $condition = "qid= '{$deqrow['qid']}'  AND language= '{$sLanguageCode}' AND scale_id=0";
                         $fresult = Answer::model()->getAllRecords($condition, array('sortorder', 'code'));
                         $fresult = $fresult->readAll();
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $l1 = 0;
                         $printablesurveyoutput2 = "\t\t\t<td>&nbsp;</td>\n";
                         $myheader2 = '';
                         foreach ($fresult as $frow) {
                             $printablesurveyoutput2 .= "\t\t\t<th>{$frow['answer']}" . self::_addsgqacode(" (" . $frow['code'] . ")") . "</th>\n";
                             $myheader2 .= "<td></td>";
                             $l1++;
                         }
                         // second scale
                         $printablesurveyoutput2 .= "\t\t\t<td>&nbsp;</td>\n";
                         //$fquery1 = "SELECT * FROM {{answers}} WHERE qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' AND scale_id=1 ORDER BY sortorder, code";
                         // $fresult1 = Yii::app()->db->createCommand($fquery1)->query();
                         $fresult1 = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}'  AND language='{$sLanguageCode}' AND scale_id=1 ", array('sortorder', 'code'));
                         $fresult1 = $fresult1->readAll();
                         $fcount1 = count($fresult1);
                         $fwidth = "120";
                         $l2 = 0;
                         //array to temporary store second scale question codes
                         $scale2array = array();
                         foreach ($fresult1 as $frow1) {
                             $printablesurveyoutput2 .= "\t\t\t<th>{$frow1['answer']}" . self::_addsgqacode(" (" . $frow1['code'] . ")") . "</th>\n";
                             //add current question code
                             $scale2array[$l2] = $frow1['code'];
                             $l2++;
                         }
                         // build header if needed
                         if ($leftheader != '' || $rightheader != '') {
                             $myheader = "\t\t\t<td>&nbsp;</td>";
                             $myheader .= "\t\t\t<th colspan=\"" . $l1 . "\">{$leftheader}</th>\n";
                             if ($rightheader != '') {
                                 // $myheader .= "\t\t\t\t\t" .$myheader2;
                                 $myheader .= "\t\t\t<td>&nbsp;</td>";
                                 $myheader .= "\t\t\t<th colspan=\"" . $l2 . "\">{$rightheader}</td>\n";
                             }
                             $myheader .= "\t\t\t\t</tr>\n";
                         } else {
                             $myheader = '';
                         }
                         $question['ANSWER'] .= $myheader . "\t\t</tr>\n\n\t\t<tr>\n";
                         $question['ANSWER'] .= $printablesurveyoutput2;
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $rowclass = 'array1';
                         //counter for each subquestion
                         $sqcounter = 0;
                         $mearesult = Question::model()->getAllRecords(" parent_qid={$deqrow['qid']}  AND language='{$sLanguageCode}' ", array('question_order'));
                         foreach ($mearesult->readAll() as $mearow) {
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $answertext = $mearow['question'] . self::_addsgqacode(" (" . $fieldname . $mearow['title'] . "#0) / (" . $fieldname . $mearow['title'] . "#1)");
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, 0, strpos($answertext, '|'));
                             }
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$answertext}</th>\n";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             $question['ANSWER'] .= "\t\t\t<td>&nbsp;</td>\n";
                             for ($i = 1; $i <= $fcount1; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             $answertext = $mearow['question'];
                             if (strpos($answertext, '|')) {
                                 $answertext = substr($answertext, strpos($answertext, '|') + 1);
                                 $question['ANSWER'] .= "\t\t\t<th class=\"answertextright\">{$answertext}</th>\n";
                             }
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             //increase subquestion counter
                             $sqcounter++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                         // ==================================================================
                     // ==================================================================
                     case "H":
                         //ARRAY (Flexible Labels) by Column
                         //$headstyle="style='border-left-style: solid; border-left-width: 1px; border-left-color: #AAAAAA'";
                         $headstyle = "style='padding-left: 20px; padding-right: 7px'";
                         $condition = "parent_qid= '{$deqrow['qid']}'  AND language= '{$sLanguageCode}'";
                         $fresult = Question::model()->getAllRecords($condition, array('question_order', 'title'));
                         $fresult = $fresult->readAll();
                         $question['QUESTION_TYPE_HELP'] .= gT("Please choose the appropriate response for each item:");
                         $question['ANSWER'] .= "\n<table>\n\t<thead>\n\t\t<tr>\n\t\t\t<td>&nbsp;</td>\n";
                         $fcount = count($fresult);
                         $fwidth = "120";
                         $i = 0;
                         foreach ($fresult as $frow) {
                             $question['ANSWER'] .= "\t\t\t<th>{$frow['question']}" . self::_addsgqacode(" (" . $fieldname . $frow['title'] . ")") . "</th>\n";
                             $i++;
                         }
                         $question['ANSWER'] .= "\t\t</tr>\n\t</thead>\n\n\t<tbody>\n";
                         $a = 1;
                         $rowclass = 'array1';
                         $mearesult = Answer::model()->getAllRecords(" qid='{$deqrow['qid']}' AND scale_id=0 AND language='{$sLanguageCode}' ", array('sortorder', 'code'));
                         foreach ($mearesult->readAll() as $mearow) {
                             //$_POST['type']=$type;
                             $question['ANSWER'] .= "\t\t<tr class=\"{$rowclass}\">\n";
                             $rowclass = alternation($rowclass, 'row');
                             $question['ANSWER'] .= "\t\t\t<th class=\"answertext\">{$mearow['answer']}" . self::_addsgqacode(" (" . $mearow['code'] . ")") . "</th>\n";
                             //$printablesurveyoutput .="\t\t\t\t\t<td>";
                             for ($i = 1; $i <= $fcount; $i++) {
                                 $question['ANSWER'] .= "\t\t\t<td>" . self::_input_type_image('radio') . "</td>\n";
                             }
                             //$printablesurveyoutput .="\t\t\t\t\t</tr></table></td>\n";
                             $question['ANSWER'] .= "\t\t</tr>\n";
                             $a++;
                         }
                         $question['ANSWER'] .= "\t</tbody>\n</table>\n";
                         break;
                     case "|":
                         // File Upload
                         $question['QUESTION_TYPE_HELP'] .= "Kindly attach the aforementioned documents along with the survey";
                         break;
                         // === END SWITCH ===================================================
                 }
                 $question['QUESTION_TYPE_HELP'] = self::_star_replace($question['QUESTION_TYPE_HELP']);
                 $group['QUESTIONS'] .= self::_populate_template('question', $question);
             }
             if ($bGroupHasVisibleQuestions) {
                 $survey_output['GROUPS'] .= self::_populate_template('group', $group);
             }
         }
         $survey_output['THEREAREXQUESTIONS'] = str_replace('{NUMBEROFQUESTIONS}', $total_questions, gT('There are {NUMBEROFQUESTIONS} questions in this survey'));
         // START recursive tag stripping.
         // PHP 5.1.0 introduced the count parameter for preg_replace() and thus allows this procedure to run with only one regular expression.
         // Previous version of PHP needs two regular expressions to do the same thing and thus will run a bit slower.
         $server_is_newer = version_compare(PHP_VERSION, '5.1.0', '>');
         $rounds = 0;
         while ($rounds < 1) {
             $replace_count = 0;
             if ($server_is_newer) {
                 $survey_output['GROUPS'] = preg_replace(array('/<td>(?:&nbsp;|&#160;| )?<\\/td>/isU', '/<th[^>]*>(?:&nbsp;|&#160;| )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS'], -1, $replace_count);
             } else {
                 $survey_output['GROUPS'] = preg_replace(array('/<td>(?:&nbsp;|&#160;| )?<\\/td>/isU', '/<th[^>]*>(?:&nbsp;|&#160;| )?<\\/th>/isU', '/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU'), array('[[EMPTY-TABLE-CELL]]', '[[EMPTY-TABLE-CELL-HEADER]]', ''), $survey_output['GROUPS']);
                 $replace_count = preg_match('/<([^ >]+)[^>]*>(?:&nbsp;|&#160;|\\r\\n|\\n\\r|\\n|\\r|\\t| )*<\\/\\1>/isU', $survey_output['GROUPS']);
             }
             if ($replace_count == 0) {
                 ++$rounds;
                 $survey_output['GROUPS'] = preg_replace(array('/\\[\\[EMPTY-TABLE-CELL\\]\\]/', '/\\[\\[EMPTY-TABLE-CELL-HEADER\\]\\]/', '/\\n(?:\\t*\\n)+/'), array('<td>&nbsp;</td>', '<th>&nbsp;</th>', "\n"), $survey_output['GROUPS']);
             }
         }
         $survey_output['GROUPS'] = preg_replace('/(<div[^>]*>){NOTEMPTY}(<\\/div>)/', '\\1&nbsp;\\2', $survey_output['GROUPS']);
         // END recursive empty tag stripping.
         echo self::_populate_template('survey', $survey_output);
     }
     // End print
 }
Esempio n. 20
0
 public function doQuestion($ia)
 {
     global $thissurvey;
     if ($thissurvey['nokeyboard'] == 'Y') {
         includeKeypad();
         $kpclass = "text-keypad";
     } else {
         $kpclass = "";
     }
     $checkconditionFunction = "checkconditions";
     $aQuestionAttributes = getQuestionAttributeValues($ia[0]);
     $query = "SELECT other FROM {{questions}} WHERE qid=" . $ia[0] . " AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' ";
     $result = Yii::app()->db->createCommand($query)->query();
     foreach ($result->readAll() as $row) {
         $other = $row['other'];
     }
     //question attribute random order set?
     if ($aQuestionAttributes['random_order'] == 1) {
         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY " . dbRandom();
     } elseif ($aQuestionAttributes['alphasort'] == 1) {
         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY answer";
     } else {
         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$ia['0']} AND language='" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang'] . "' and scale_id=0 ORDER BY sortorder, answer";
     }
     $ansresult = dbExecuteAssoc($ansquery)->readAll();
     //Checked
     $anscount = count($ansresult);
     if (trim($aQuestionAttributes['display_columns']) != '') {
         $dcols = $aQuestionAttributes['display_columns'];
     } else {
         $dcols = 1;
     }
     if (trim($aQuestionAttributes['other_replace_text'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']]) != '') {
         $othertext = $aQuestionAttributes['other_replace_text'][$_SESSION['survey_' . Yii::app()->getConfig('surveyID')]['s_lang']];
     } else {
         $othertext = gT('Other:');
     }
     if (isset($other) && $other == 'Y') {
         $anscount++;
     }
     //Count up for the Other answer
     if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
         $anscount++;
     }
     //Count up if "No answer" is showing
     $wrapper = setupColumns($dcols, $anscount, "answers-list radio-list", "answer-item radio-item");
     $iBootCols = round(12 / $dcols);
     $ansByCol = round($anscount / $dcols);
     $ansByCol = $ansByCol > 0 ? $ansByCol : 1;
     //$answer = 'IKI: '.$iBootCols.' '.$ansByCol.' '.$wrapper['whole-start'];
     $answer = '<div class="row">';
     $answer .= '    <div class="col-xs-' . $iBootCols . '">AAAAAAAAAAAAAA';
     //Time Limit Code
     if (trim($aQuestionAttributes['time_limit']) != '') {
         $answer .= return_timer_script($aQuestionAttributes, $ia);
     }
     //End Time Limit Code
     // Get array_filter stuff
     $rowcounter = 0;
     $colcounter = 1;
     $trbc = '';
     foreach ($ansresult as $key => $ansrow) {
         $myfname = $ia[1] . $ansrow['code'];
         $check_ans = '';
         if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == $ansrow['code']) {
             $check_ans = CHECKED;
         }
         list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, $ansrow, $myfname, '', $myfname, "div", "form-group answer-item radio-item");
         /*    if(substr($wrapper['item-start'],0,4) == "\t<li")
                     {
                         $startitem = "\t$htmltbody2\n";
                     } else {
                         $startitem = $wrapper['item-start'];
                     }
         
                     $answer .= $startitem;*/
         $answer .= "\t{$hiddenfield}\n";
         $answer .= '<div  class="form-group">';
         $answer .= '    <label for="answer' . $ia[1] . $ansrow['code'] . '" class="answertext control-label">' . $ansrow['answer'] . '</label>';
         $answer .= '        <input class="radio" type="radio" value="' . $ansrow['code'] . '" name="' . $ia[1] . '" id="answer' . $ia[1] . $ansrow['code'] . '"' . $check_ans . ' onclick="if (document.getElementById(\'answer' . $ia[1] . 'othertext\') != null) document.getElementById(\'answer' . $ia[1] . 'othertext\').value=\'\';' . $checkconditionFunction . '(this.value, this.name, this.type)" />';
         $answer .= $wrapper['item-end'];
         $answer .= '</div>';
         ++$rowcounter;
         //if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols'] || (count($ansresult)-$key)==$wrapper['cols']-$colcounter)
         if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) {
             if ($colcounter == $wrapper['cols']) {
                 //$answer .= 'là '.$wrapper['col-devide-last'];
                 $answer .= '    </div><!-- last -->';
             } else {
                 //$answer .= 'et là '.$wrapper['col-devide'];
                 $answer .= '    </div><!-- devide --> ';
                 $answer .= '    <div class="col-xs-' . $iBootCols . '">';
             }
             $rowcounter = 0;
             ++$colcounter;
         }
     }
     if (isset($other) && $other == 'Y') {
         $sSeparator = getRadixPointData($thissurvey['surveyls_numberformat']);
         $sSeparator = $sSeparator['separator'];
         if ($aQuestionAttributes['other_numbers_only'] == 1) {
             $oth_checkconditionFunction = 'fixnum_checkconditions';
         } else {
             $oth_checkconditionFunction = 'checkconditions';
         }
         if ($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == '-oth-') {
             $check_ans = CHECKED;
         } else {
             $check_ans = '';
         }
         $thisfieldname = $ia[1] . 'other';
         if (isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$thisfieldname])) {
             $dispVal = $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$thisfieldname];
             if ($aQuestionAttributes['other_numbers_only'] == 1) {
                 $dispVal = str_replace('.', $sSeparator, $dispVal);
             }
             $answer_other = ' value="' . htmlspecialchars($dispVal, ENT_QUOTES) . '"';
         } else {
             $answer_other = ' value=""';
         }
         list($htmltbody2, $hiddenfield) = return_array_filter_strings($ia, $aQuestionAttributes, $thissurvey, array("code" => "other"), $thisfieldname, $trbc, $myfname, "div", "form-group answer-item radio-item other-item other");
         $answer .= "\t{$hiddenfield}\n";
         $answer .= '<div  class="form-group">';
         $answer .= '    <label for="SOTH' . $ia[1] . '" class="answertext control-label">' . $othertext . '</label>';
         $answer .= '    <input class="radio" type="radio" value="-oth-" name="' . $ia[1] . '" id="SOTH' . $ia[1] . '"' . $check_ans . ' onclick="' . $checkconditionFunction . '(this.value, this.name, this.type)" />';
         $answer .= '    <input type="text" class="text ' . $kpclass . '" id="answer' . $ia[1] . 'othertext" name="' . $ia[1] . 'other" title="' . gT('Other') . '"' . $answer_other . ' onkeyup="if($.trim($(this).val())!=\'\'){ $(\'#SOTH' . $ia[1] . '\').click(); }; ' . $oth_checkconditionFunction . '(this.value, this.name, this.type);" />';
         $answer .= $wrapper['item-end'];
         $answer .= '</div>';
         $inputnames[] = $thisfieldname;
         ++$rowcounter;
         if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) {
             if ($colcounter == $wrapper['cols']) {
                 $answer .= '    </div><!-- last -->';
             } else {
                 $answer .= '    </div><!-- devide -->';
                 $answer .= '    <div class="col-xs-' . $iBootCols . '">';
             }
             $rowcounter = 0;
             ++$colcounter;
         }
     }
     if ($ia[6] != 'Y' && SHOW_NO_ANSWER == 1) {
         if (!isset($_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]]) || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == '' || $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] == ' ') {
             $check_ans = CHECKED;
             //Check the "no answer" radio button if there is no answer in session.
         } else {
             $check_ans = '';
         }
         $answer .= '<div  class="form-group">';
         $answer .= '    <label for="answer' . $ia[1] . 'NANS" class="answertext control-label">' . gT('No answer') . '</label>';
         $answer .= '        <input class="radio" type="radio" name="' . $ia[1] . '" id="answer' . $ia[1] . 'NANS" value=""' . $check_ans . ' onclick="if (document.getElementById(\'answer' . $ia[1] . 'othertext\') != null) document.getElementById(\'answer' . $ia[1] . 'othertext\').value=\'\';' . $checkconditionFunction . '(this.value, this.name, this.type)" />';
         $answer .= $wrapper['item-end'];
         $answer .= '</div>';
         // --> END NEW FEATURE - SAVE
         ++$rowcounter;
         //if ($rowcounter == $wrapper['maxrows'] && $colcounter < $wrapper['cols'])
         if ($rowcounter == $ansByCol && $colcounter < $wrapper['cols']) {
             if ($colcounter == $wrapper['cols']) {
                 //$answer .= $wrapper['col-devide-last'];
                 $answer .= '    </div><!-- last -->';
             } else {
                 //$answer .= $wrapper['col-devide'];
                 $answer .= '    </div><!-- devide -->';
                 $answer .= '    <div class="col-xs-' . $iBootCols . '">';
             }
             $rowcounter = 0;
             ++$colcounter;
         }
     }
     //END OF ITEMS
     //$answer .= $wrapper['whole-end'].'
     $answer .= '    <input type="hidden" name="java' . $ia[1] . '" id="java' . $ia[1] . "\" value=\"" . $_SESSION['survey_' . Yii::app()->getConfig('surveyID')][$ia[1]] . "\" />\n";
     $answer .= '</div> <!-- wrapper row -->';
     $inputnames[] = $ia[1];
     return array($answer, $inputnames);
 }
Esempio n. 21
0
                            echo "\t<span class='smalltext'>".gT("Responses containing").":</span><br />\n"
                            .CHtml::textField($myfield2,isset($_POST[$myfield2])?$_POST[$myfield2]:'',array() )
                            ."</div></td>\n";
                            $counter2++;
                        }
                    }
                    echo "\t<td><div class='inerTableBox'>\n";
                    $counter=0;
                    break;

                case ":":  //ARRAY (Multi Flex) (Numbers)
                    echo "\t</tr>\n\t<tr>\n";

                    $counter2=0;
                    //Get qidattributes for this question
                    $qidattributes=getQuestionAttributeValues($flt[0]);
                    if (trim($qidattributes['multiflexible_max'])!='' && trim($qidattributes['multiflexible_min']) ==''){
                        $maxvalue=$qidattributes['multiflexible_max'];
                        $minvalue=1;
                    }
                    if (trim($qidattributes['multiflexible_min'])!='' && trim($qidattributes['multiflexible_max']) ==''){
                        $minvalue=$qidattributes['multiflexible_min'];
                        $maxvalue=$qidattributes['multiflexible_min'] + 10;
                    }
                    if (trim($qidattributes['multiflexible_min'])=='' && trim($qidattributes['multiflexible_max']) ==''){
                        $minvalue=1;
                        $maxvalue=10;
                    }
                    if (trim($qidattributes['multiflexible_min']) !='' && trim($qidattributes['multiflexible_max']) !=''){
                        if($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']){
                            $minvalue=$qidattributes['multiflexible_min'];
    function run($actionID)
    {
        $surveyid = Yii::app()->session['LEMsid'];
        $oSurvey = Survey::model()->findByPk($surveyid);
        if (!$oSurvey) {
            throw new CHttpException(400);
        }
        // See for debug > 1
        $sLanguage = isset(Yii::app()->session['survey_' . $surveyid]['s_lang']) ? Yii::app()->session['survey_' . $surveyid]['s_lang'] : "";
        $uploaddir = Yii::app()->getConfig("uploaddir");
        $tempdir = Yii::app()->getConfig("tempdir");
        Yii::app()->loadHelper("database");
        // Fill needed var
        $sFileGetContent = Yii::app()->request->getParam('filegetcontents', '');
        // The file to view fu_ or fu_tmp
        $bDelete = Yii::app()->request->getParam('delete');
        $sFieldName = Yii::app()->request->getParam('fieldname');
        $sFileName = Yii::app()->request->getParam('filename', '');
        // The file to delete fu_ or fu_tmp
        $sOriginalFileName = Yii::app()->request->getParam('name', '');
        // Used for javascript return only
        $sMode = Yii::app()->request->getParam('mode');
        $sPreview = Yii::app()->request->getParam('preview', 0);
        // Validate and filter and throw error if problems
        // Using 'futmp_'.randomChars(15).'_'.$pathinfo['extension'] for filename, then remove all other characters
        $sFileGetContentFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileGetContent);
        $sFileNameFiltered = preg_replace('/[^a-zA-Z0-9_]/', '', $sFileName);
        $sFieldNameFiltered = preg_replace('/[^X0-9]/', '', $sFieldName);
        if ($sFileGetContent != $sFileGetContentFiltered || $sFileName != $sFileNameFiltered || $sFieldName != $sFieldNameFiltered) {
            // If one seems to be a hack: Bad request
            throw new CHttpException(400);
            // See for debug > 1
        }
        if ($sFileGetContent) {
            if (substr($sFileGetContent, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileGetContent, 0, 3) == 'fu_') {
                // Need to validate $_SESSION['srid'], and this file is from this srid !
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                throw new CHttpException(400);
                // See for debug > 1
            }
            if (is_file($sFileDir . $sFileGetContent)) {
                header('Content-Type: ' . CFileHelper::getMimeType($sFileDir . $sFileGetContent));
                readfile($sFileDir . $sFileGetContent);
                Yii::app()->end();
            } else {
                Yii::app()->end();
            }
        } elseif ($bDelete) {
            if (substr($sFileName, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileName, 0, 3) == 'fu_') {
                // Need to validate $_SESSION['srid'], and this file is from this srid !
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                throw new CHttpException(400);
                // See for debug > 1
            }
            if (isset($_SESSION[$sFieldName])) {
                // We already have $sFieldName ?
                $sJSON = $_SESSION[$sFieldName];
                $aFiles = json_decode(stripslashes($sJSON), true);
                if (substr($sFileName, 0, 3) == 'fu_') {
                    $iFileIndex = 0;
                    $found = false;
                    foreach ($aFiles as $aFile) {
                        if ($aFile['filename'] == $sFileName) {
                            $found = true;
                            break;
                        }
                        $iFileIndex++;
                    }
                    if ($found == true) {
                        unset($aFiles[$iFileIndex]);
                    }
                    $_SESSION[$sFieldName] = ls_json_encode($aFiles);
                }
            }
            //var_dump($sFileDir.$sFilename);
            // Return some json to do a beautiful text
            if (@unlink($sFileDir . $sFileName)) {
                echo sprintf(gT('File %s deleted'), $sOriginalFileName);
            } else {
                echo gT('Oops, There was an error deleting the file');
            }
            Yii::app()->end();
        }
        if ($sMode == "upload") {
            $sTempUploadDir = $tempdir . '/upload/';
            // Check if exists and is writable
            if (!file_exists($sTempUploadDir)) {
                // Try to create
                mkdir($sTempUploadDir);
            }
            $filename = $_FILES['uploadfile']['name'];
            // Do we filter file name ? It's used on displaying only , but not save like that.
            //$filename = sanitize_filename($_FILES['uploadfile']['name']);// This remove all non alpha numeric characters and replaced by _ . Leave only one dot .
            $size = 0.001 * $_FILES['uploadfile']['size'];
            $preview = Yii::app()->session['preview'];
            $aFieldMap = createFieldMap($surveyid, 'short', false, false, $sLanguage);
            if (!isset($aFieldMap[$sFieldName])) {
                throw new CHttpException(400);
                // See for debug > 1
            }
            $aAttributes = getQuestionAttributeValues($aFieldMap[$sFieldName]['qid']);
            $maxfilesize = (int) $aAttributes['max_filesize'];
            $valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']);
            $valid_extensions_array = array_map('trim', $valid_extensions_array);
            $pathinfo = pathinfo($_FILES['uploadfile']['name']);
            $ext = strtolower($pathinfo['extension']);
            $randfilename = 'futmp_' . randomChars(15) . '_' . $pathinfo['extension'];
            $randfileloc = $sTempUploadDir . $randfilename;
            // check to see that this file type is allowed
            // it is also  checked at the client side, but jst double checking
            if (!in_array($ext, $valid_extensions_array)) {
                $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file extension (%s) is not allowed!"), $ext));
                //header('Content-Type: application/json');
                echo ls_json_encode($return);
                Yii::app()->end();
            }
            // If this is just a preview, don't save the file
            if ($preview) {
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } else {
                    if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                        $return = array("success" => true, "file_index" => $filecount, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => gT("The file has been successfuly uploaded."));
                        // TODO : unlink this file since this is just a preview. But we can do it only if it's not needed, and still needed to have the file content
                        // Maybe use a javascript 'onunload' on preview question/group
                        // unlink($randfileloc)
                        //header('Content-Type: application/json');
                        echo ls_json_encode($return);
                        Yii::app()->end();
                    }
                }
            } else {
                // if everything went fine and the file was uploaded successfuly,
                // send the file related info back to the client
                $iFileUploadTotalSpaceMB = Yii::app()->getConfig("iFileUploadTotalSpaceMB");
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files up to %s KB are allowed.", 'unescaped'), $maxfilesize));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } elseif ($iFileUploadTotalSpaceMB > 0 && calculateTotalFileUploadUsage() + $size / 1024 / 1024 > $iFileUploadTotalSpaceMB) {
                    $return = array("success" => false, "msg" => gT("We are sorry but there was a system error and your file was not saved. An email has been dispatched to notify the survey administrator.", 'unescaped'));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } elseif (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                    $return = array("success" => true, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => gT("The file has been successfuly uploaded."));
                    //header('Content-Type: application/json');
                    echo ls_json_encode($return);
                    Yii::app()->end();
                } else {
                    // check for upload error
                    if ($_FILES['uploadfile']['error'] > 2) {
                        $return = array("success" => false, "msg" => gT("Sorry, there was an error uploading your file"));
                        //header('Content-Type: application/json');
                        echo ls_json_encode($return);
                        Yii::app()->end();
                    } else {
                        if ($_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize) {
                            $return = array("success" => false, "msg" => sprintf(gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                            //header('Content-Type: application/json');
                            echo ls_json_encode($return);
                            Yii::app()->end();
                        } else {
                            $return = array("success" => false, "msg" => gT("Unknown error"));
                            //header('Content-Type: application/json');
                            echo ls_json_encode($return);
                            Yii::app()->end();
                        }
                    }
                }
            }
            return;
        }
        $meta = '';
        App()->getClientScript()->registerPackage('jqueryui');
        App()->getClientScript()->registerPackage('jquery-superfish');
        $sNeededScriptVar = '
            var uploadurl = "' . $this->createUrl('/uploader/index/mode/upload/') . '";
            var imageurl = "' . Yii::app()->getConfig('imageurl') . '/";
            var surveyid = "' . $surveyid . '";
            var fieldname = "' . $sFieldName . '";
            var questgrppreview  = ' . $sPreview . ';
            csrfToken = ' . ls_json_encode(Yii::app()->request->csrfToken) . ';
            showpopups="' . Yii::app()->getConfig("showpopups") . '";
        ';
        $sLangScriptVar = "\n                uploadLang = {\n                     titleFld: '" . gT('Title', 'js') . "',\n                     commentFld: '" . gT('Comment', 'js') . "',\n                     errorNoMoreFiles: '" . gT('Sorry, no more files can be uploaded!', 'js') . "',\n                     errorOnlyAllowed: '" . gT('Sorry, only %s files can be uploaded for this question!', 'js') . "',\n                     uploading: '" . gT('Uploading', 'js') . "',\n                     selectfile: '" . gT('Select file', 'js') . "',\n                     errorNeedMore: '" . gT('Please upload %s more file(s).', 'js') . "',\n                     errorMoreAllowed: '" . gT('If you wish, you may upload %s more file(s); else you may return back to survey.', 'js') . "',\n                     errorMaxReached: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n                     errorTooMuch: '" . gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n                     errorNeedMoreConfirm: '" . gT("You need to upload %s more files for this question.\nAre you sure you want to exit?", 'js') . "',\n                     deleteFile : '" . gt('Delete', 'js') . "',\n                     editFile : '" . gt('Edit', 'js') . "',\n                    };\n        ";
        $aSurveyInfo = getSurveyInfo($surveyid, $sLanguage);
        $oEvent = new PluginEvent('beforeSurveyPage');
        $oEvent->set('surveyId', $surveyid);
        App()->getPluginManager()->dispatchEvent($oEvent);
        if (!is_null($oEvent->get('template'))) {
            $aSurveyInfo['templatedir'] = $event->get('template');
        }
        $sTemplateDir = getTemplatePath($aSurveyInfo['template']);
        $sTemplateUrl = getTemplateURL($aSurveyInfo['template']) . "/";
        App()->clientScript->registerScript('sNeededScriptVar', $sNeededScriptVar, CClientScript::POS_HEAD);
        App()->clientScript->registerScript('sLangScriptVar', $sLangScriptVar, CClientScript::POS_HEAD);
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'ajaxupload.js');
        App()->getClientScript()->registerScriptFile(Yii::app()->getConfig("generalscripts") . 'uploader.js');
        App()->getClientScript()->registerScriptFile("{$sTemplateUrl}template.js");
        App()->clientScript->registerCssFile(Yii::app()->getConfig("publicstyleurl") . "uploader.css");
        App()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "uploader-files.css");
        if (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui-custom.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui-custom.css");
        } elseif (file_exists($sTemplateDir . DIRECTORY_SEPARATOR . 'jquery-ui.css')) {
            Yii::app()->getClientScript()->registerCssFile("{$sTemplateUrl}jquery-ui.css");
        } else {
            Yii::app()->getClientScript()->registerCssFile(Yii::app()->getConfig('publicstyleurl') . "jquery-ui.css");
        }
        App()->clientScript->registerCssFile("{$sTemplateUrl}template.css");
        $header = getHeader($meta);
        echo $header;
        $fn = $sFieldName;
        $qid = (int) Yii::app()->request->getParam('qid');
        $minfiles = (int) Yii::app()->request->getParam('minfiles');
        $maxfiles = (int) Yii::app()->request->getParam('maxfiles');
        $qidattributes = getQuestionAttributeValues($qid);
        $qidattributes['max_filesize'] = floor(min($qidattributes['max_filesize'] * 1024, getMaximumFileUploadSize()) / 1024);
        $body = '</head><body class="uploader">
                <div id="notice"></div>
                <input type="hidden" id="ia"                value="' . $fn . '" />
                <input type="hidden" id="' . $fn . '_minfiles"          value="' . $minfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfiles"          value="' . $maxfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfilesize"       value="' . $qidattributes['max_filesize'] . '" />
                <input type="hidden" id="' . $fn . '_allowed_filetypes" value="' . $qidattributes['allowed_filetypes'] . '" />
                <input type="hidden" id="preview"                   value="' . Yii::app()->session['preview'] . '" />
                <input type="hidden" id="' . $fn . '_show_comment"      value="' . $qidattributes['show_comment'] . '" />
                <input type="hidden" id="' . $fn . '_show_title"        value="' . $qidattributes['show_title'] . '" />
                <input type="hidden" id="' . $fn . '_licount"           value="0" />
                <input type="hidden" id="' . $fn . '_filecount"         value="0" />

                <!-- The upload button -->
                <div class="upload-div">
                    <button id="button1" class="button upload-button" type="button" >' . gT("Select file") . '</button>
                </div>

                <p class="uploadmsg">' . sprintf(gT("You can upload %s under %s KB each."), $qidattributes['allowed_filetypes'], $qidattributes['max_filesize']) . '</p>
                <div class="uploadstatus" id="uploadstatus"></div>

                <!-- The list of uploaded files -->

            </body>
        </html>';
        App()->getClientScript()->render($body);
        echo $body;
    }
Esempio n. 23
0
/**
* Creates a fieldmap with all information necessary to output the fields
*
* @param $prefix string prefix for the variable ID
* @return array
*/
function SPSSFieldMap($iSurveyID, $prefix = 'V')
{
    $typeMap = array('5' => array('name' => '5 Point Choice', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 3), 'B' => array('name' => 'Array (10 Point Choice)', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 3), 'A' => array('name' => 'Array (5 Point Choice)', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 3), 'F' => array('name' => 'Array (Flexible Labels)', 'size' => 1, 'SPSStype' => 'F'), '1' => array('name' => 'Array (Flexible Labels) Dual Scale', 'size' => 1, 'SPSStype' => 'F'), 'H' => array('name' => 'Array (Flexible Labels) by Column', 'size' => 1, 'SPSStype' => 'F'), 'E' => array('name' => 'Array (Increase, Same, Decrease)', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 2), 'C' => array('name' => 'Array (Yes/No/Uncertain)', 'size' => 1, 'SPSStype' => 'F'), 'X' => array('name' => 'Boilerplate Question', 'size' => 1, 'SPSStype' => 'A', 'hide' => 1), 'D' => array('name' => 'Date', 'size' => 20, 'SPSStype' => 'DATETIME23.2'), 'G' => array('name' => 'Gender', 'size' => 1, 'SPSStype' => 'F'), 'U' => array('name' => 'Huge Free Text', 'size' => 1, 'SPSStype' => 'A'), 'I' => array('name' => 'Language Switch', 'size' => 1, 'SPSStype' => 'A'), '!' => array('name' => 'List (Dropdown)', 'size' => 1, 'SPSStype' => 'F'), 'W' => array('name' => 'List (Flexible Labels) (Dropdown)', 'size' => 1, 'SPSStype' => 'F'), 'Z' => array('name' => 'List (Flexible Labels) (Radio)', 'size' => 1, 'SPSStype' => 'F'), 'L' => array('name' => 'List (Radio)', 'size' => 1, 'SPSStype' => 'F'), 'O' => array('name' => 'List With Comment', 'size' => 1, 'SPSStype' => 'F'), 'T' => array('name' => 'Long free text', 'size' => 1, 'SPSStype' => 'A'), 'K' => array('name' => 'Multiple Numerical Input', 'size' => 1, 'SPSStype' => 'F'), 'M' => array('name' => 'Multiple choice', 'size' => 1, 'SPSStype' => 'F'), 'P' => array('name' => 'Multiple choice with comments', 'size' => 1, 'SPSStype' => 'F'), 'Q' => array('name' => 'Multiple Short Text', 'size' => 1, 'SPSStype' => 'F'), 'N' => array('name' => 'Numerical Input', 'size' => 3, 'SPSStype' => 'F', 'Scale' => 3), 'R' => array('name' => 'Ranking', 'size' => 1, 'SPSStype' => 'F'), 'S' => array('name' => 'Short free text', 'size' => 1, 'SPSStype' => 'F'), 'Y' => array('name' => 'Yes/No', 'size' => 1, 'SPSStype' => 'F'), ':' => array('name' => 'Multi flexi numbers', 'size' => 1, 'SPSStype' => 'F', 'Scale' => 3), ';' => array('name' => 'Multi flexi text', 'size' => 1, 'SPSStype' => 'A'), '|' => array('name' => 'File upload', 'size' => 1, 'SPSStype' => 'A'), '*' => array('name' => 'Equation', 'size' => 1, 'SPSStype' => 'A'));
    $fieldmap = createFieldMap($iSurveyID, 'full', false, false, getBaseLanguageFromSurveyID($iSurveyID));
    #See if tokens are being used
    $bTokenTableExists = tableExists('tokens_' . $iSurveyID);
    #Lookup the names of the attributes
    $query = "SELECT sid, anonymized, language FROM {{surveys}} WHERE sid={$iSurveyID}";
    $aRow = Yii::app()->db->createCommand($query)->queryRow();
    //Checked
    $surveyprivate = $aRow['anonymized'];
    $language = $aRow['language'];
    $fieldno = 0;
    $fields = array();
    if ($bTokenTableExists && $surveyprivate == 'N' && Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
        $tokenattributes = getTokenFieldsAndNames($iSurveyID, false);
        foreach ($tokenattributes as $attributefield => $attributedescription) {
            //Drop the token field, since it is in the survey too
            if ($attributefield != 'token') {
                $fieldno++;
                $fields[] = array('id' => "{$prefix}{$fieldno}", 'name' => mb_substr($attributefield, 0, 8), 'qid' => 0, 'code' => '', 'SPSStype' => 'A', 'LStype' => 'Undef', 'VariableLabel' => $attributedescription['description'], 'sql_name' => $attributefield, 'size' => '100', 'title' => $attributefield, 'hide' => 0, 'scale' => '');
            }
        }
    }
    $tempArray = array();
    $fieldnames = Yii::app()->db->schema->getTable("{{survey_{$iSurveyID}}}")->getColumnNames();
    $num_results = count($fieldnames);
    $num_fields = $num_results;
    $diff = 0;
    $noQID = array('id', 'token', 'datestamp', 'submitdate', 'startdate', 'startlanguage', 'ipaddr', 'refurl', 'lastpage');
    # Build array that has to be returned
    for ($i = 0; $i < $num_results; $i++) {
        #Condition for SPSS fields:
        # - Length may not be longer than 8 characters
        # - Name may not begin with a digit
        $fieldname = $fieldnames[$i];
        $fieldtype = '';
        $ftype = '';
        $val_size = 1;
        $hide = 0;
        $export_scale = '';
        $code = '';
        $scale_id = null;
        $aQuestionAttribs = array();
        #Determine field type
        if ($fieldname == 'submitdate' || $fieldname == 'startdate' || $fieldname == 'datestamp') {
            $fieldtype = 'DATETIME23.2';
        } elseif ($fieldname == 'startlanguage') {
            $fieldtype = 'A';
            $val_size = 19;
        } elseif ($fieldname == 'token') {
            $fieldtype = 'A';
            $val_size = 16;
        } elseif ($fieldname == 'id') {
            $fieldtype = 'F';
            $val_size = 7;
            //Arbitrarilty restrict to 9,999,999 (7 digits) responses/survey
        } elseif ($fieldname == 'ipaddr') {
            $fieldtype = 'A';
            $val_size = 15;
        } elseif ($fieldname == 'refurl') {
            $fieldtype = 'A';
            $val_size = 255;
        } elseif ($fieldname == 'lastpage') {
            $fieldtype = 'F';
            $val_size = 7;
            //Arbitrarilty restrict to 9,999,999 (7 digits) pages
        }
        #Get qid (question id)
        if (in_array($fieldname, $noQID) || substr($fieldname, 0, 10) == 'attribute_') {
            $qid = 0;
            $varlabel = $fieldname;
            $ftitle = $fieldname;
        } else {
            //GET FIELD DATA
            if (!isset($fieldmap[$fieldname])) {
                //Field in database but no longer in survey... how is this possible?
                //@TODO: think of a fix.
                $fielddata = array();
                $qid = 0;
                $varlabel = $fieldname;
                $ftitle = $fieldname;
                $fieldtype = "F";
                $val_size = 1;
            } else {
                $fielddata = $fieldmap[$fieldname];
                $qid = $fielddata['qid'];
                $ftype = $fielddata['type'];
                $fsid = $fielddata['sid'];
                $fgid = $fielddata['gid'];
                $code = mb_substr($fielddata['fieldname'], strlen($fsid . "X" . $fgid . "X" . $qid));
                $varlabel = $fielddata['question'];
                if (isset($fielddata['scale'])) {
                    $varlabel = "[{$fielddata['scale']}] " . $varlabel;
                }
                if (isset($fielddata['subquestion'])) {
                    $varlabel = "[{$fielddata['subquestion']}] " . $varlabel;
                }
                if (isset($fielddata['subquestion2'])) {
                    $varlabel = "[{$fielddata['subquestion2']}] " . $varlabel;
                }
                if (isset($fielddata['subquestion1'])) {
                    $varlabel = "[{$fielddata['subquestion1']}] " . $varlabel;
                }
                $ftitle = $fielddata['title'];
                if (!is_null($code) && $code != "") {
                    $ftitle .= "_{$code}";
                }
                if (isset($typeMap[$ftype]['size'])) {
                    $val_size = $typeMap[$ftype]['size'];
                }
                if (isset($fielddata['scale_id'])) {
                    $scale_id = $fielddata['scale_id'];
                }
                if ($fieldtype == '') {
                    $fieldtype = $typeMap[$ftype]['SPSStype'];
                }
                if (isset($typeMap[$ftype]['hide'])) {
                    $hide = $typeMap[$ftype]['hide'];
                    $diff++;
                }
                //Get default scale for this type
                if (isset($typeMap[$ftype]['Scale'])) {
                    $export_scale = $typeMap[$ftype]['Scale'];
                }
                //But allow override
                $aQuestionAttribs = getQuestionAttributeValues($qid);
                if (isset($aQuestionAttribs['scale_export'])) {
                    $export_scale = $aQuestionAttribs['scale_export'];
                }
            }
        }
        $fieldno++;
        $fid = $fieldno - $diff;
        $lsLong = isset($typeMap[$ftype]["name"]) ? $typeMap[$ftype]["name"] : $ftype;
        $tempArray = array('id' => "{$prefix}{$fid}", 'name' => mb_substr($fieldname, 0, 8), 'qid' => $qid, 'code' => $code, 'SPSStype' => $fieldtype, 'LStype' => $ftype, "LSlong" => $lsLong, 'ValueLabels' => '', 'VariableLabel' => $varlabel, "sql_name" => $fieldname, "size" => $val_size, 'title' => $ftitle, 'hide' => $hide, 'scale' => $export_scale, 'scale_id' => $scale_id);
        //Now check if we have to retrieve value labels
        $answers = SPSSGetValues($tempArray, $aQuestionAttribs, $language);
        if (is_array($answers)) {
            //Ok we have answers
            if (isset($answers['size'])) {
                $tempArray['size'] = $answers['size'];
                unset($answers['size']);
            }
            if (isset($answers['SPSStype'])) {
                $tempArray['SPSStype'] = $answers['SPSStype'];
                unset($answers['SPSStype']);
            }
            $tempArray['answers'] = $answers;
        }
        $fields[] = $tempArray;
    }
    return $fields;
}
Esempio n. 24
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);
 }
Esempio n. 25
0
 function index($subaction, $iSurveyID = null, $gid = null, $qid = null)
 {
     $iSurveyID = sanitize_int($iSurveyID);
     $gid = sanitize_int($gid);
     $qid = sanitize_int($qid);
     $clang = $this->getController()->lang;
     $imageurl = Yii::app()->getConfig("adminimageurl");
     Yii::app()->loadHelper("database");
     if (!empty($_POST['subaction'])) {
         $subaction = Yii::app()->request->getPost('subaction');
     }
     //BEGIN Sanitizing POSTed data
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($gid)) {
         $gid = returnGlobal('gid');
     }
     if (!isset($p_scenario)) {
         $p_scenario = returnGlobal('scenario');
     }
     if (!isset($p_cqid)) {
         $p_cqid = returnGlobal('cqid');
         if ($p_cqid == '') {
             $p_cqid = 0;
         }
         // we are not using another question as source of condition
     }
     if (!isset($p_cid)) {
         $p_cid = returnGlobal('cid');
     }
     if (!isset($p_subaction)) {
         if (isset($_POST['subaction'])) {
             $p_subaction = $_POST['subaction'];
         } else {
             $p_subaction = $subaction;
         }
     }
     if (!isset($p_cquestions)) {
         $p_cquestions = returnGlobal('cquestions');
     }
     if (!isset($p_csrctoken)) {
         $p_csrctoken = returnGlobal('csrctoken');
     }
     if (!isset($p_prevquestionsgqa)) {
         $p_prevquestionsgqa = returnGlobal('prevQuestionSGQA');
     }
     if (!isset($p_canswers)) {
         if (isset($_POST['canswers']) && is_array($_POST['canswers'])) {
             foreach ($_POST['canswers'] as $key => $val) {
                 $p_canswers[$key] = preg_replace("/[^_.a-zA-Z0-9]@/", "", $val);
             }
         }
     }
     // this array will be used soon,
     // to explain wich conditions is used to evaluate the question
     if (Yii::app()->getConfig('stringcomparizonoperators') == 1) {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"), "a<b" => $clang->gT("Less than (Strings)"), "a<=b" => $clang->gT("Less than or equal to (Strings)"), "a>=b" => $clang->gT("Greater than or equal to (Strings)"), "a>b" => $clang->gT("Greater than (Strings)"));
     } else {
         $method = array("<" => $clang->gT("Less than"), "<=" => $clang->gT("Less than or equal to"), "==" => $clang->gT("equals"), "!=" => $clang->gT("Not equal to"), ">=" => $clang->gT("Greater than or equal to"), ">" => $clang->gT("Greater than"), "RX" => $clang->gT("Regular expression"));
     }
     if (isset($_POST['method'])) {
         if (!in_array($_POST['method'], array_keys($method))) {
             $p_method = "==";
         } else {
             $p_method = trim($_POST['method']);
         }
     }
     if (isset($_POST['newscenarionum'])) {
         $p_newscenarionum = sanitize_int($_POST['newscenarionum']);
     }
     //END Sanitizing POSTed data
     //include_once("login_check.php");
     include_once "database.php";
     // Caution (lemeur): database.php uses autoUnescape on all entries in $_POST
     // Take care to not use autoUnescape on $_POST variables after this
     $br = CHtml::openTag('br /');
     //MAKE SURE THAT THERE IS A SID
     if (!isset($iSurveyID) || !$iSurveyID) {
         $conditionsoutput = $clang->gT("You have not selected a survey") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     if (isset($p_subaction) && $p_subaction == "resetsurveylogic") {
         $clang = $this->getController()->lang;
         $resetsurveylogicoutput = $br;
         $resetsurveylogicoutput .= CHtml::openTag('table', array('class' => 'alertbox'));
         $resetsurveylogicoutput .= CHtml::openTag('tr') . CHtml::openTag('td', array('colspan' => '2'));
         $resetsurveylogicoutput .= CHtml::tag('font', array('size' => '1'), CHtml::tag('strong', array(), $clang->gT("Reset Survey Logic")));
         $resetsurveylogicoutput .= CHtml::closeTag('td') . CHtml::closeTag('tr');
         if (!isset($_GET['ok'])) {
             $button_yes = CHtml::submitButton($clang->gT("Yes"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/conditions/sa/index/subaction/resetsurveylogic/surveyid/{$iSurveyID}") . "?ok=Y" . "', '_top')"));
             $button_cancel = CHtml::submitButton($clang->gT("Cancel"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/survey/sa/view/surveyid/{$iSurveyID}") . "', '_top')"));
             $messagebox_content = $clang->gT("You are about to delete all conditions on this survey's questions") . "({$iSurveyID})" . $br . $clang->gT("We recommend that before you proceed, you export the entire survey from the main administration screen.") . $br . $clang->gT("Continue?") . $br . $button_yes . $button_cancel;
             $this->_renderWrappedTemplate('conditions', array('message' => array('title' => $clang->gT("Warning"), 'message' => $messagebox_content)));
             exit;
         } else {
             LimeExpressionManager::RevertUpgradeConditionsToRelevance($iSurveyID);
             Conditions::model()->deleteRecords("qid in (select qid from {{questions}} where sid={$iSurveyID})");
             Yii::app()->session['flashmessage'] = $clang->gT("All conditions in this survey have been deleted.");
             $this->getController()->redirect($this->getController()->createUrl('admin/survey/sa/view/surveyid/' . $iSurveyID));
         }
     }
     // MAKE SURE THAT THERE IS A QID
     if (!isset($qid) || !$qid) {
         $conditionsoutput = $clang->gT("You have not selected a question") . str_repeat($br, 2);
         $conditionsoutput .= CHtml::submitButton($clang->gT("Main admin screen"), array('onclick' => "window.open('" . $this->getController()->createUrl("admin/") . "', '_top')")) . $br;
         safeDie($conditionsoutput);
         return;
     }
     // If we made it this far, then lets develop the menu items
     // add the conditions container table
     $extraGetParams = "";
     if (isset($qid) && isset($gid)) {
         $extraGetParams = "/gid/{$gid}/qid/{$qid}";
     }
     $conditionsoutput_action_error = "";
     // defined during the actions
     $markcidarray = array();
     if (isset($_GET['markcid'])) {
         $markcidarray = explode("-", $_GET['markcid']);
     }
     //BEGIN PROCESS ACTIONS
     // ADD NEW ENTRY IF THIS IS AN ADD
     if (isset($p_subaction) && $p_subaction == "insertcondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             $condition_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method);
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     //First lets make sure there isn't already an exact replica of this condition
                     $condition_data['value'] = $ca;
                     $result = Conditions::model()->findAllByAttributes($condition_data);
                     $count_caseinsensitivedupes = count($result);
                     if ($count_caseinsensitivedupes == 0) {
                         $result = Conditions::model()->insertRecords($condition_data);
                     }
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $condition_data['value'] = $posted_condition_value;
                 $result = Conditions::model()->insertRecords($condition_data);
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE ENTRY IF THIS IS AN EDIT
     if (isset($p_subaction) && $p_subaction == "updatecondition") {
         if (!isset($p_canswers) && !isset($_POST['ConditionConst']) && !isset($_POST['prevQuestionSGQA']) && !isset($_POST['tokenAttr']) && !isset($_POST['ConditionRegexp']) || !isset($p_cquestions) && !isset($p_csrctoken)) {
             $conditionsoutput_action_error .= CHtml::script("\n<!--\n alert(\"" . $clang->gT("Your condition could not be added! It did not include the question and/or answer upon which the condition was based. Please ensure you have selected a question and an answer.", "js") . "\")\n //-->\n");
         } else {
             if (isset($p_cquestions) && $p_cquestions != '') {
                 $conditionCfieldname = $p_cquestions;
             } elseif (isset($p_csrctoken) && $p_csrctoken != '') {
                 $conditionCfieldname = $p_csrctoken;
             }
             if (isset($p_canswers)) {
                 foreach ($p_canswers as $ca) {
                     // This is an Edit, there will only be ONE VALUE
                     $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $ca);
                     $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
                 }
             }
             unset($posted_condition_value);
             // Please note that autoUnescape is already applied in database.php included above
             // so we only need to db_quote _POST variables
             if (isset($_POST['ConditionConst']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#CONST") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionConst');
             } elseif (isset($_POST['prevQuestionSGQA']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#PREVQUESTIONS") {
                 $posted_condition_value = Yii::app()->request->getPost('prevQuestionSGQA');
             } elseif (isset($_POST['tokenAttr']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#TOKENATTRS") {
                 $posted_condition_value = Yii::app()->request->getPost('tokenAttr');
             } elseif (isset($_POST['ConditionRegexp']) && isset($_POST['editTargetTab']) && $_POST['editTargetTab'] == "#REGEXP") {
                 $posted_condition_value = Yii::app()->request->getPost('ConditionRegexp');
             }
             if (isset($posted_condition_value)) {
                 $updated_data = array('qid' => $qid, 'scenario' => $p_scenario, 'cqid' => $p_cqid, 'cfieldname' => $conditionCfieldname, 'method' => $p_method, 'value' => $posted_condition_value);
                 $result = Conditions::model()->insertRecords($updated_data, TRUE, array('cid' => $p_cid));
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ENTRY IF THIS IS DELETE
     if (isset($p_subaction) && $p_subaction == "delete") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('cid' => $p_cid));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS IN THIS SCENARIO
     if (isset($p_subaction) && $p_subaction == "deletescenario") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // UPDATE SCENARIO
     if (isset($p_subaction) && $p_subaction == "updatescenario" && isset($p_newscenarionum)) {
         $result = Conditions::model()->insertRecords(array('scenario' => $p_newscenarionum), TRUE, array('qid' => $qid, 'scenario' => $p_scenario));
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
     }
     // DELETE ALL CONDITIONS FOR THIS QUESTION
     if (isset($p_subaction) && $p_subaction == "deleteallconditions") {
         LimeExpressionManager::RevertUpgradeConditionsToRelevance(NULL, $qid);
         // in case deleted the last condition
         $result = Conditions::model()->deleteRecords(array('qid' => $qid));
     }
     // RENUMBER SCENARIOS
     if (isset($p_subaction) && $p_subaction == "renumberscenarios") {
         $query = "SELECT DISTINCT scenario FROM {{conditions}} WHERE qid=:qid ORDER BY scenario";
         $result = Yii::app()->db->createCommand($query)->bindParam(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't select scenario<br />{$query}<br />");
         $newindex = 1;
         foreach ($result->readAll() as $srow) {
             // new var $update_result == old var $result2
             $update_result = Conditions::model()->insertRecords(array('scenario' => $newindex), TRUE, array('qid' => $qid, 'scenario' => $srow['scenario']));
             $newindex++;
         }
         LimeExpressionManager::UpgradeConditionsToRelevance(NULL, $qid);
         Yii::app()->session['flashmessage'] = $clang->gT("All conditions scenarios were renumbered.");
     }
     // COPY CONDITIONS IF THIS IS COPY
     if (isset($p_subaction) && $p_subaction == "copyconditions") {
         $qid = returnGlobal('qid');
         $copyconditionsfrom = returnGlobal('copyconditionsfrom');
         $copyconditionsto = returnGlobal('copyconditionsto');
         if (isset($copyconditionsto) && is_array($copyconditionsto) && isset($copyconditionsfrom) && is_array($copyconditionsfrom)) {
             //Get the conditions we are going to copy
             foreach ($copyconditionsfrom as &$entry) {
                 $entry = Yii::app()->db->quoteValue($entry);
             }
             $query = "SELECT * FROM {{conditions}}\n" . "WHERE cid in (";
             $query .= implode(", ", $copyconditionsfrom);
             $query .= ")";
             $result = Yii::app()->db->createCommand($query)->query() or safeDie("Couldn't get conditions for copy<br />{$query}<br />");
             foreach ($result->readAll() as $row) {
                 $proformaconditions[] = array("scenario" => $row['scenario'], "cqid" => $row['cqid'], "cfieldname" => $row['cfieldname'], "method" => $row['method'], "value" => $row['value']);
             }
             // while
             foreach ($copyconditionsto as $copyc) {
                 list($newsid, $newgid, $newqid) = explode("X", $copyc);
                 foreach ($proformaconditions as $pfc) {
                     //TIBO
                     //First lets make sure there isn't already an exact replica of this condition
                     $conditions_data = array('qid' => $newqid, 'scenario' => $pfc['scenario'], 'cqid' => $pfc['cqid'], 'cfieldname' => $pfc['cfieldname'], 'method' => $pfc['method'], 'value' => $pfc['value']);
                     $result = Conditions::model()->findAllByAttributes($conditions_data);
                     $count_caseinsensitivedupes = count($result);
                     $countduplicates = 0;
                     if ($count_caseinsensitivedupes != 0) {
                         foreach ($result as $ccrow) {
                             if ($ccrow['value'] == $pfc['value']) {
                                 $countduplicates++;
                             }
                         }
                     }
                     if ($countduplicates == 0) {
                         $result = Conditions::model()->insertRecords($conditions_data);
                         $conditionCopied = true;
                     } else {
                         $conditionDuplicated = true;
                     }
                 }
             }
             if (isset($conditionCopied) && $conditionCopied === true) {
                 if (isset($conditionDuplicated) && $conditionDuplicated == true) {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'partialheader'), '(' . $clang->gT("Conditions successfully copied (some were skipped because they were duplicates)") . ')');
                 } else {
                     $CopyConditionsMessage = CHtml::tag('div', array('class' => 'successheader'), '(' . $clang->gT("Conditions successfully copied") . ')');
                 }
             } else {
                 $CopyConditionsMessage = CHtml::tag('div', array('class' => 'warningheader'), '(' . $clang->gT("No conditions could be copied (due to duplicates)") . ')');
             }
         }
         LimeExpressionManager::UpgradeConditionsToRelevance($iSurveyID);
         // do for whole survey, since don't know which questions affected.
     }
     //END PROCESS ACTIONS
     $cquestions = array();
     $canswers = array();
     //BEGIN: GATHER INFORMATION
     // 1: Get information for this question
     if (!isset($qid)) {
         $qid = returnGlobal('qid');
     }
     if (!isset($iSurveyID)) {
         $iSurveyID = returnGlobal('sid');
     }
     $thissurvey = getSurveyInfo($iSurveyID);
     $qresult = Questions::model()->with('groups')->findByAttributes(array('qid' => $qid, 'parent_qid' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $questiongroupname = $qresult->groups->group_name;
     $questiontitle = $qresult['title'];
     $questiontext = $qresult['question'];
     $questiontype = $qresult['type'];
     // 2: Get all other questions that occur before this question that are pre-determined answer types
     // To avoid natural sort order issues,
     // first get all questions in natural sort order
     // , and find out which number in that order this question is
     $qresult = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
     $qrows = array();
     foreach ($qresult as $k => $v) {
         $qrows[$k] = array_merge($v->attributes, $v->groups->attributes);
     }
     // Perform a case insensitive natural sort on group name then question title (known as "code" in the form) of a multidimensional array
     usort($qrows, 'groupOrderThenQuestionOrder');
     $position = "before";
     // Go through each question until we reach the current one
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] != $qid && $position == "before") {
             // remember all previous questions
             // all question types are supported.
             $questionlist[] = $qrow["qid"];
         } elseif ($qrow["qid"] == $qid) {
             break;
         }
     }
     // Now, using the same array which is now properly sorted by group then question
     // Create an array of all the questions that appear AFTER the current one
     $position = "before";
     foreach ($qrows as $qrow) {
         if ($qrow["qid"] == $qid) {
             $position = "after";
             //break;
         } elseif ($qrow["qid"] != $qid && $position == "after") {
             $postquestionlist[] = $qrow['qid'];
         }
     }
     $theserows = array();
     $postrows = array();
     if (isset($questionlist) && is_array($questionlist)) {
         foreach ($questionlist as $ql) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $ql, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $thiscount = count($result);
             // And store again these questions in this array...
             foreach ($result as $myrows) {
                 //key => value
                 $theserows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
         }
     }
     if (isset($postquestionlist) && is_array($postquestionlist)) {
         foreach ($postquestionlist as $pq) {
             $result = Questions::model()->with(array('groups' => array('condition' => 'groups.language = :lang', 'params' => array(':lang' => Survey::model()->findByPk($iSurveyID)->language))))->findAllByAttributes(array('qid' => $pq, 'parent_qid' => 0, 'sid' => $iSurveyID, 'language' => Survey::model()->findByPk($iSurveyID)->language));
             $postcount = count($result);
             foreach ($result as $myrows) {
                 $postrows[] = array("qid" => $myrows['qid'], "sid" => $myrows['sid'], "gid" => $myrows['gid'], "question" => $myrows['question'], "type" => $myrows['type'], "mandatory" => $myrows['mandatory'], "other" => $myrows['other'], "title" => $myrows['title']);
             }
             // while
         }
         $postquestionscount = count($postrows);
     }
     $questionscount = count($theserows);
     if (isset($postquestionscount) && $postquestionscount > 0) {
         //Build the array used for the questionNav and copyTo select boxes
         foreach ($postrows as $pr) {
             $pquestions[] = array("text" => $pr['title'] . ": " . substr(strip_tags($pr['question']), 0, 80), "fieldname" => $pr['sid'] . "X" . $pr['gid'] . "X" . $pr['qid']);
         }
     }
     // Previous question parsing ==> building cquestions[] and canswers[]
     if ($questionscount > 0) {
         $X = "X";
         foreach ($theserows as $rows) {
             $shortquestion = $rows['title'] . ": " . strip_tags($rows['question']);
             if ($rows['type'] == "A" || $rows['type'] == "B" || $rows['type'] == "C" || $rows['type'] == "E" || $rows['type'] == "F" || $rows['type'] == "H") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order ASC'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . flattenText($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . flattenText($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     switch ($rows['type']) {
                         case "A":
                             //Array 5 buttons
                             for ($i = 1; $i <= 5; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "B":
                             //Array 10 buttons
                             for ($i = 1; $i <= 10; $i++) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $i, $i);
                             }
                             break;
                         case "C":
                             //Array Y/N/NA
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "Y", $clang->gT("Yes"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "U", $clang->gT("Uncertain"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "N", $clang->gT("No"));
                             break;
                         case "E":
                             //Array >/=/<
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "I", $clang->gT("Increase"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "S", $clang->gT("Same"));
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "D", $clang->gT("Decrease"));
                             break;
                         case "F":
                             //Array Flexible Row
                         //Array Flexible Row
                         case "H":
                             //Array Flexible Column
                             $fresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language, 'scale_id' => 0), array('order' => 'sortorder, code'));
                             foreach ($fresult as $frow) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], $frow['code'], $frow['answer']);
                             }
                             break;
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == ":" || $rows['type'] == ";") {
                 // Multiflexi
                 //Get question attribute for $canswers
                 $qidattributes = getQuestionAttributeValues($rows['qid'], $rows['type']);
                 if (isset($qidattributes['multiflexible_max']) && trim($qidattributes['multiflexible_max']) != '') {
                     $maxvalue = floatval($qidattributes['multiflexible_max']);
                 } else {
                     $maxvalue = 10;
                 }
                 if (isset($qidattributes['multiflexible_min']) && trim($qidattributes['multiflexible_min']) != '') {
                     $minvalue = floatval($qidattributes['multiflexible_min']);
                 } else {
                     $minvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_step']) && trim($qidattributes['multiflexible_step']) != '') {
                     $stepvalue = floatval($qidattributes['multiflexible_step']);
                     if ($stepvalue == 0) {
                         $stepvalue = 1;
                     }
                 } else {
                     $stepvalue = 1;
                 }
                 if (isset($qidattributes['multiflexible_checkbox']) && $qidattributes['multiflexible_checkbox'] != 0) {
                     $minvalue = 0;
                     $maxvalue = 1;
                     $stepvalue = 1;
                 }
                 // Get the Y-Axis
                 $fquery = "SELECT sq.*, q.other" . " FROM {{questions sq}}, {{questions q}}" . " WHERE sq.sid={$iSurveyID} AND sq.parent_qid=q.qid " . "AND q.language=:lang" . " AND sq.language=:lang" . " AND q.qid=:qid\n                    AND sq.scale_id=0\n                    ORDER BY sq.question_order";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $y_axis_db = Yii::app()->db->createCommand($fquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query();
                 // Get the X-Axis
                 $aquery = "SELECT sq.*\n                    FROM {{questions q}}, {{questions sq}}\n                    WHERE q.sid={$iSurveyID}\n                    AND sq.parent_qid=q.qid\n                    AND q.language=:lang\n                    AND sq.language=:lang\n                    AND q.qid=:qid\n                    AND sq.scale_id=1\n                    ORDER BY sq.question_order";
                 $x_axis_db = Yii::app()->db->createCommand($aquery)->bindParam(":lang", $sLanguage, PDO::PARAM_STR)->bindParam(":qid", $rows['qid'], PDO::PARAM_INT)->query() or safeDie("Couldn't get answers to Array questions<br />{$aquery}<br />");
                 foreach ($x_axis_db->readAll() as $frow) {
                     $x_axis[$frow['title']] = $frow['question'];
                 }
                 foreach ($y_axis_db->readAll() as $yrow) {
                     foreach ($x_axis as $key => $val) {
                         $shortquestion = $rows['title'] . ":{$yrow['title']}:{$key}: [" . strip_tags($yrow['question']) . "][" . strip_tags($val) . "] " . flattenText($rows['question']);
                         $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key);
                         if ($rows['type'] == ":") {
                             for ($ii = $minvalue; $ii <= $maxvalue; $ii += $stepvalue) {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $yrow['title'] . "_" . $key, $ii, $ii);
                             }
                         }
                     }
                 }
                 unset($x_axis);
             } elseif ($rows['type'] == "1") {
                 $aresult = Questions::model()->findAllByAttributes(array('parent_qid' => $rows['qid'], 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $attr = getQuestionAttributeValues($rows['qid']);
                     $label1 = isset($attr['dualscale_headerA']) ? $attr['dualscale_headerA'] : 'Label1';
                     $label2 = isset($attr['dualscale_headerB']) ? $attr['dualscale_headerB'] : 'Label2';
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label1}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0");
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "][{$label2}]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1");
                     // first label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // second label
                     $lresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 1, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                     foreach ($lresult as $lrows) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "{$lrows['code']}", "{$lrows['code']}");
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#0", "", $clang->gT("No answer"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'] . "#1", "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "K" || $rows['type'] == "Q") {
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], "", $clang->gT("No answer"));
                     }
                 }
                 //while
             } elseif ($rows['type'] == "R") {
                 $aresult = Answers::model()->findAllByAttributes(array("qid" => $rows['qid'], "scale_id" => 0, "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                 $acount = count($aresult);
                 foreach ($aresult as $arow) {
                     $theanswer = addcslashes($arow['answer'], "'");
                     $quicky[] = array($arow['code'], $theanswer);
                 }
                 for ($i = 1; $i <= $acount; $i++) {
                     $cquestions[] = array("{$rows['title']}: [RANK {$i}] " . strip_tags($rows['question']), $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i);
                     foreach ($quicky as $qck) {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, $qck[0], $qck[1]);
                     }
                     // Only Show No-Answer if question is not mandatory
                     if ($rows['mandatory'] != 'Y') {
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $i, " ", $clang->gT("No answer"));
                     }
                 }
                 unset($quicky);
             } elseif ($rows['type'] == "M" || $rows['type'] == "P") {
                 $shortanswer = " [" . $clang->gT("Group of checkboxes") . "]";
                 $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 $aresult = Questions::model()->findAllByAttributes(array("parent_qid" => $rows['qid'], "language" => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'question_order desc'));
                 foreach ($aresult as $arows) {
                     $theanswer = addcslashes($arows['question'], "'");
                     $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['title'], $theanswer);
                     $shortanswer = "{$arows['title']}: [" . strip_tags($arows['question']) . "]";
                     $shortanswer .= "[" . $clang->gT("Single checkbox") . "]";
                     $shortquestion = $rows['title'] . ":{$shortanswer} " . strip_tags($rows['question']);
                     $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], "+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title']);
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], 'Y', $clang->gT("checked"));
                     $canswers[] = array("+" . $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'] . $arows['title'], '', $clang->gT("not checked"));
                 }
             } elseif ($rows['type'] == "X") {
                 //Just ignore this questiontype
             } else {
                 $cquestions[] = array($shortquestion, $rows['qid'], $rows['type'], $rows['sid'] . $X . $rows['gid'] . $X . $rows['qid']);
                 switch ($rows['type']) {
                     case "Y":
                         // Y/N/NA
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "Y", $clang->gT("Yes"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "N", $clang->gT("No"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "G":
                         //Gender
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "F", $clang->gT("Female"));
                         $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "M", $clang->gT("Male"));
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "5":
                         // 5 choice
                         for ($i = 1; $i <= 5; $i++) {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $i, $i);
                         }
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     case "N":
                         // Simple Numerical questions
                         // Only Show No-Answer if question is not mandatory
                         if ($rows['mandatory'] != 'Y') {
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                         }
                         break;
                     default:
                         $aresult = Answers::model()->findAllByAttributes(array('qid' => $rows['qid'], 'scale_id' => 0, 'language' => Survey::model()->findByPk($iSurveyID)->language), array('order' => 'sortorder, answer'));
                         foreach ($aresult as $arows) {
                             $theanswer = addcslashes($arows['answer'], "'");
                             $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], $arows['code'], $theanswer);
                         }
                         if ($rows['type'] == "D") {
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         } elseif ($rows['type'] != "M" && $rows['type'] != "P" && $rows['type'] != "J" && $rows['type'] != "I") {
                             // For dropdown questions
                             // optinnaly add the 'Other' answer
                             if (($rows['type'] == "L" || $rows['type'] == "!") && $rows['other'] == "Y") {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], "-oth-", $clang->gT("Other"));
                             }
                             // Only Show No-Answer if question is not mandatory
                             if ($rows['mandatory'] != 'Y') {
                                 $canswers[] = array($rows['sid'] . $X . $rows['gid'] . $X . $rows['qid'], " ", $clang->gT("No answer"));
                             }
                         }
                         break;
                 }
                 //switch row type
             }
             //else
         }
         //foreach theserows
     }
     //if questionscount > 0
     //END Gather Information for this question
     $questionNavOptions = CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Before", "js")));
     foreach ($theserows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("Current", "js")));
     $question = strip_tags($questiontext);
     if (strlen($question) < 35) {
         $questiontextshort = $question;
     } else {
         //$questiontextshort = substr($question, 0, 35)."..";
         $questiontextshort = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
     }
     $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}"), 'selected' => 'selected'), $questiontitle . ': ' . $questiontextshort);
     $questionNavOptions .= CHtml::closeTag('optgroup');
     $questionNavOptions .= CHtml::openTag('optgroup', array('class' => 'activesurveyselect', 'label' => $clang->gT("After", "js")));
     foreach ($postrows as $row) {
         $question = $row['question'];
         $question = strip_tags($question);
         if (strlen($question) < 35) {
             $questionselecter = $question;
         } else {
             //$questionselecter = substr($question, 0, 35)."..";
             $questionselecter = htmlspecialchars(mb_strcut(html_entity_decode($question, ENT_QUOTES, 'UTF-8'), 0, 35, 'UTF-8')) . "...";
         }
         $questionNavOptions .= CHtml::tag('option', array('value' => $this->getController()->createUrl("/admin/conditions/sa/index/subaction/editconditionsform/surveyid/{$iSurveyID}/gid/{$row['gid']}/qid/{$row['qid']}")), $row['title'] . ':' . $questionselecter);
     }
     $questionNavOptions .= CHtml::closeTag('optgroup');
     //Now display the information and forms
     //BEGIN: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $javascriptpre = CHtml::openTag('script', array('type' => 'text/javascript')) . "<!--\n" . "\tvar Fieldnames = new Array();\n" . "\tvar Codes = new Array();\n" . "\tvar Answers = new Array();\n" . "\tvar QFieldnames = new Array();\n" . "\tvar Qcqids = new Array();\n" . "\tvar Qtypes = new Array();\n";
     $jn = 0;
     if (isset($canswers)) {
         foreach ($canswers as $can) {
             $an = ls_json_encode(flattenText($can[2]));
             $javascriptpre .= "Fieldnames[{$jn}]='{$can['0']}';\n" . "Codes[{$jn}]='{$can['1']}';\n" . "Answers[{$jn}]={$an};\n";
             $jn++;
         }
     }
     $jn = 0;
     if (isset($cquestions)) {
         foreach ($cquestions as $cqn) {
             $javascriptpre .= "QFieldnames[{$jn}]='{$cqn['3']}';\n" . "Qcqids[{$jn}]='{$cqn['1']}';\n" . "Qtypes[{$jn}]='{$cqn['2']}';\n";
             $jn++;
         }
     }
     //  record a JS variable to let jQuery know if survey is Anonymous
     if ($thissurvey['anonymized'] == 'Y') {
         $javascriptpre .= "isAnonymousSurvey = true;";
     } else {
         $javascriptpre .= "isAnonymousSurvey = false;";
     }
     $javascriptpre .= "//-->\n" . CHtml::closeTag('script');
     //END: PREPARE JAVASCRIPT TO SHOW MATCHING ANSWERS TO SELECTED QUESTION
     $this->getController()->_css_admin_includes(Yii::app()->getConfig("publicstyleurl") . 'jquery.multiselect.css');
     $aViewUrls = array();
     $aData['clang'] = $clang;
     $aData['surveyid'] = $iSurveyID;
     $aData['qid'] = $qid;
     $aData['gid'] = $gid;
     $aData['imageurl'] = $imageurl;
     $aData['extraGetParams'] = $extraGetParams;
     $aData['quesitonNavOptions'] = $questionNavOptions;
     $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
     $aData['javascriptpre'] = $javascriptpre;
     $aViewUrls['conditionshead_view'][] = $aData;
     //BEGIN DISPLAY CONDITIONS FOR THIS QUESTION
     if ($subaction == 'index' || $subaction == 'editconditionsform' || $subaction == 'insertcondition' || $subaction == "editthiscondition" || $subaction == "delete" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == 'copyconditionsform' || $subaction == 'copyconditions' || $subaction == 'conditions') {
         //3: Get other conditions currently set for this question
         $conditionscount = 0;
         $s = 0;
         $criteria = new CDbCriteria();
         $criteria->select = 'scenario';
         // only select the 'scenario' column
         $criteria->condition = 'qid=:qid';
         $criteria->params = array(':qid' => $qid);
         $criteria->order = 'scenario';
         $criteria->group = 'scenario';
         $scenarioresult = Conditions::model()->findAll($criteria);
         $scenariocount = count($scenarioresult);
         $showreplace = "{$questiontitle}" . $this->_showSpeaker($questiontext);
         $onlyshow = sprintf($clang->gT("Only show question %s IF"), $showreplace);
         $aData['conditionsoutput'] = '';
         $aData['extraGetParams'] = $extraGetParams;
         $aData['quesitonNavOptions'] = $questionNavOptions;
         $aData['conditionsoutput_action_error'] = $conditionsoutput_action_error;
         $aData['javascriptpre'] = $javascriptpre;
         $aData['onlyshow'] = $onlyshow;
         $aData['subaction'] = $subaction;
         $aData['scenariocount'] = $scenariocount;
         $aViewUrls['conditionslist_view'][] = $aData;
         if ($scenariocount > 0) {
             //self::_js_admin_includes($this->config->item("generalscripts").'jquery/jquery.checkgroup.js');
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.checkgroup.js');
             foreach ($scenarioresult as $scenarionr) {
                 $scenariotext = "";
                 if ($s == 0 && $scenariocount > 1) {
                     $scenariotext = " -------- <i>Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($s > 0) {
                     $scenariotext = " -------- <i>" . $clang->gT("OR") . " Scenario {$scenarionr['scenario']}</i> --------";
                 }
                 if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                     $initialCheckbox = "<td><input type='checkbox' id='scenarioCbx{$scenarionr['scenario']}' checked='checked'/>\n" . "<script type='text/javascript'>\$(document).ready(function () { \$('#scenarioCbx{$scenarionr['scenario']}').checkgroup({ groupName:'aConditionFromScenario{$scenarionr['scenario']}'}); });</script>" . "</td><td>&nbsp;</td>\n";
                 } else {
                     $initialCheckbox = "";
                 }
                 if ($scenariotext != "" && ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete")) {
                     $img_tag = CHtml::image($imageurl . '/scenario_delete.png', $clang->gT("Delete this scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content = CHtml::link($img_tag, '#', array('onclick' => "if ( confirm('" . $clang->gT("Are you sure you want to delete all conditions set in this scenario?", "js") . "')) { document.getElementById('deletescenario{$scenarionr['scenario']}').submit();}"));
                     $img_tag = CHtml::image($imageurl . '/scenario_edit.png', $clang->gT("Edit scenario"), array('name' => 'DeleteWholeGroup'));
                     $additional_main_content .= CHtml::link($img_tag, '#', array('id' => 'editscenariobtn' . $scenarionr['scenario'], 'onclick' => "\$('#editscenario{$scenarionr['scenario']}').toggle('slow');"));
                     $aData['additional_content'] = $additional_main_content;
                 }
                 $aData['initialCheckbox'] = $initialCheckbox;
                 $aData['scenariotext'] = $scenariotext;
                 $aData['scenarionr'] = $scenarionr;
                 if (!isset($aViewUrls['output'])) {
                     $aViewUrls['output'] = '';
                 }
                 $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_scenario', $aData, TRUE);
                 unset($currentfield);
                 $query = "SELECT count(*) as recordcount\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' ";
                 // avoid catching SRCtokenAttr conditions
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->queryRow();
                 $conditionscount = (int) $result['recordcount'];
                 $query = "SELECT c.cid, c.scenario, c.cqid, c.cfieldname, c.method, c.value, q.type\n                    FROM {{conditions}} c, {{questions}} q, {{groups}} g\n                    WHERE c.cqid=q.qid " . "AND q.gid=g.gid " . "AND q.parent_qid=0 " . "AND q.language=:lang1 " . "AND g.language=:lang2 " . "AND c.qid=:qid " . "AND c.scenario=:scenario " . "AND c.cfieldname NOT LIKE '{%' " . "ORDER BY g.group_order, q.question_order, c.cfieldname";
                 $sLanguage = Survey::model()->findByPk($iSurveyID)->language;
                 $result = Yii::app()->db->createCommand($query)->bindValue(":scenario", $scenarionr['scenario'])->bindValue(":qid", $qid, PDO::PARAM_INT)->bindValue(":lang1", $sLanguage, PDO::PARAM_STR)->bindValue(":lang2", $sLanguage, PDO::PARAM_STR)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $querytoken = "SELECT count(*) as recordcount " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' ";
                 // only catching SRCtokenAttr conditions
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->queryRow() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscounttoken = (int) $resulttoken['recordcount'];
                 $querytoken = "SELECT {{conditions}}.cid, " . "{{conditions}}.scenario, " . "{{conditions}}.cqid, " . "{{conditions}}.cfieldname, " . "{{conditions}}.method, " . "{{conditions}}.value, " . "'' AS type " . "FROM {{conditions}} " . "WHERE " . " {{conditions}}.qid=:qid " . "AND {{conditions}}.scenario=:scenario " . "AND {{conditions}}.cfieldname LIKE '{%' " . "ORDER BY {{conditions}}.cfieldname";
                 $resulttoken = Yii::app()->db->createCommand($querytoken)->bindValue(":scenario", $scenarionr['scenario'], PDO::PARAM_INT)->bindValue(":qid", $qid, PDO::PARAM_INT)->query() or safeDie("Couldn't get other conditions for question {$qid}<br />{$query}<br />");
                 $conditionscount = $conditionscount + $conditionscounttoken;
                 if ($conditionscount > 0) {
                     $aConditionsMerged = array();
                     foreach ($resulttoken->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($result->readAll() as $arow) {
                         $aConditionsMerged[] = $arow;
                     }
                     foreach ($aConditionsMerged as $rows) {
                         if ($rows['method'] == "") {
                             $rows['method'] = "==";
                         }
                         //Fill in the empty method from previous versions
                         $markcidstyle = "oddrow";
                         if (array_search($rows['cid'], $markcidarray) !== FALSE) {
                             // This is the style used when the condition editor is called
                             // in order to check which conditions prevent a question deletion
                             $markcidstyle = "markedrow";
                         }
                         if ($subaction == "editthiscondition" && isset($p_cid) && $rows['cid'] === $p_cid) {
                             // Style used when editing a condition
                             $markcidstyle = "editedrow";
                         }
                         if (isset($currentfield) && $currentfield != $rows['cfieldname']) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("and") . "</strong></span></td></tr>";
                         } elseif (isset($currentfield)) {
                             $aViewUrls['output'] .= "<tr class='evenrow'>\n" . "\t<td colspan='2'>\n" . "<span><strong>" . $clang->gT("or") . "</strong></span></td></tr>";
                         }
                         $aViewUrls['output'] .= "\t<tr class='{$markcidstyle}'>\n" . "\t<td colspan='2'>" . CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "conditionaction{$rows['cid']}", 'name' => "conditionaction{$rows['cid']}")) . "<table>\n" . "\t<tr>\n";
                         if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
                             $aViewUrls['output'] .= "<td>&nbsp;&nbsp;</td>" . "<td>\n" . "\t<input type='checkbox' name='aConditionFromScenario{$scenarionr['scenario']}' id='cbox{$rows['cid']}' value='{$rows['cid']}' checked='checked'/>\n" . "</td>\n";
                         }
                         $aViewUrls['output'] .= "" . "<td>\n" . "\t<span>\n";
                         $leftOperandType = 'unknown';
                         // prevquestion, tokenattr
                         if ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['cfieldname'], $extractedTokenAttr) > 0) {
                             $leftOperandType = 'tokenattr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                             // TIBO not sure this is used anymore !!
                             $conditionsList[] = array("cid" => $rows['cid'], "text" => $thisAttrName);
                         } else {
                             $leftOperandType = 'prevquestion';
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $rows['cfieldname']) {
                                     $aViewUrls['output'] .= "\t{$cqn['0']} (qid{$rows['cqid']})\n";
                                     $conditionsList[] = array("cid" => $rows['cid'], "text" => $cqn[0] . " ({$rows['value']})");
                                 } else {
                                     //$aViewUrls['output'] .= "\t<font color='red'>ERROR: Delete this condition. It is out of order.</font>\n";
                                 }
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n" . "<span>\n" . $method[trim($rows['method'])] . "</span>\n" . "\t</td>\n" . "\n" . "\t<td>\n" . "<span>\n";
                         // let's read the condition's right operand
                         // determine its type and display it
                         $rightOperandType = 'unknown';
                         // predefinedAnsw,constantVal, prevQsgqa, tokenAttr, regexp
                         if ($rows['method'] == 'RX') {
                             $rightOperandType = 'regexp';
                             $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                         } elseif (preg_match('/^@([0-9]+X[0-9]+X[^@]*)@$/', $rows['value'], $matchedSGQA) > 0) {
                             // SGQA
                             $rightOperandType = 'prevQsgqa';
                             $textfound = false;
                             foreach ($cquestions as $cqn) {
                                 if ($cqn[3] == $matchedSGQA[1]) {
                                     $matchedSGQAText = $cqn[0];
                                     $textfound = true;
                                     break;
                                 }
                             }
                             if ($textfound === false) {
                                 $matchedSGQAText = $rows['value'] . ' (' . $clang->gT("Not found") . ')';
                             }
                             $aViewUrls['output'] .= "" . HTMLEscape($matchedSGQAText) . "\n";
                         } elseif ($thissurvey['anonymized'] != 'Y' && preg_match('/^{TOKEN:([^}]*)}$/', $rows['value'], $extractedTokenAttr) > 0) {
                             $rightOperandType = 'tokenAttr';
                             $aTokenAttrNames = getTokenFieldsAndNames($iSurveyID);
                             if (count($aTokenAttrNames) != 0) {
                                 $thisAttrName = HTMLEscape($aTokenAttrNames[strtolower($extractedTokenAttr[1])]['description']) . " [" . $clang->gT("From token table") . "]";
                             } else {
                                 $thisAttrName = HTMLEscape($extractedTokenAttr[1]) . " [" . $clang->gT("Inexistant token table") . "]";
                             }
                             $aViewUrls['output'] .= "\t{$thisAttrName}\n";
                         } elseif (isset($canswers)) {
                             foreach ($canswers as $can) {
                                 if ($can[0] == $rows['cfieldname'] && $can[1] == $rows['value']) {
                                     $aViewUrls['output'] .= "{$can['2']} ({$can['1']})\n";
                                     $rightOperandType = 'predefinedAnsw';
                                 }
                             }
                         }
                         // if $rightOperandType is still unkown then it is a simple constant
                         if ($rightOperandType == 'unknown') {
                             $rightOperandType = 'constantVal';
                             if ($rows['value'] == ' ' || $rows['value'] == '') {
                                 $aViewUrls['output'] .= "" . $clang->gT("No answer") . "\n";
                             } else {
                                 $aViewUrls['output'] .= "" . HTMLEscape($rows['value']) . "\n";
                             }
                         }
                         $aViewUrls['output'] .= "\t</span></td>\n" . "\t<td>\n";
                         if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "editthiscondition" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "deletescenario" || $subaction == "delete") {
                             // show single condition action buttons in edit mode
                             $aData['rows'] = $rows;
                             $aData['sImageURL'] = Yii::app()->getConfig('adminimageurl');
                             //$aViewUrls['includes/conditions_edit'][] = $aData;
                             $aViewUrls['output'] .= $this->getController()->render('/admin/conditions/includes/conditions_edit', $aData, TRUE);
                             // now sets e corresponding hidden input field
                             // depending on the leftOperandType
                             if ($leftOperandType == 'tokenattr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('csrctoken', HTMLEscape($rows['cfieldname']), array('id' => 'csrctoken' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('cquestions', HTMLEscape($rows['cfieldname']), array('id' => 'cquestions' . $rows['cid']));
                             }
                             // now set the corresponding hidden input field
                             // depending on the rightOperandType
                             // This is used when Editting a condition
                             if ($rightOperandType == 'predefinedAnsw') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITcanswers[]', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'prevQsgqa') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITprevQuestionSGQA', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'tokenAttr') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITtokenAttr', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } elseif ($rightOperandType == 'regexp') {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionRegexp', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             } else {
                                 $aViewUrls['output'] .= CHtml::hiddenField('EDITConditionConst', HTMLEscape($rows['value']), array('id' => 'editModeTargetVal' . $rows['cid']));
                             }
                         }
                         $aViewUrls['output'] .= CHtml::closeTag('td') . CHtml::closeTag('tr') . CHtml::closeTag('table') . CHtml::closeTag('form') . CHtml::closeTag('td') . CHtml::closeTag('tr');
                         $currentfield = $rows['cfieldname'];
                     }
                 }
                 $s++;
             }
         } else {
             // no condition ==> disable delete all conditions button, and display a simple comment
             $aViewUrls['output'] = CHtml::openTag('tr') . CHtml::tag('td', array(), $clang->gT("This question is always shown.")) . CHtml::tag('td', array(), '&nbsp;') . CHtml::closeTag('tr');
         }
         $aViewUrls['output'] .= CHtml::closeTag('table');
     }
     //END DISPLAY CONDITIONS FOR THIS QUESTION
     // BEGIN: DISPLAY THE COPY CONDITIONS FORM
     if ($subaction == "copyconditionsform" || $subaction == "copyconditions") {
         $aViewUrls['output'] .= "<tr class=''><td colspan='3'>\n" . CHtml::form(array("/admin/conditions/sa/index/subaction/copyconditions/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "copyconditions", 'name' => "copyconditions")) . "<div class='header ui-widget-header'>" . $clang->gT("Copy conditions") . "</div>\n";
         //CopyConditionsMessage
         if (isset($CopyConditionsMessage)) {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "{$CopyConditionsMessage}\n" . "</div>\n";
         }
         if (isset($conditionsList) && is_array($conditionsList)) {
             //TIBO
             $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/jquery.multiselect.min.js');
             // TODO
             $aViewUrls['output'] .= "<script type='text/javascript'>\$(document).ready(function () { \$('#copytomultiselect').multiselect( { autoOpen: true, noneSelectedText: '" . $clang->gT("No questions selected") . "', checkAllText: '" . $clang->gT("Check all") . "', uncheckAllText: '" . $clang->gT("Uncheck all") . "', selectedText: '# " . $clang->gT("selected") . "', beforeclose: function(){ return false;},height: 200 } ); });</script>";
             $aViewUrls['output'] .= "\t<div class='conditioncopy-tbl-row'>\n" . "\t<div class='condition-tbl-left'>" . $clang->gT("Copy the selected conditions to") . ":</div>\n" . "\t<div class='condition-tbl-right'>\n" . "\t\t<select name='copyconditionsto[]' id='copytomultiselect'  multiple='multiple' >\n";
             if (isset($pquestions) && count($pquestions) != 0) {
                 foreach ($pquestions as $pq) {
                     $aViewUrls['output'] .= "\t\t<option value='{$pq['fieldname']}'>" . $pq['text'] . "</option>\n";
                 }
             }
             $aViewUrls['output'] .= "\t\t</select>\n" . "\t</div>\n" . "\t</div>\n";
             if (!isset($pquestions) || count($pquestions) == 0) {
                 $disableCopyCondition = " disabled='disabled'";
             } else {
                 $disableCopyCondition = " ";
             }
             $aViewUrls['output'] .= "\t<div class='condition-tbl-full'>\n" . "\t\t<input type='submit' value='" . $clang->gT("Copy conditions") . "' onclick=\"prepareCopyconditions(); return true;\" {$disableCopyCondition}/>\n" . "<input type='hidden' name='subaction' value='copyconditions' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "</div>\n";
             $aViewUrls['output'] .= "<script type=\"text/javascript\">\n" . "function prepareCopyconditions()\n" . "{\n" . "\t\$(\"input:checked[name^='aConditionFromScenario']\").each(function(i,val)\n" . "\t{\n" . "var thecid = val.value;\n" . "var theform = document.getElementById('copyconditions');\n" . "addHiddenElement(theform,'copyconditionsfrom[]',thecid);\n" . "return true;\n" . "\t});\n" . "}\n" . "</script>\n";
         } else {
             $aViewUrls['output'] .= "<div class='messagebox ui-corner-all'>\n" . "<div class='partialheader'>" . $clang->gT("There are no existing conditions in this survey.") . "</div><br />\n" . "</div>\n";
         }
         $aViewUrls['output'] .= "</form></td></tr>\n";
     }
     // END: DISPLAY THE COPY CONDITIONS FORM
     if (isset($cquestions)) {
         if (count($cquestions) > 0 && count($cquestions) <= 10) {
             $qcount = count($cquestions);
         } else {
             $qcount = 9;
         }
     } else {
         $qcount = 0;
     }
     //BEGIN: DISPLAY THE ADD or EDIT CONDITION FORM
     if ($subaction == "editconditionsform" || $subaction == "insertcondition" || $subaction == "updatecondition" || $subaction == "deletescenario" || $subaction == "renumberscenarios" || $subaction == "deleteallconditions" || $subaction == "updatescenario" || $subaction == "editthiscondition" || $subaction == "delete") {
         $aViewUrls['output'] .= CHtml::form(array("/admin/conditions/sa/index/subaction/{$subaction}/surveyid/{$iSurveyID}/gid/{$gid}/qid/{$qid}/"), 'post', array('id' => "editconditions", 'name' => "editconditions"));
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $mytitle = $clang->gT("Edit condition");
         } else {
             $mytitle = $clang->gT("Add condition");
         }
         $aViewUrls['output'] .= "<div class='header ui-widget-header'>" . $mytitle . "</div>\n";
         ///////////////////////////////////////////////////////////////////////////////////////////
         // Begin "Scenario" row
         if ($subaction != "editthiscondition" && isset($scenariocount) && ($scenariocount == 1 || $scenariocount == 0) || $subaction == "editthiscondition" && isset($scenario) && $scenario == 1) {
             $scenarioAddBtn = "\t<a id='scenarioaddbtn' href='#' onclick=\"\$('#scenarioaddbtn').hide();\$('#defaultscenariotxt').hide('slow');\$('#scenario').show('slow');\">" . "<img src='{$imageurl}/plus.png' alt='" . $clang->gT('Add scenario') . "' /></a>\n";
             $scenarioTxt = "<span id='defaultscenariotxt'>" . $clang->gT("Default scenario") . "</span>";
             $scenarioInputStyle = "style = 'display: none;'";
         } else {
             $scenarioAddBtn = "";
             $scenarioTxt = "";
             $scenarioInputStyle = "style = ''";
         }
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>{$scenarioAddBtn}&nbsp;" . $clang->gT("Scenario") . "</div>\n" . "<div class='condition-tbl-right'><input type='text' name='scenario' id='scenario' value='1' size='2' {$scenarioInputStyle}/>" . "{$scenarioTxt}\n" . "</div>\n" . "</div>\n";
         // Begin "Question" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Question") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "\t<div id=\"conditionsource\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t<li><a href=\"#SRCPREVQUEST\"><span>" . $clang->gT("Previous questions") . "</span></a></li>\n" . "\t<li><a href=\"#SRCTOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t</ul>\n";
         // Previous question tab
         $aViewUrls['output'] .= "<div id='SRCPREVQUEST'><select name='cquestions' id='cquestions' size='" . ($qcount + 1) . "' >\n";
         if (isset($cquestions)) {
             $js_getAnswers_onload = "";
             foreach ($cquestions as $cqn) {
                 $aViewUrls['output'] .= "<option value='{$cqn['3']}' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_cquestions) && $cqn[3] == $p_cquestions) {
                     $aViewUrls['output'] .= " selected";
                     if (isset($p_canswers)) {
                         $canswersToSelect = "";
                         foreach ($p_canswers as $checkval) {
                             $canswersToSelect .= ";{$checkval}";
                         }
                         $canswersToSelect = substr($canswersToSelect, 1);
                         $js_getAnswers_onload .= "\$('#canswersToSelect').val('{$canswersToSelect}');\n";
                     }
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n";
         // Source token Tab
         $aViewUrls['output'] .= "<div id='SRCTOKENATTRS'><select name='csrctoken' id='csrctoken' size='" . ($qcount + 1) . "' >\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             // Check to select
             if (isset($p_csrctoken) && $p_csrctoken == '{TOKEN:' . strtoupper($tokenattr) . '}') {
                 $selectThisSrcTokenAttr = "selected=\"selected\"";
             } else {
                 $selectThisSrcTokenAttr = "";
             }
             $aViewUrls['output'] .= "<option value='{TOKEN:" . strtoupper($tokenattr) . "}' {$selectThisSrcTokenAttr}>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n\n";
         $aViewUrls['output'] .= "\t</div>\n";
         // end conditionsource div
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin "Comparison operator" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Comparison operator") . "</div>\n" . "<div class='condition-tbl-right'>\n" . "<select name='method' id='method'>\n";
         foreach ($method as $methodCode => $methodTxt) {
             $selected = $methodCode == "==" ? " selected='selected'" : "";
             $aViewUrls['output'] .= "\t<option value='" . $methodCode . "'{$selected}>" . $methodTxt . "</option>\n";
         }
         $aViewUrls['output'] .= "</select>\n" . "</div>\n" . "</div>\n";
         // Begin "Answer" row
         $aViewUrls['output'] .= "<div class='condition-tbl-row'>\n" . "<div class='condition-tbl-left'>" . $clang->gT("Answer") . "</div>\n";
         if ($subaction == "editthiscondition") {
             $multipletext = "";
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['EDITConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['EDITConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         } else {
             $multipletext = "multiple";
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 $EDITConditionConst = HTMLEscape($_POST['ConditionConst']);
             } else {
                 $EDITConditionConst = "";
             }
             if (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 $EDITConditionRegexp = HTMLEscape($_POST['ConditionRegexp']);
             } else {
                 $EDITConditionRegexp = "";
             }
         }
         $aViewUrls['output'] .= "" . "<div class='condition-tbl-right'>\n" . "<div id=\"conditiontarget\" class=\"tabs-nav\">\n" . "\t<ul>\n" . "\t\t<li><a href=\"#CANSWERSTAB\"><span>" . $clang->gT("Predefined") . "</span></a></li>\n" . "\t\t<li><a href=\"#CONST\"><span>" . $clang->gT("Constant") . "</span></a></li>\n" . "\t\t<li><a href=\"#PREVQUESTIONS\"><span>" . $clang->gT("Questions") . "</span></a></li>\n" . "\t\t<li><a href=\"#TOKENATTRS\"><span>" . $clang->gT("Token fields") . "</span></a></li>\n" . "\t\t<li><a href=\"#REGEXP\"><span>" . $clang->gT("RegExp") . "</span></a></li>\n" . "\t</ul>\n";
         // Predefined answers tab
         $aViewUrls['output'] .= "\t<div id='CANSWERSTAB'>\n" . "\t\t<select  name='canswers[]' {$multipletext} id='canswers' size='7'>\n" . "\t\t</select>\n" . "\t\t<br /><span id='canswersLabel'>" . $clang->gT("Predefined answer options for this question") . "</span>\n" . "\t</div>\n";
         // Constant tab
         $aViewUrls['output'] .= "\t<div id='CONST' style='display:block;' >\n" . "\t\t<textarea name='ConditionConst' id='ConditionConst' rows='5' cols='113'>{$EDITConditionConst}</textarea>\n" . "\t\t<br /><div id='ConditionConstLabel'>" . $clang->gT("Constant value") . "</div>\n" . "\t</div>\n";
         // Previous answers tab @SGQA@ placeholders
         $aViewUrls['output'] .= "\t<div id='PREVQUESTIONS'>\n" . "\t\t<select name='prevQuestionSGQA' id='prevQuestionSGQA' size='7'>\n";
         foreach ($cquestions as $cqn) {
             // building the @SGQA@ placeholders options
             if ($cqn[2] != 'M' && $cqn[2] != 'P') {
                 // Type M or P aren't real fieldnames and thus can't be used in @SGQA@ placehodlers
                 $aViewUrls['output'] .= "\t\t<option value='@{$cqn['3']}@' title=\"" . htmlspecialchars($cqn[0]) . "\"";
                 if (isset($p_prevquestionsgqa) && $p_prevquestionsgqa == "@" . $cqn[3] . "@") {
                     $aViewUrls['output'] .= " selected='selected'";
                 }
                 $aViewUrls['output'] .= ">{$cqn['0']}</option>\n";
             }
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='prevQuestionSGQALabel'>" . $clang->gT("Answers from previous questions") . "</span>\n" . "\t</div>\n";
         // Token tab
         $aViewUrls['output'] .= "\t<div id='TOKENATTRS'>\n" . "\t\t<select name='tokenAttr' id='tokenAttr' size='7'>\n";
         foreach (getTokenFieldsAndNames($iSurveyID) as $tokenattr => $tokenattrName) {
             $aViewUrls['output'] .= "\t\t<option value='{TOKEN:" . strtoupper($tokenattr) . "}'>" . HTMLEscape($tokenattrName['description']) . "</option>\n";
         }
         $aViewUrls['output'] .= "\t\t</select>\n" . "\t\t<br /><span id='tokenAttrLabel'>" . $clang->gT("Attributes values from the participant's token") . "</span>\n" . "\t</div>\n";
         // Regexp Tab
         $aViewUrls['output'] .= "\t<div id='REGEXP' style='display:block;'>\n" . "\t\t<textarea name='ConditionRegexp' id='ConditionRegexp' rows='5' cols='113'>{$EDITConditionRegexp}</textarea>\n" . "\t\t<br /><div id='ConditionRegexpLabel'><a href=\"http://docs.limesurvey.org/tiki-index.php?page=Using+Regular+Expressions\" target=\"_blank\">" . $clang->gT("Regular expression") . "</a></div>\n" . "\t</div>\n";
         $aViewUrls['output'] .= "</div>\n";
         // end conditiontarget div
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("adminscripts") . 'conditions.js');
         $this->getController()->_js_admin_includes(Yii::app()->getConfig("generalscripts") . 'jquery/lime-conditions-tabs.js');
         if ($subaction == "editthiscondition" && isset($p_cid)) {
             $submitLabel = $clang->gT("Update condition");
             $submitSubaction = "updatecondition";
             $submitcid = sanitize_int($p_cid);
         } else {
             $submitLabel = $clang->gT("Add condition");
             $submitSubaction = "insertcondition";
             $submitcid = "";
         }
         $aViewUrls['output'] .= "</div>\n" . "</div>\n";
         // Begin buttons row
         $aViewUrls['output'] .= "<div class='condition-tbl-full'>\n" . "\t<input type='reset' id='resetForm' value='" . $clang->gT("Clear") . "' />\n" . "\t<input type='submit' value='" . $submitLabel . "' />\n" . "<input type='hidden' name='sid' value='{$iSurveyID}' />\n" . "<input type='hidden' name='gid' value='{$gid}' />\n" . "<input type='hidden' name='qid' value='{$qid}' />\n" . "<input type='hidden' name='subaction' value='{$submitSubaction}' />\n" . "<input type='hidden' name='cqid' id='cqid' value='' />\n" . "<input type='hidden' name='cid' id='cid' value='" . $submitcid . "' />\n" . "<input type='hidden' name='editTargetTab' id='editTargetTab' value='' />\n" . "<input type='hidden' name='editSourceTab' id='editSourceTab' value='' />\n" . "<input type='hidden' name='canswersToSelect' id='canswersToSelect' value='' />\n" . "</div>\n" . "</form>\n";
         if (!isset($js_getAnswers_onload)) {
             $js_getAnswers_onload = '';
         }
         $aViewUrls['output'] .= "<script type='text/javascript'>\n" . "<!--\n" . "\t" . $js_getAnswers_onload . "\n";
         if (isset($p_method)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('method').value='" . $p_method . "';\n";
         }
         if ($subaction == "editthiscondition") {
             // in edit mode we read previous values in order to dusplay them in the corresponding inputs
             if (isset($_POST['EDITConditionConst']) && $_POST['EDITConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['EDITConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['EDITprevQuestionSGQA']) && $_POST['EDITprevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['EDITprevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['EDITtokenAttr']) && $_POST['EDITtokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['EDITtokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['EDITConditionRegexp']) && $_POST['EDITConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['EDITConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } elseif (isset($_POST['EDITcanswers']) && is_array($_POST['EDITcanswers'])) {
                 // was a predefined answers post
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
                 $aViewUrls['output'] .= "\t\$('#canswersToSelect').val('" . $_POST['EDITcanswers'][0] . "');\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions']) && $_POST['cquestions'] != '') {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                     $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
                 }
             }
         } else {
             // in other modes, for the moment we do the same as for edit mode
             if (isset($_POST['ConditionConst']) && $_POST['ConditionConst'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionConst').value='".HTMLEscape($_POST['ConditionConst'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CONST';\n";
             } elseif (isset($_POST['prevQuestionSGQA']) && $_POST['prevQuestionSGQA'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('prevQuestionSGQA').value='" . HTMLEscape($_POST['prevQuestionSGQA']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#PREVQUESTIONS';\n";
             } elseif (isset($_POST['tokenAttr']) && $_POST['tokenAttr'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('tokenAttr').value='" . HTMLEscape($_POST['tokenAttr']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#TOKENATTRS';\n";
             } elseif (isset($_POST['ConditionRegexp']) && $_POST['ConditionRegexp'] != '') {
                 // In order to avoid issues with backslash escaping, I don't use javascript to set the value
                 // Thus the value is directly set when creating the Textarea element
                 //$aViewUrls['output'] .= "\tdocument.getElementById('ConditionRegexp').value='".HTMLEscape($_POST['ConditionRegexp'])."';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#REGEXP';\n";
             } else {
                 // was a predefined answers post
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . HTMLEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editTargetTab').value='#CANSWERSTAB';\n";
             }
             if (isset($_POST['csrctoken']) && $_POST['csrctoken'] != '') {
                 $aViewUrls['output'] .= "\tdocument.getElementById('csrctoken').value='" . HTMLEscape($_POST['csrctoken']) . "';\n";
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCTOKENATTRS';\n";
             } else {
                 if (isset($_POST['cquestions'])) {
                     $aViewUrls['output'] .= "\tdocument.getElementById('cquestions').value='" . javascriptEscape($_POST['cquestions']) . "';\n";
                 }
                 $aViewUrls['output'] .= "\tdocument.getElementById('editSourceTab').value='#SRCPREVQUEST';\n";
             }
         }
         if (isset($p_scenario)) {
             $aViewUrls['output'] .= "\tdocument.getElementById('scenario').value='" . $p_scenario . "';\n";
         }
         $aViewUrls['output'] .= "-->\n" . "</script>\n";
     }
     //END: DISPLAY THE ADD or EDIT CONDITION FORM
     $conditionsoutput = $aViewUrls['output'];
     $aData['conditionsoutput'] = $conditionsoutput;
     $this->_renderWrappedTemplate('conditions', $aViewUrls, $aData);
     // TMSW Conditions->Relevance:  Must call LEM->ConvertConditionsToRelevance() whenever Condition is added or updated - what is best location for that action?
 }
Esempio n. 26
0
 public function getExtendedData($colName, $sLanguage, $base64jsonFieldMap)
 {
     $oFieldMap = json_decode(base64_decode($base64jsonFieldMap));
     $value = $this->{$colName};
     $sFullValue = strip_tags(getExtendedAnswer(self::$sid, $oFieldMap->fieldname, $value, $sLanguage));
     if (strlen($sFullValue) > 50) {
         $sElipsizedValue = ellipsize($sFullValue, $this->ellipsize_question_value);
         $sValue = '<span data-toggle="tooltip" data-placement="left" title="' . quoteText($sFullValue) . '">' . $sElipsizedValue . '</span>';
     } else {
         $sValue = $sFullValue;
     }
     // Upload question
     if ($oFieldMap->type == '|' && strpos($oFieldMap->fieldname, 'filecount') === false) {
         $sSurveyEntry = "<table class='table table-condensed upload-question'><tr>";
         $aQuestionAttributes = getQuestionAttributeValues($oFieldMap->qid);
         $aFilesInfo = json_decode_ls($this->{$colName});
         for ($iFileIndex = 0; $iFileIndex < $aQuestionAttributes['max_num_of_files']; $iFileIndex++) {
             $sSurveyEntry .= '<tr>';
             if (isset($aFilesInfo[$iFileIndex])) {
                 $sSurveyEntry .= '<td>' . CHtml::link(rawurldecode($aFilesInfo[$iFileIndex]['name']), App()->createUrl("/admin/responses", array("sa" => "actionDownloadfile", "surveyid" => self::$sid, "iResponseId" => $this->id, "sFileName" => $aFilesInfo[$iFileIndex]['name']))) . '</td>';
                 $sSurveyEntry .= '<td>' . sprintf('%s Mb', round($aFilesInfo[$iFileIndex]['size'] / 1000, 2)) . '</td>';
                 if ($aQuestionAttributes['show_title']) {
                     if (!isset($aFilesInfo[$iFileIndex]['title'])) {
                         $aFilesInfo[$iFileIndex]['title'] = '';
                     }
                     $sSurveyEntry .= '<td>' . htmlspecialchars($aFilesInfo[$iFileIndex]['title'], ENT_QUOTES, 'UTF-8') . '</td>';
                 }
                 if ($aQuestionAttributes['show_comment']) {
                     if (!isset($aFilesInfo[$iFileIndex]['comment'])) {
                         $aFilesInfo[$iFileIndex]['comment'] = '';
                     }
                     $sSurveyEntry .= '<td>' . htmlspecialchars($aFilesInfo[$iFileIndex]['comment'], ENT_QUOTES, 'UTF-8') . '</td>';
                 }
             }
             $sSurveyEntry .= '</tr>';
         }
         $sSurveyEntry .= '</table>';
         $sValue = $sSurveyEntry;
     }
     return $sValue;
 }
 /**
  * Construction of replacement array, actually doing it with redata
  *
  * @param $aQuestionQanda : array from qanda helper
  * @return aray of replacement for question.psptl
  **/
 public static function getQuestionReplacement($aQuestionQanda)
 {
     // Get the default replacement and set empty value by default
     $aReplacement = array("QID" => "", "SGQ" => "", "AID" => "", "QUESTION_CODE" => "", "QUESTION_NUMBER" => "", "QUESTION" => "", "QUESTION_TEXT" => "", "QUESTIONHELP" => "", "QUESTIONHELPPLAINTEXT" => "", "QUESTION_CLASS" => "", "QUESTION_MAN_CLASS" => "", "QUESTION_INPUT_ERROR_CLASS" => "", "ANSWER" => "", "QUESTION_HELP" => "", "QUESTION_VALID_MESSAGE" => "", "QUESTION_FILE_VALID_MESSAGE" => "", "QUESTION_MAN_MESSAGE" => "", "QUESTION_MANDATORY" => "", "QUESTION_ESSENTIALS" => "");
     if (!is_array($aQuestionQanda) || empty($aQuestionQanda[0])) {
         return $aReplacement;
     }
     $iQid = $aQuestionQanda[4];
     $lemQuestionInfo = LimeExpressionManager::GetQuestionStatus($iQid);
     $iSurveyId = Yii::app()->getConfig('surveyID');
     // Or : by SGQA of question ? by Question::model($iQid)->sid;
     $oSurveyId = Survey::model()->findByPk($iSurveyId);
     $sType = $lemQuestionInfo['info']['type'];
     // Core value : not replaced
     $aReplacement['QID'] = $iQid;
     $aReplacement['GID'] = $aQuestionQanda[6];
     // Not sure for aleatory : it's the real gid or the updated gid ? We need original gid or updated gid ?
     $aReplacement['SGQ'] = $aQuestionQanda[7];
     $aReplacement['AID'] = isset($aQuestionQanda[0]['aid']) ? $aQuestionQanda[0]['aid'] : "";
     $aReplacement['QUESTION_CODE'] = $aReplacement['QUESTION_NUMBER'] = "";
     $sCode = $aQuestionQanda[5];
     $iNumber = $aQuestionQanda[0]['number'];
     switch (Yii::app()->getConfig('showqnumcode')) {
         case 'both':
             $aReplacement['QUESTION_CODE'] = $sCode;
             $aReplacement['QUESTION_NUMBER'] = $iNumber;
             break;
         case 'number':
             $aReplacement['QUESTION_NUMBER'] = $iNumber;
             break;
         case 'number':
             $aReplacement['QUESTION_CODE'] = $sCode;
             break;
         case 'choose':
         default:
             switch ($oSurveyId->showqnumcode) {
                 case 'B':
                     // Both
                     $aReplacement['QUESTION_CODE'] = $sCode;
                     $aReplacement['QUESTION_NUMBER'] = $iNumber;
                     break;
                 case 'N':
                     $aReplacement['QUESTION_NUMBER'] = $iNumber;
                     break;
                 case 'C':
                     $aReplacement['QUESTION_CODE'] = $sCode;
                     break;
                 case 'X':
                 default:
                     break;
             }
             break;
     }
     $aReplacement['QUESTION'] = $aQuestionQanda[0]['all'];
     // Deprecated : only used in old template (very old)
     // Core value : user text
     $aReplacement['QUESTION_TEXT'] = $aQuestionQanda[0]['text'];
     $aReplacement['QUESTIONHELP'] = $lemQuestionInfo['info']['help'];
     // User help
     // To be moved in a extra plugin : QUESTIONHELP img adding
     $sTemplateDir = Template::model()->getTemplatePath($oSurveyId->template);
     $sTemplateUrl = Template::model()->getTemplateURL($oSurveyId->template);
     if (flattenText($aReplacement['QUESTIONHELP'], true, true) != '') {
         $aReplacement['QUESTIONHELP'] = Yii::app()->getController()->renderPartial('/survey/system/questionhelp/questionhelp', array('questionHelp' => $aReplacement['QUESTIONHELP']), true);
     }
     // Core value :the classes
     $aReplacement['QUESTION_CLASS'] = Question::getQuestionClass($sType);
     //get additional question classes from question attribute
     $aQuestionAttributes = getQuestionAttributeValues($aQuestionQanda[4]);
     //add additional classes
     if (isset($aQuestionAttributes['cssclass'])) {
         $aReplacement['QUESTION_CLASS'] .= " " . $aQuestionAttributes['cssclass'];
     }
     $aMandatoryClass = array();
     if ($lemQuestionInfo['info']['mandatory'] == 'Y') {
         $aMandatoryClass[] = 'mandatory';
     }
     if ($lemQuestionInfo['anyUnanswered'] && $_SESSION['survey_' . $iSurveyId]['maxstep'] != $_SESSION['survey_' . $iSurveyId]['step']) {
         $aMandatoryClass[] = 'missing';
     }
     $aReplacement['QUESTION_MAN_CLASS'] = !empty($aMandatoryClass) ? " " . implode(" ", $aMandatoryClass) : "";
     $aReplacement['QUESTION_INPUT_ERROR_CLASS'] = $aQuestionQanda[0]['input_error_class'];
     // Core value : LS text : EM and not
     $aReplacement['ANSWER'] = $aQuestionQanda[1];
     $aReplacement['QUESTION_HELP'] = $aQuestionQanda[0]['help'];
     // Core help only, not EM
     $aReplacement['QUESTION_VALID_MESSAGE'] = $aQuestionQanda[0]['valid_message'];
     // $lemQuestionInfo['validTip']
     $aReplacement['QUESTION_FILE_VALID_MESSAGE'] = $aQuestionQanda[0]['file_valid_message'];
     // $lemQuestionInfo['??']
     $aReplacement['QUESTION_MAN_MESSAGE'] = $aQuestionQanda[0]['man_message'];
     $aReplacement['QUESTION_MANDATORY'] = $aQuestionQanda[0]['mandatory'];
     // For QUESTION_ESSENTIALS
     $aHtmlOptions = array();
     if (!$lemQuestionInfo['relevant'] || $lemQuestionInfo['hidden']) {
         $aHtmlOptions['style'] = 'display: none;';
     }
     // Launch the event
     $event = new PluginEvent('beforeQuestionRender');
     // Some helper
     $event->set('surveyId', $iSurveyId);
     $event->set('type', $sType);
     $event->set('code', $sCode);
     $event->set('qid', $iQid);
     $event->set('gid', $aReplacement['GID']);
     // User text
     $event->set('text', $aReplacement['QUESTION_TEXT']);
     $event->set('questionhelp', $aReplacement['QUESTIONHELP']);
     // The classes
     $event->set('class', $aReplacement['QUESTION_CLASS']);
     $event->set('man_class', $aReplacement['QUESTION_MAN_CLASS']);
     $event->set('input_error_class', $aReplacement['QUESTION_INPUT_ERROR_CLASS']);
     // LS core text
     $event->set('answers', $aReplacement['ANSWER']);
     $event->set('help', $aReplacement['QUESTION_HELP']);
     $event->set('man_message', $aReplacement['QUESTION_MAN_MESSAGE']);
     $event->set('valid_message', $aReplacement['QUESTION_VALID_MESSAGE']);
     $event->set('file_valid_message', $aReplacement['QUESTION_FILE_VALID_MESSAGE']);
     // htmlOptions for container
     $event->set('aHtmlOptions', $aHtmlOptions);
     App()->getPluginManager()->dispatchEvent($event);
     // User text
     $aReplacement['QUESTION_TEXT'] = $event->get('text');
     $aReplacement['QUESTIONHELP'] = $event->get('questionhelp');
     $aReplacement['QUESTIONHELPPLAINTEXT'] = strip_tags(addslashes($aReplacement['QUESTIONHELP']));
     // The classes
     $aReplacement['QUESTION_CLASS'] = $event->get('class');
     $aReplacement['QUESTION_MAN_CLASS'] = $event->get('man_class');
     $aReplacement['QUESTION_INPUT_ERROR_CLASS'] = $event->get('input_error_class');
     // LS core text
     $aReplacement['ANSWER'] = $event->get('answers');
     $aReplacement['QUESTION_HELP'] = $event->get('help');
     $aReplacement['QUESTION_MAN_MESSAGE'] = $event->get('man_message');
     $aReplacement['QUESTION_VALID_MESSAGE'] = $event->get('valid_message');
     $aReplacement['QUESTION_FILE_VALID_MESSAGE'] = $event->get('file_valid_message');
     $aReplacement['QUESTION_MANDATORY'] = $event->get('mandatory', $aReplacement['QUESTION_MANDATORY']);
     // Always add id for QUESTION_ESSENTIALS
     $aHtmlOptions['id'] = "question{$iQid}";
     $aReplacement['QUESTION_ESSENTIALS'] = CHtml::renderAttributes($aHtmlOptions);
     return $aReplacement;
 }
Esempio n. 28
0
 function browse($iSurveyID)
 {
     $aData = $this->_getData($iSurveyID);
     extract($aData);
     $aViewUrls = array();
     $oBrowseLanguage = new Limesurvey_lang($aData['language']);
     $tokenRequest = Yii::app()->request->getParam('token', null);
     //Delete Individual answer using inrow delete buttons/links - checked
     if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') != '' && Yii::app()->request->getPost('deleteanswer') != 'marked') {
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
             $iResponseID = (int) Yii::app()->request->getPost('deleteanswer');
             // sanitize the value
             Response::model($iSurveyID)->findByPk($iResponseID)->delete(true);
             // delete timings if savetimings is set
             if ($aData['surveyinfo']['savetimings'] == "Y") {
                 SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
             }
             Yii::app()->session['flashmessage'] = sprintf(gT("Response ID %s was successfully deleted."), $iResponseID);
         } else {
             Yii::app()->session['flashmessage'] = gT("Access denied!", 'js');
         }
     }
     // Marked responses -> deal with the whole batch of marked responses
     if (Yii::app()->request->getPost('markedresponses') && count(Yii::app()->request->getPost('markedresponses')) > 0) {
         // Delete the marked responses - checked
         if (Yii::app()->request->getPost('deleteanswer') && Yii::app()->request->getPost('deleteanswer') === 'marked') {
             if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'delete')) {
                 foreach (Response::model($iSurveyID)->findAllByPk(Yii::app()->request->getPost('markedresponses')) as $response) {
                     $response->deleteFiles();
                     // delete timings if savetimings is set
                     /**
                      * @todo Move this to the Response model.
                      */
                     if ($aData['surveyinfo']['savetimings'] == "Y") {
                         SurveyTimingDynamic::model($iSurveyID)->deleteByPk($iResponseID);
                     }
                 }
                 Response::model($iSurveyID)->deleteByPk(Yii::app()->request->getPost('markedresponses'));
                 Yii::app()->session['flashmessage'] = sprintf(ngT("%s response was successfully deleted.", "%s responses were successfully deleted.", count(Yii::app()->request->getPost('markedresponses'))), count(Yii::app()->request->getPost('markedresponses')), 'js');
             } else {
                 Yii::app()->session['flashmessage'] = $clang->gT("Access denied!", 'js');
             }
         } elseif (Yii::app()->request->getPost('downloadfile') && Yii::app()->request->getPost('downloadfile') === 'marked') {
             if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
                 // Now, zip all the files in the filelist
                 $zipfilename = "Responses_for_survey_{$iSurveyID}.zip";
                 $this->_zipFiles($iSurveyID, Yii::app()->request->getPost('markedresponses'), $zipfilename);
             }
         }
     } elseif (Yii::app()->request->getPost('downloadfile') && Yii::app()->request->getPost('downloadfile') != '' && Yii::app()->request->getPost('downloadfile') !== true) {
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
             // Now, zip all the files in the filelist
             $zipfilename = "Files_for_responses_" . Yii::app()->request->getPost('downloadfile') . ".zip";
             $this->_zipFiles($iSurveyID, Yii::app()->request->getPost('downloadfile'), $zipfilename);
         }
     } elseif (Yii::app()->request->getParam('downloadindividualfile') != '') {
         if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
             $iId = (int) Yii::app()->request->getParam('id');
             $downloadindividualfile = Yii::app()->request->getParam('downloadindividualfile');
             $fieldname = Yii::app()->request->getParam('fieldname');
             $oRow = SurveyDynamic::model($iSurveyID)->findByAttributes(array('id' => $iId));
             $phparray = json_decode_ls($oRow->{$fieldname});
             for ($i = 0; $i < count($phparray); $i++) {
                 if (rawurldecode($phparray[$i]['name']) == rawurldecode($downloadindividualfile)) {
                     $file = Yii::app()->getConfig('uploaddir') . "/surveys/" . $iSurveyID . "/files/" . $phparray[$i]['filename'];
                     if (file_exists($file)) {
                         @ob_clean();
                         header('Content-Description: File Transfer');
                         header('Content-Type: application/octet-stream');
                         header('Content-Disposition: attachment; filename="' . rawurldecode($phparray[$i]['name']) . '"');
                         header('Content-Transfer-Encoding: binary');
                         header('Expires: 0');
                         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                         header('Pragma: public');
                         header('Content-Length: ' . filesize($file));
                         readfile($file);
                         exit;
                     } else {
                         Yii::app()->session['flashmessage'] = gT("The requested file does not exist on the server.");
                     }
                     break;
                 }
             }
         }
     }
     /**
      * fnames is used as informational array
      * it containts
      *             $fnames[] = array(<dbfieldname>, <some strange title>, <questiontext>, <group_id>, <questiontype>);
      */
     if (Permission::model()->hasSurveyPermission($iSurveyID, 'responses', 'read')) {
         if (Yii::app()->request->getPost('sql')) {
             $aViewUrls[] = 'browseallfiltered_view';
         }
         //add token to top of list if survey is not private
         if ($aData['surveyinfo']['anonymized'] == "N" && tableExists('tokens_' . $iSurveyID)) {
             if (Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
                 $fnames[] = array("token", $clang->gT("Token ID"), 'code' => 'token');
                 $fnames[] = array("firstname", $clang->gT("First name"), 'code' => 'firstname');
                 // or token:firstname ?
                 $fnames[] = array("lastname", $clang->gT("Last name"), 'code' => 'lastname');
                 $fnames[] = array("email", $clang->gT("Email"), 'code' => 'email');
             }
         }
         $fnames[] = array("submitdate", $clang->gT("Completed"), $clang->gT("Completed"), "0", 'D');
         $fields = createFieldMap($iSurveyID, 'full', false, false, $aData['language']);
         foreach ($fields as $fielddetails) {
             if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate') {
                 continue;
             }
             $question = $fielddetails['question'];
             if ($fielddetails['type'] != "|") {
                 if ($fielddetails['fieldname'] == 'lastpage' || $fielddetails['fieldname'] == 'submitdate' || $fielddetails['fieldname'] == 'token') {
                     continue;
                 }
                 // no headers for time data
                 if ($fielddetails['type'] == 'interview_time') {
                     continue;
                 }
                 if ($fielddetails['type'] == 'page_time') {
                     continue;
                 }
                 if ($fielddetails['type'] == 'answer_time') {
                     continue;
                 }
                 $fnames[] = array($fielddetails['fieldname'], viewHelper::getFieldText($fielddetails), 'code' => viewHelper::getFieldCode($fielddetails, array('LEMcompat' => true)));
             } elseif ($fielddetails['aid'] !== 'filecount') {
                 $qidattributes = getQuestionAttributeValues($fielddetails['qid']);
                 for ($i = 0; $i < $qidattributes['max_num_of_files']; $i++) {
                     $filenum = sprintf($clang->gT("File %s"), $i + 1);
                     if ($qidattributes['show_title'] == 1) {
                         $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . $clang->gT('Title') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(title)', "type" => "|", "metadata" => "title", "index" => $i);
                     }
                     if ($qidattributes['show_comment'] == 1) {
                         $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . $clang->gT('Comment') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(comment)', "type" => "|", "metadata" => "comment", "index" => $i);
                     }
                     $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . $clang->gT('File name') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(name)', "type" => "|", "metadata" => "name", "index" => $i);
                     $fnames[] = array($fielddetails['fieldname'], "{$filenum} - {$question} (" . $clang->gT('File size') . ")", 'code' => viewHelper::getFieldCode($fielddetails) . '(size)', "type" => "|", "metadata" => "size", "index" => $i);
                     //$fnames[] = array($fielddetails['fieldname'], "File ".($i+1)." - ".$fielddetails['question']."(extension)", "type"=>"|", "metadata"=>"ext",     "index"=>$i);
                 }
             } else {
                 $fnames[] = array($fielddetails['fieldname'], $clang->gT("File count"), 'code' => viewHelper::getFieldCode($fielddetails));
             }
         }
         $fncount = count($fnames);
         $start = (int) Yii::app()->request->getParam('start', 0);
         $limit = (int) Yii::app()->request->getParam('limit', 50);
         $order = Yii::app()->request->getParam('order', 'asc');
         if (!$limit) {
             $limit = 50;
         }
         $oCriteria = new CDbCriteria();
         //Create the query
         if ($aData['surveyinfo']['anonymized'] == "N" && tableExists("{{tokens_{$iSurveyID}}}") && Permission::model()->hasSurveyPermission($iSurveyID, 'tokens', 'read')) {
             $oCriteria = SurveyDynamic::model($iSurveyID)->addTokenCriteria($oCriteria);
         }
         if (incompleteAnsFilterState() == "incomplete") {
             $oCriteria->addCondition("submitdate IS NULL");
         } elseif (incompleteAnsFilterState() == "complete") {
             $oCriteria->addCondition("submitdate IS NOT NULL");
         }
         $dtcount = SurveyDynamic::model($iSurveyID)->count($oCriteria);
         // or die("Couldn't get response data<br />");
         if ($limit > $dtcount) {
             $limit = $dtcount;
         }
         //NOW LETS SHOW THE DATA
         if (Yii::app()->request->getPost('sql') && stripcslashes(Yii::app()->request->getPost('sql')) !== "" && Yii::app()->request->getPost('sql') != "NULL") {
             $oCriteria->addCondition(stripcslashes(Yii::app()->request->getPost('sql')));
         }
         if (!is_null($tokenRequest)) {
             $oCriteria->addCondition('t.token = ' . Yii::app()->db->quoteValue($tokenRequest));
         }
         $oCriteria->order = 'id ' . ($order == 'desc' ? 'desc' : 'asc');
         $oCriteria->offset = $start;
         $oCriteria->limit = $limit;
         $dtresult = SurveyDynamic::model($iSurveyID)->findAllAsArray($oCriteria);
         $dtcount2 = count($dtresult);
         $cells = $fncount + 1;
         // Fix start if order is desc, only if actual start is 0
         if ($order == 'desc' && $start == 0) {
             $start = $dtcount - count($dtresult);
         }
         //CONTROL MENUBAR
         $last = $start - $limit;
         $next = $start + $limit;
         $end = $dtcount - $limit;
         if ($end < 0) {
             $end = 0;
         }
         if ($last < 0) {
             $last = 0;
         }
         if ($next >= $dtcount) {
             $next = $dtcount - $limit;
         }
         if ($end < 0) {
             $end = 0;
         }
         $aData['dtcount2'] = $dtcount2;
         $aData['sCompletionStateValue'] = incompleteAnsFilterState();
         $aData['start'] = $start;
         $aData['limit'] = $limit;
         $aData['last'] = $last;
         $aData['next'] = $next;
         $aData['end'] = $end;
         $aData['fncount'] = $fncount;
         $aData['fnames'] = $fnames;
         $aData['bHasFileUploadQuestion'] = hasFileUploadQuestion($iSurveyID);
         $aViewUrls[] = 'browseallheader_view';
         $bgcc = 'even';
         foreach ($dtresult as $dtrow) {
             if ($bgcc == "even") {
                 $bgcc = "odd";
             } else {
                 $bgcc = "even";
             }
             $aData['dtrow'] = $dtrow;
             $aData['bgcc'] = $bgcc;
             $aData['oBrowseLanguage'] = $oBrowseLanguage;
             $aViewUrls['browseallrow_view'][] = $aData;
         }
         $aViewUrls[] = 'browseallfooter_view';
         $this->_renderWrappedTemplate('', $aViewUrls, $aData);
     } else {
         $clang = $this->getController()->lang;
         $aData['surveyid'] = $iSurveyID;
         App()->getClientScript()->registerPackage('jquery-superfish');
         $message['title'] = $clang->gT('Access denied!');
         $message['message'] = $clang->gT('You do not have sufficient rights to access this page.');
         $message['class'] = "error";
         $this->_renderWrappedTemplate('survey', array("message" => $message), $aData);
     }
 }
Esempio n. 29
0
 /**
  * dataentry::view()
  * view a dataentry
  * @param mixed $surveyid
  * @param mixed $lang
  * @return
  */
 public function view($surveyid, $lang = NULL)
 {
     $surveyid = sanitize_int($surveyid);
     $lang = isset($_GET['lang']) ? $_GET['lang'] : NULL;
     if (isset($lang)) {
         $lang = sanitize_languagecode($lang);
     }
     $aViewUrls = array();
     if (hasSurveyPermission($surveyid, 'responses', 'read')) {
         $clang = Yii::app()->lang;
         $sDataEntryLanguage = Survey::model()->findByPk($surveyid)->language;
         $surveyinfo = getSurveyInfo($surveyid);
         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
         $baselang = Survey::model()->findByPk($surveyid)->language;
         array_unshift($slangs, $baselang);
         if (is_null($lang) || !in_array($lang, $slangs)) {
             $sDataEntryLanguage = $baselang;
             $blang = $clang;
         } else {
             Yii::app()->loadLibrary('Limesurvey_lang', array($lang));
             $blang = new Limesurvey_lang($lang);
             $sDataEntryLanguage = $lang;
         }
         $langlistbox = languageDropdown($surveyid, $sDataEntryLanguage);
         $thissurvey = getSurveyInfo($surveyid);
         //This is the default, presenting a blank dataentry form
         LimeExpressionManager::StartSurvey($surveyid, 'survey', NULL, false, LEM_PRETTY_PRINT_ALL_SYNTAX);
         $moveResult = LimeExpressionManager::NavigateForwards();
         $aData['thissurvey'] = $thissurvey;
         $aData['langlistbox'] = $langlistbox;
         $aData['surveyid'] = $surveyid;
         $aData['blang'] = $blang;
         $aData['site_url'] = Yii::app()->homeUrl;
         LimeExpressionManager::StartProcessingPage(true, Yii::app()->baseUrl);
         // means that all variables are on the same page
         $aViewUrls[] = 'caption_view';
         Yii::app()->loadHelper('database');
         // SURVEY NAME AND DESCRIPTION TO GO HERE
         $degquery = "SELECT * FROM {{groups}} WHERE sid={$surveyid} AND language='{$sDataEntryLanguage}' ORDER BY {{groups}}.group_order";
         $degresult = dbExecuteAssoc($degquery);
         // GROUP NAME
         $aDataentryoutput = '';
         foreach ($degresult->readAll() as $degrow) {
             LimeExpressionManager::StartProcessingGroup($degrow['gid'], $thissurvey['anonymized'] != "N", $surveyid);
             $deqquery = "SELECT * FROM {{questions}} WHERE sid={$surveyid} AND parent_qid=0 AND gid={$degrow['gid']} AND language='{$sDataEntryLanguage}'";
             $deqrows = (array) dbExecuteAssoc($deqquery)->readAll();
             $aDataentryoutput .= "\t<tr>\n" . "<td colspan='3' align='center'><strong>" . flattenText($degrow['group_name'], true) . "</strong></td>\n" . "\t</tr>\n";
             $gid = $degrow['gid'];
             $aDataentryoutput .= "\t<tr class='data-entry-separator'><td colspan='3'></td></tr>\n";
             // Perform a case insensitive natural sort on group name then question title of a multidimensional array
             usort($deqrows, 'groupOrderThenQuestionOrder');
             $bgc = 'odd';
             foreach ($deqrows as $deqrow) {
                 $qidattributes = getQuestionAttributeValues($deqrow['qid'], $deqrow['type']);
                 $cdata['qidattributes'] = $qidattributes;
                 $hidden = isset($qidattributes['hidden']) ? $qidattributes['hidden'] : 0;
                 // TODO - can questions be hidden?  Are JavaScript variables names used?  Consistently with everywhere else?
                 //                    LimeExpressionManager::ProcessRelevance($qidattributes['relevance'],$deqrow['qid'],NULL,$deqrow['type'],$hidden);
                 // TMSW Conditions->Relevance:  Show relevance equation instead of conditions here - better yet, have data entry use survey-at-a-time but with different view
                 $qinfo = LimeExpressionManager::GetQuestionStatus($deqrow['qid']);
                 $relevance = trim($qinfo['info']['relevance']);
                 $explanation = trim($qinfo['relEqn']);
                 $validation = trim($qinfo['prettyValidTip']);
                 $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                 $array_filter_help = flattenText($this->_array_filter_help($qidattributes, $sDataEntryLanguage, $surveyid));
                 if ($relevance != '' && $relevance != '1' || $validation != '' || $array_filter_help != '') {
                     $showme = '';
                     if ($bgc == "even") {
                         $bgc = "odd";
                     } else {
                         $bgc = "even";
                     }
                     //Do no alternate on explanation row
                     if ($relevance != '' && $relevance != '1') {
                         $showme = "[" . $blang->gT("Only answer this if the following conditions are met:") . "]<br />{$explanation}\n";
                     }
                     if ($showme != '' && $validation != '') {
                         $showme .= '<br/>';
                     }
                     if ($validation != '') {
                         $showme .= "[" . $blang->gT("The answer(s) must meet these validation criteria:") . "]<br />{$validation}\n";
                     }
                     if ($showme != '' && $array_filter_help != '') {
                         $showme .= '<br/>';
                     }
                     if ($array_filter_help != '') {
                         $showme .= "[" . $blang->gT("The answer(s) must meet these array_filter criteria:") . "]<br />{$array_filter_help}\n";
                     }
                     $cdata['explanation'] = "<tr class ='data-entry-explanation'><td class='data-entry-small-text' colspan='3' align='left'>{$showme}</td></tr>\n";
                 }
                 //END OF GETTING CONDITIONS
                 //Alternate bgcolor for different groups
                 if (!isset($bgc)) {
                     $bgc = "even";
                 }
                 if ($bgc == "even") {
                     $bgc = "odd";
                 } else {
                     $bgc = "even";
                 }
                 $qid = $deqrow['qid'];
                 $fieldname = "{$surveyid}" . "X" . "{$gid}" . "X" . "{$qid}";
                 $cdata['bgc'] = $bgc;
                 $cdata['fieldname'] = $fieldname;
                 $cdata['deqrow'] = $deqrow;
                 $cdata['clang'] = $clang;
                 //DIFFERENT TYPES OF DATA FIELD HERE
                 $cdata['blang'] = $blang;
                 $cdata['thissurvey'] = $thissurvey;
                 if ($deqrow['help']) {
                     $hh = addcslashes($deqrow['help'], "..'\"");
                     //Escape ASCII decimal 0-32 plus single and double quotes to make JavaScript happy.
                     $hh = htmlspecialchars($hh, ENT_QUOTES);
                     //Change & " ' < > to HTML entities to make HTML happy.
                     $cdata['hh'] = $hh;
                     //$aDataentryoutput .= "\t<img src='$imageurl/help.gif' alt='".$blang->gT("Help about this question")."' align='right' onclick=\"javascript:alert('Question {$deqrow['title']} Help: $hh')\" />\n";
                 }
                 switch ($deqrow['type']) {
                     case "Q":
                         //MULTIPLE SHORT TEXT
                     //MULTIPLE SHORT TEXT
                     case "K":
                         $deaquery = "SELECT question,title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         break;
                     case "1":
                         // multi scale^
                         $deaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$baselang}' ORDER BY question_order";
                         $dearesult = dbExecuteAssoc($deaquery);
                         $cdata['dearesult'] = $dearesult->readAll();
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$baselang}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />" . $oquery);
                         foreach ($oresult->readAll() as $orow) {
                             $cdata['fother'] = $orow['other'];
                         }
                         break;
                     case "L":
                         //LIST drop-down/radio-button list
                     //LIST drop-down/radio-button list
                     case "!":
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         if ($deqrow['type'] == '!' && trim($qidattributes['category_separator']) != '') {
                             $optCategorySeparator = $qidattributes['category_separator'];
                         } else {
                             unset($optCategorySeparator);
                         }
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname'>\n";
                         $aDatatemp = '';
                         if (!isset($optCategorySeparator)) {
                             foreach ($dearesult->readAll() as $dearow) {
                                 $aDatatemp .= "<option value='{$dearow['code']}'";
                                 //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$dearow['answer']}</option>\n";
                             }
                         } else {
                             $defaultopts = array();
                             $optgroups = array();
                             foreach ($dearesult->readAll() as $dearow) {
                                 list($categorytext, $answertext) = explode($optCategorySeparator, $dearow['answer']);
                                 if ($categorytext == '') {
                                     $defaultopts[] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 } else {
                                     $optgroups[$categorytext][] = array('code' => $dearow['code'], 'answer' => $answertext, 'default_value' => $dearow['assessment_value']);
                                 }
                             }
                             foreach ($optgroups as $categoryname => $optionlistarray) {
                                 $aDatatemp .= "<optgroup class=\"dropdowncategory\" label=\"" . $categoryname . "\">\n";
                                 foreach ($optionlistarray as $optionarray) {
                                     $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                     //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                     $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                                 }
                                 $aDatatemp .= "</optgroup>\n";
                             }
                             foreach ($defaultopts as $optionarray) {
                                 $aDatatemp .= "\t<option value='{$optionarray['code']}'";
                                 //if ($optionarray['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                                 $aDatatemp .= ">{$optionarray['answer']}</option>\n";
                             }
                         }
                         $oquery = "SELECT other FROM {{questions}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}'";
                         $oresult = dbExecuteAssoc($oquery) or safeDie("Couldn't get other for list question<br />");
                         foreach ($oresult->readAll() as $orow) {
                             $fother = $orow['other'];
                         }
                         $cdata['fother'] = $fother;
                         $cdata['defexists'] = $defexists;
                         $cdata['datatemp'] = $aDatatemp;
                         break;
                     case "O":
                         //LIST WITH COMMENT drop-down/radio-button list + textarea
                         $defexists = "";
                         $deaquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $dearesult = dbExecuteAssoc($deaquery);
                         //$aDataentryoutput .= "\t<select name='$fieldname'>\n";
                         $aDatatemp = '';
                         foreach ($dearesult->readAll() as $dearow) {
                             $aDatatemp .= "<option value='{$dearow['code']}'";
                             //if ($dearow['default_value'] == "Y") {$aDatatemp .= " selected='selected'"; $defexists = "Y";}
                             $aDatatemp .= ">{$dearow['answer']}</option>\n";
                         }
                         $cdata['datatemp'] = $aDatatemp;
                         $cdata['defexists'] = $defexists;
                         break;
                     case "R":
                         //RANKING TYPE QUESTION
                         $thisqid = $deqrow['qid'];
                         $ansquery = "SELECT * FROM {{answers}} WHERE qid={$thisqid} AND language='{$sDataEntryLanguage}' ORDER BY sortorder, answer";
                         $ansresult = dbExecuteAssoc($ansquery);
                         $ansresult = $ansresult->readAll();
                         $anscount = count($ansresult);
                         $cdata['thisqid'] = $thisqid;
                         $cdata['anscount'] = $anscount;
                         foreach ($ansresult as $ansrow) {
                             $answers[] = array($ansrow['code'], $ansrow['answer']);
                         }
                         for ($i = 1; $i <= $anscount; $i++) {
                             if (isset($fname)) {
                                 $myfname = $fname . $i;
                             }
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $existing++;
                             }
                         }
                         for ($i = 1; $i <= $anscount; $i++) {
                             if (isset($fname)) {
                                 $myfname = $fname . $i;
                             }
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 foreach ($answers as $ans) {
                                     if ($ans[0] == Yii::app()->session[$myfname]) {
                                         $thiscode = $ans[0];
                                         $thistext = $ans[1];
                                     }
                                 }
                             }
                             if (!isset($ranklist)) {
                                 $ranklist = "";
                             }
                             $ranklist .= "&nbsp;<font color='#000080'>{$i}:&nbsp;<input class='ranklist' type='text' name='RANK{$i}' id='RANK_{$thisqid}{$i}'";
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $ranklist .= " value='";
                                 $ranklist .= $thistext;
                                 $ranklist .= "'";
                             }
                             $ranklist .= " onFocus=\"this.blur()\"  />\n";
                             $ranklist .= "<input type='hidden' id='d{$fieldname}{$i}' name='{$fieldname}{$i}' value='";
                             $chosen[] = "";
                             //create array
                             if (isset($myfname) && Yii::app()->session[$myfname]) {
                                 $ranklist .= $thiscode;
                                 $chosen[] = array($thiscode, $thistext);
                             }
                             $ranklist .= "' /></font>\n";
                             $ranklist .= "<img src='" . Yii::app()->getConfig('imageurl') . "/cut.gif' alt='" . $blang->gT("Remove this item") . "' title='" . $blang->gT("Remove this item") . "' ";
                             if (!isset($existing) || $i != $existing) {
                                 $ranklist .= "style='display:none'";
                             }
                             $mfn = $fieldname . $i;
                             $ranklist .= " id='cut_{$thisqid}{$i}' onclick=\"deletethis_{$thisqid}(document.addsurvey.RANK_{$thisqid}{$i}.value, document.addsurvey.d{$fieldname}{$i}.value, document.addsurvey.RANK_{$thisqid}{$i}.id, this.id)\" /><br />\n\n";
                         }
                         if (!isset($choicelist)) {
                             $choicelist = "";
                         }
                         $choicelist .= "<select size='{$anscount}' class='choicelist' name='CHOICES' id='CHOICES_{$thisqid}' onclick=\"rankthis_{$thisqid}(this.options[this.selectedIndex].value, this.options[this.selectedIndex].text)\" >\n";
                         foreach ($answers as $ans) {
                             if (!in_array($ans, $chosen)) {
                                 $choicelist .= "\t<option value='{$ans[0]}'>{$ans[1]}</option>\n";
                             }
                         }
                         $choicelist .= "</select>\n";
                         $cdata['choicelist'] = $choicelist;
                         $cdata['ranklist'] = $ranklist;
                         if (isset($multifields)) {
                             $cdata['multifields'] = $multifields;
                         }
                         $choicelist = "";
                         $ranklist = "";
                         unset($answers);
                         break;
                     case "M":
                         //Multiple choice checkbox (Quite tricky really!)
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         if (trim($qidattributes['display_columns']) != '') {
                             $dcols = $qidattributes['display_columns'];
                         } else {
                             $dcols = 0;
                         }
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['dcols'] = $dcols;
                         $cdata['meacount'] = $meacount;
                         $cdata['mearesult'] = $mearesult->readAll();
                         $meacount = count($cdata['mearesult']);
                         break;
                     case "I":
                         //Language Switch
                         $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
                         $sbaselang = Survey::model()->findByPk($surveyid)->language;
                         array_unshift($slangs, $sbaselang);
                         $cdata['slangs'] = $slangs;
                         break;
                     case "P":
                         //Multiple choice with comments checkbox + text
                         //$aDataentryoutput .= "<table border='0'>\n";
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order, question";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "|":
                         //                            $qidattributes = getQuestionAttributeValues($deqrow['qid']);
                         $cdata['qidattributes'] = $qidattributes;
                         $maxfiles = $qidattributes['max_num_of_files'];
                         $cdata['maxfiles'] = $maxfiles;
                         break;
                     case "A":
                         //ARRAY (5 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "B":
                         //ARRAY (10 POINT CHOICE) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                     case "C":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery);
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "E":
                         //ARRAY (YES/UNCERTAIN/NO) radio-buttons
                         $meaquery = "SELECT title, question FROM {{questions}} WHERE parent_qid={$deqrow['qid']} AND language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ":":
                         //ARRAY (Multi Flexi)
                         //                            $qidattributes=getQuestionAttributeValues($deqrow['qid']);
                         $minvalue = 1;
                         $maxvalue = 10;
                         if (trim($qidattributes['multiflexible_max']) != '' && trim($qidattributes['multiflexible_min']) == '') {
                             $maxvalue = $qidattributes['multiflexible_max'];
                             $minvalue = 1;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) == '') {
                             $minvalue = $qidattributes['multiflexible_min'];
                             $maxvalue = $qidattributes['multiflexible_min'] + 10;
                         }
                         if (trim($qidattributes['multiflexible_min']) != '' && trim($qidattributes['multiflexible_max']) != '') {
                             if ($qidattributes['multiflexible_min'] < $qidattributes['multiflexible_max']) {
                                 $minvalue = $qidattributes['multiflexible_min'];
                                 $maxvalue = $qidattributes['multiflexible_max'];
                             }
                         }
                         if (trim($qidattributes['multiflexible_step']) != '') {
                             $stepvalue = $qidattributes['multiflexible_step'];
                         } else {
                             $stepvalue = 1;
                         }
                         if ($qidattributes['multiflexible_checkbox'] != 0) {
                             $minvalue = 0;
                             $maxvalue = 1;
                             $stepvalue = 1;
                         }
                         $cdata['minvalue'] = $minvalue;
                         $cdata['maxvalue'] = $maxvalue;
                         $cdata['stepvalue'] = $stepvalue;
                         $lquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=1 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT question, title FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and scale_id=0 and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case ";":
                         //ARRAY (Multi Flexi)
                         $lquery = "SELECT * FROM {{questions}} WHERE scale_id=1 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $lresult = dbExecuteAssoc($lquery) or die("Couldn't get labels, Type \":\"<br />{$lquery}<br />");
                         $cdata['lresult'] = $lresult->readAll();
                         $meaquery = "SELECT * FROM {{questions}} WHERE scale_id=0 and parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or die("Couldn't get answers, Type \":\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         break;
                     case "F":
                         //ARRAY (Flexible Labels)
                     //ARRAY (Flexible Labels)
                     case "H":
                         $meaquery = "SELECT * FROM {{questions}} WHERE parent_qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY question_order";
                         $mearesult = dbExecuteAssoc($meaquery) or safeDie("Couldn't get answers, Type \"E\"<br />{$meaquery}<br />");
                         $cdata['mearesult'] = $mearesult->readAll();
                         $fquery = "SELECT * FROM {{answers}} WHERE qid={$deqrow['qid']} and language='{$sDataEntryLanguage}' ORDER BY sortorder, code";
                         $fresult = dbExecuteAssoc($fquery);
                         $cdata['fresult'] = $fresult->readAll();
                         break;
                 }
                 $cdata['sDataEntryLanguage'] = $sDataEntryLanguage;
                 $viewdata = $this->getController()->render("/admin/dataentry/content_view", $cdata, TRUE);
                 $viewdata_em = LimeExpressionManager::ProcessString($viewdata, $deqrow['qid'], NULL, false, 1, 1);
                 $aDataentryoutput .= $viewdata_em;
             }
             LimeExpressionManager::FinishProcessingGroup();
         }
         LimeExpressionManager::FinishProcessingPage();
         $aDataentryoutput .= LimeExpressionManager::GetRelevanceAndTailoringJavaScript();
         $aViewUrls['output'] = $aDataentryoutput;
         $aData['thissurvey'] = $thissurvey;
         $aData['surveyid'] = $surveyid;
         $aData['sDataEntryLanguage'] = $sDataEntryLanguage;
         if ($thissurvey['active'] == "Y" && $thissurvey['allowsave'] == "Y") {
             $slangs = Survey::model()->findByPk($surveyid)->additionalLanguages;
             $sbaselang = Survey::model()->findByPk($surveyid)->language;
             array_unshift($slangs, $sbaselang);
             $aData['slangs'] = $slangs;
             $aData['baselang'] = $baselang;
         }
         $aViewUrls[] = 'active_html_view';
         $this->_renderWrappedTemplate('dataentry', $aViewUrls, $aData);
     }
 }
    function run($actionID)
    {
        $surveyid = $_SESSION['LEMsid'];
        if (isset($_SESSION['survey_' . $surveyid]['s_lang'])) {
            $sLanguage = $_SESSION['survey_' . $surveyid]['s_lang'];
        } else {
            $sLanguage = '';
        }
        $clang = SetSurveyLanguage($surveyid, $sLanguage);
        $uploaddir = Yii::app()->getConfig("uploaddir");
        $tempdir = Yii::app()->getConfig("tempdir");
        Yii::app()->loadHelper("database");
        $param = $_REQUEST;
        if (isset($param['filegetcontents'])) {
            $sFileName = $param['filegetcontents'];
            if (substr($sFileName, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFileName, 0, 3) == 'fu_') {
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            }
            header('Content-Type: ' . CFileHelper::getMimeType($sFileDir . $sFileName));
            readfile($sFileDir . $sFileName);
            exit;
        } elseif (isset($param['delete'])) {
            $sFieldname = $param['fieldname'];
            $sFilename = sanitize_filename($param['filename']);
            $sOriginalFileName = sanitize_filename($param['name']);
            if (substr($sFilename, 0, 6) == 'futmp_') {
                $sFileDir = $tempdir . '/upload/';
            } elseif (substr($sFilename, 0, 3) == 'fu_') {
                $sFileDir = "{$uploaddir}/surveys/{$surveyid}/files/";
            } else {
                die('Invalid filename');
            }
            if (isset($_SESSION[$sFieldname])) {
                $sJSON = $_SESSION[$sFieldname];
                $aFiles = json_decode(stripslashes($sJSON), true);
                if (substr($sFilename, 0, 3) == 'fu_') {
                    $iFileIndex = 0;
                    $found = false;
                    foreach ($aFiles as $aFile) {
                        if ($aFile['filename'] == $sFilename) {
                            $found = true;
                            break;
                        }
                        $iFileIndex++;
                    }
                    if ($found == true) {
                        unset($aFiles[$iFileIndex]);
                    }
                    $_SESSION[$sFieldname] = ls_json_encode($aFiles);
                }
            }
            //var_dump($sFileDir.$sFilename);
            if (@unlink($sFileDir . $sFilename)) {
                echo sprintf($clang->gT('File %s deleted'), $sOriginalFileName);
            } else {
                echo $clang->gT('Oops, There was an error deleting the file');
            }
            exit;
        }
        if (isset($param['mode']) && $param['mode'] == "upload") {
            $clang = Yii::app()->lang;
            $sTempUploadDir = $tempdir . '/upload/';
            // Check if exists and is writable
            if (!file_exists($sTempUploadDir)) {
                // Try to create
                mkdir($sTempUploadDir);
            }
            $filename = $_FILES['uploadfile']['name'];
            $size = 0.001 * $_FILES['uploadfile']['size'];
            $valid_extensions = strtolower($_POST['valid_extensions']);
            $maxfilesize = (int) $_POST['max_filesize'];
            $preview = $_POST['preview'];
            $fieldname = $_POST['fieldname'];
            $aFieldMap = createFieldMap($surveyid, 'short', false, false, $_SESSION['survey_' . $surveyid]['s_lang']);
            if (!isset($aFieldMap[$fieldname])) {
                die;
            }
            $aAttributes = getQuestionAttributeValues($aFieldMap[$fieldname]['qid'], $aFieldMap[$fieldname]['type']);
            $valid_extensions_array = explode(",", $aAttributes['allowed_filetypes']);
            $valid_extensions_array = array_map('trim', $valid_extensions_array);
            $pathinfo = pathinfo($_FILES['uploadfile']['name']);
            $ext = $pathinfo['extension'];
            $randfilename = 'futmp_' . randomChars(15) . '_' . $pathinfo['extension'];
            $randfileloc = $sTempUploadDir . $randfilename;
            // check to see that this file type is allowed
            // it is also  checked at the client side, but jst double checking
            if (!in_array(strtolower($ext), $valid_extensions_array)) {
                $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file extension (%s) is not allowed!"), $ext));
                echo ls_json_encode($return);
                exit;
            }
            // If this is just a preview, don't save the file
            if ($preview) {
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                    echo ls_json_encode($return);
                    exit;
                } else {
                    if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                        $return = array("success" => true, "file_index" => $filecount, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => $clang->gT("The file has been successfuly uploaded."));
                        echo ls_json_encode($return);
                        // TODO : unlink this file since this is just a preview
                        // unlink($randfileloc);
                        exit;
                    }
                }
            } else {
                // if everything went fine and the file was uploaded successfuly,
                // send the file related info back to the client
                $iFileUploadTotalSpaceMB = Yii::app()->getConfig("iFileUploadTotalSpaceMB");
                if ($size > $maxfilesize) {
                    $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file is too large. Only files up to %s KB are allowed.", 'unescaped'), $maxfilesize));
                    echo ls_json_encode($return);
                    exit;
                } elseif ($iFileUploadTotalSpaceMB > 0 && calculateTotalFileUploadUsage() + $size / 1024 / 1024 > $iFileUploadTotalSpaceMB) {
                    $return = array("success" => false, "msg" => $clang->gT("We are sorry but there was a system error and your file was not saved. An email has been dispatched to notify the survey administrator.", 'unescaped'));
                    echo ls_json_encode($return);
                    exit;
                } elseif (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $randfileloc)) {
                    $return = array("success" => true, "size" => $size, "name" => rawurlencode(basename($filename)), "ext" => $ext, "filename" => $randfilename, "msg" => $clang->gT("The file has been successfuly uploaded."));
                    echo ls_json_encode($return);
                    exit;
                } else {
                    // check for upload error
                    if ($_FILES['uploadfile']['error'] > 2) {
                        $return = array("success" => false, "msg" => $clang->gT("Sorry, there was an error uploading your file"));
                        echo ls_json_encode($return);
                        exit;
                    } else {
                        if ($_FILES['uploadfile']['error'] == 1 || $_FILES['uploadfile']['error'] == 2 || $size > $maxfilesize) {
                            $return = array("success" => false, "msg" => sprintf($clang->gT("Sorry, this file is too large. Only files upto %s KB are allowed."), $maxfilesize));
                            echo ls_json_encode($return);
                            exit;
                        } else {
                            $return = array("success" => false, "msg" => $clang->gT("Unknown error"));
                            echo ls_json_encode($return);
                            exit;
                        }
                    }
                }
            }
            return;
        }
        $meta = '<script type="text/javascript" src="' . Yii::app()->getConfig("generalscripts") . 'jquery/jquery.js"></script>';
        $meta .= '<script type="text/javascript">
		    var uploadurl = "' . $this->createUrl('/uploader/index/mode/upload/') . '";
            var imageurl = "' . Yii::app()->getConfig('imageurl') . '/";
		    var surveyid = "' . $surveyid . '";
		    var fieldname = "' . $param['fieldname'] . '";
		    var questgrppreview  = ' . $param['preview'] . ';
		</script>';
        $meta .= '<script type="text/javascript" src="' . Yii::app()->getConfig("generalscripts") . '/ajaxupload.js"></script>
		<script type="text/javascript" src="' . Yii::app()->getConfig("generalscripts") . '/uploader.js"></script>
		<link type="text/css" href="' . Yii::app()->getConfig("publicstyleurl") . 'uploader.css" rel="stylesheet" />';
        $clang = Yii::app()->lang;
        $header = getHeader($meta);
        echo $header;
        echo "<script type='text/javascript'>\n\t\t        var translt = {\n\t\t             titleFld: '" . $clang->gT('Title', 'js') . "',\n\t\t             commentFld: '" . $clang->gT('Comment', 'js') . "',\n\t\t             errorNoMoreFiles: '" . $clang->gT('Sorry, no more files can be uploaded!', 'js') . "',\n\t\t             errorOnlyAllowed: '" . $clang->gT('Sorry, only %s files can be uploaded for this question!', 'js') . "',\n\t\t             uploading: '" . $clang->gT('Uploading', 'js') . "',\n\t\t             selectfile: '" . $clang->gT('Select file', 'js') . "',\n\t\t             errorNeedMore: '" . $clang->gT('Please upload %s more file(s).', 'js') . "',\n\t\t             errorMoreAllowed: '" . $clang->gT('If you wish, you may upload %s more file(s); else you may return back to survey.', 'js') . "',\n\t\t             errorMaxReached: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n\t\t             errorTooMuch: '" . $clang->gT('The maximum number of files has been uploaded. You may return back to survey.', 'js') . "',\n\t\t             errorNeedMoreConfirm: '" . $clang->gT("You need to upload %s more files for this question.\nAre you sure you want to exit?", 'js') . "'\n\t\t            };\n\t\t    </script>\n";
        $fn = $param['fieldname'];
        $qid = $param['qid'];
        $minfiles = sanitize_int($param['minfiles']);
        $maxfiles = sanitize_int($param['maxfiles']);
        $qidattributes = getQuestionAttributeValues($qid);
        $body = '
		        <div id="notice"></div>
		        <input type="hidden" id="ia"                value="' . $fn . '" />
                <input type="hidden" id="' . $fn . '_minfiles"          value="' . $minfiles . '" />
                <input type="hidden" id="' . $fn . '_maxfiles"          value="' . $maxfiles . '" />
		        <input type="hidden" id="' . $fn . '_maxfilesize"       value="' . $qidattributes['max_filesize'] . '" />
		        <input type="hidden" id="' . $fn . '_allowed_filetypes" value="' . $qidattributes['allowed_filetypes'] . '" />
		        <input type="hidden" id="preview"                   value="' . Yii::app()->session['preview'] . '" />
		        <input type="hidden" id="' . $fn . '_show_comment"      value="' . $qidattributes['show_comment'] . '" />
		        <input type="hidden" id="' . $fn . '_show_title"        value="' . $qidattributes['show_title'] . '" />
		        <input type="hidden" id="' . $fn . '_licount"           value="0" />
		        <input type="hidden" id="' . $fn . '_filecount"         value="0" />

		        <!-- The upload button -->
		        <div align="center" class="upload-div">
		            <button id="button1" class="upload-button" type="button" >' . $clang->gT("Select file") . '</button>
		        </div>

		        <p class="uploadmsg">' . sprintf($clang->gT("You can upload %s under %s KB each.", 'js'), $qidattributes['allowed_filetypes'], $qidattributes['max_filesize']) . '</p>
		        <div class="uploadstatus" id="uploadstatus"></div>

		        <!-- The list of uploaded files -->
		        <ul id="' . $fn . '_listfiles"></ul>

		    </body>
		</html>';
        echo $body;
    }