function mkresavg($total, $precision, $showTotals, $length)
 {
     global $CFG;
     $stravg = '<div style="text-align:center">' . get_string('averagerank', 'questionnaire') . '</div>';
     $strstd = '<div style="text-align:center">' . get_string('stdrank', 'questionnaire') . '</div>';
     $isna = $this->precise == 1;
     $isnahead = '';
     $osgood = false;
     if ($precision == 3) {
         // Osgood's semantic differential
         $osgood = true;
     }
     if ($isna) {
         $isnahead = get_string('notapplicable', 'questionnaire') . '<br />(#)';
     }
     $table = new Object();
     $table->align = array('', 'left', 'right', 'center', 'center');
     if ($isna) {
         $table->head = array('', $stravg, '', $isnahead);
     } else {
         if ($osgood) {
             $table->head = array('', $stravg, '', $strstd, '');
         } else {
             $table->head = array('', $stravg, '', $strstd);
         }
     }
     if (!$osgood) {
         $rightcolwidth = '5%';
     } else {
         $rightcolwidth = '25%';
     }
     $table->size = array('*', '40%', $rightcolwidth, '5%', '*');
     $image_url = $CFG->wwwroot . '/mod/questionnaire/images/';
     $currhbar = $this->theme_bars_url();
     if (!$length) {
         $length = 5;
     }
     $nacol = 0;
     $width = 100 / $length;
     $n = array();
     $nameddegrees = 0;
     foreach ($this->choices as $choice) {
         $content = $choice->content;
         if (ereg("^[0-9]{1,3}", $content, $ndd)) {
             $n[$nameddegrees] = substr($content, strlen($ndd[0]) + 1);
             $nameddegrees++;
         }
     }
     $align = 'center';
     for ($j = 0; $j < $this->length; $j++) {
         if (isset($n[$j])) {
             $str = $n[$j];
         } else {
             $str = $j + 1;
         }
     }
     $out = '<table style="width:100%" cellpadding="2" cellspacing="0" border="1"><tr>';
     for ($i = 0; $i <= $length - 1; $i++) {
         if (isset($n[$i])) {
             $str = $n[$i];
         } else {
             $str = $i + 1;
         }
         $out .= '<td align = "center" style="width:' . $width . '%" >' . $str . '</td>';
     }
     $out .= '</tr></table>';
     $table->data[] = array('', $out, '');
     if (!empty($this->counts) && is_array($this->counts)) {
         while (list($content) = each($this->counts)) {
             // eliminate potential named degrees on Likert scale
             if (!ereg("^[0-9]{1,3}", $content)) {
                 if (isset($this->counts[$content]->avg)) {
                     $avg = $this->counts[$content]->avg;
                 } else {
                     $avg = '';
                 }
                 $nbna = $this->counts[$content]->nbna;
                 if ($avg) {
                     $out = '';
                     if (($j = $avg * $width) > 0) {
                         $interval = 50 / $length;
                         $out .= sprintf('<img alt="" src="' . $image_url . $currhbar . 'rhbar.gif" height="0" width="%d%%" style="visibility:hidden" />', $j - $interval - 0.3);
                     }
                     $out .= '<img alt="" src="' . $image_url . $currhbar . 'rhbar.gif" height="12" width="6" />';
                 } else {
                     $out = '';
                 }
                 if ($osgood) {
                     list($content, $contentright) = split('[|]', $content);
                 } else {
                     $contents = choice_values($content);
                     if ($contents->modname) {
                         $content = $contents->text;
                     }
                 }
                 if (!$isna) {
                     if ($osgood) {
                         $table->data[] = array('<div align="right">' . $content . '</div>', $out, sprintf('%.1f', $avg), '<div align="left"><strong>' . $contentright . '</strong></div>', '<div>' . sprintf('%.2f', $this->counts[$content]->std) . '</div>');
                     } else {
                         $table->data[] = array($content, $out, sprintf('%.1f', $avg), '<div>' . sprintf('%.2f', $this->counts[$content]->std) . '</div>');
                     }
                 } else {
                     if ($avg) {
                         $avg = sprintf('%.1f', $avg);
                     }
                     $table->data[] = array($content, $out, $avg, $nbna);
                 }
             }
             // end if named degrees
         }
         // end while
     } else {
         $table->data[] = array('', get_string('noresponsedata', 'questionnaire'));
     }
     print_table($table);
 }
 function generate_csv($rid = '', $userid = '')
 {
     global $CFG, $SESSION;
     if (isset($SESSION->questionnaire->currentgroupid)) {
         $groupid = $SESSION->questionnaire->currentgroupid;
     } else {
         $groupid = -1;
     }
     $output = array();
     $nbinfocols = 9;
     // change this if you want more info columns
     $stringother = get_string('other', 'questionnaire');
     $columns = array(get_string('response', 'questionnaire'), get_string('submitted', 'questionnaire'), get_string('institution'), get_string('department'), get_string('course'), get_string('group'), get_string('id', 'questionnaire'), get_string('fullname'), get_string('username'));
     $types = array(0, 0, 1, 1, 1, 1, 0, 1, 1);
     // get extra user_info_field columns names
     // 		$uifs = get_records('user_info_field');
     // 		foreach ($uifs as $uif) {
     // 			array_push($columns,$uif->shortname);
     // 			array_push($types,1);
     // 			$nbinfocols++;
     // 		}
     $arr = array();
     // 0 = number; 1 = text
     $id_to_csv_map = array('0', '0', '1', '1', '0', '0', '0', '0', '0', '1', '0');
     if (!($survey = get_record('questionnaire_survey', 'id', $this->survey->id))) {
         error(get_string('surveynotexists', 'questionnaire'));
     }
     $select = 'survey_id = ' . $this->survey->id . ' AND deleted = \'n\' AND type_id < 50';
     $fields = 'id,name,type_id,position';
     if (!($records = get_records_select('questionnaire_question', $select, 'position', $fields))) {
         $records = array();
     }
     global $CFG;
     $num = 1;
     foreach ($records as $record) {
         // establish the table's field names
         $qid = $record->id;
         $qpos = $record->position;
         if ($record->name == '') {
         }
         $col = $record->name;
         $type = $record->type_id;
         if ($type == 4 || $type == 5 || $type == 8) {
             /* single or multiple or rate */
             $sql = "SELECT c.id as cid, q.id as qid, q.precise AS precise, q.name, c.content\n                FROM " . $CFG->prefix . "questionnaire_question q " . 'LEFT JOIN ' . $CFG->prefix . "questionnaire_quest_choice c ON question_id = q.id " . 'WHERE q.id = ' . $qid . ' ORDER BY cid ASC';
             if (!($records2 = get_records_sql($sql))) {
                 $records2 = array();
             }
             $subqnum = 0;
             switch ($type) {
                 case 4:
                     // single
                     $columns[][$qpos] = $col;
                     array_push($types, $id_to_csv_map[$type]);
                     $thisnum = 1;
                     foreach ($records2 as $record2) {
                         $content = $record2->content;
                         if (ereg('^!other', $content)) {
                             $col = $record2->name . '_' . $stringother;
                             $columns[][$qpos] = $col;
                             array_push($types, '0');
                         }
                     }
                     break;
                 case 5:
                     // multiple
                     $thisnum = 1;
                     foreach ($records2 as $record2) {
                         $content = $record2->content;
                         $modality = '';
                         if (ereg('^!other', $content)) {
                             $content = $stringother;
                             $col = $record2->name . '->[' . $content . ']';
                             $columns[][$qpos] = $col;
                             array_push($types, '0');
                         }
                         $contents = choice_values($content);
                         if ($contents->modname) {
                             $modality = $contents->modname;
                         } elseif ($contents->title) {
                             $modality = $contents->title;
                         } else {
                             $modality = html_to_text($contents->text);
                         }
                         $col = $record2->name . '->' . $modality;
                         $columns[][$qpos] = $col;
                         array_push($types, '0');
                     }
                     break;
                 case 8:
                     // rate
                     foreach ($records2 as $record2) {
                         $nameddegrees = 0;
                         $modality = '';
                         $content = $record2->content;
                         $osgood = false;
                         if ($record2->precise == 3) {
                             $osgood = true;
                         }
                         if (ereg("^[0-9]{1,3}", $content, $ndd)) {
                             $nameddegrees++;
                         } else {
                             if ($osgood) {
                                 list($contentleft, $contentright) = split('[|]', $content);
                                 $contents = choice_values($contentleft);
                                 if ($contents->title) {
                                     $contentleft = $contents->title;
                                 }
                                 $contents = choice_values($contentright);
                                 if ($contents->title) {
                                     $contentright = $contents->title;
                                 }
                                 $modality = html_to_text($contentleft . '|' . $contentright);
                             } else {
                                 $contents = choice_values($content);
                                 if ($contents->modname) {
                                     $modality = $contents->modname;
                                 } elseif ($contents->title) {
                                     $modality = $contents->title;
                                 } else {
                                     $modality = html_to_text($contents->text);
                                     $modality = ereg_replace("[\r\n\t]", ' ', $modality);
                                 }
                             }
                             $col = $record2->name . '->' . $modality;
                             $columns[][$qpos] = $col;
                             array_push($types, $id_to_csv_map[$type]);
                         }
                     }
                     break;
             }
         } else {
             if (in_array($col, $columns)) {
                 $col = $col . $num;
             }
             $columns[][$qpos] = $col;
             array_push($types, $id_to_csv_map[$type]);
         }
         $num++;
     }
     array_push($output, $columns);
     $numcols = count($output[0]);
     if ($rid) {
         // send e-mail for a unique response ($rid)
         $select = 'survey_id = ' . $this->survey->id . ' AND complete=\'y\' AND id = ' . $rid;
         $fields = 'id,submitted,username';
         if (!($records = get_records_select('questionnaire_response', $select, 'submitted', $fields))) {
             $records = array();
         }
     } else {
         if ($userid) {
             // download CSV for one user's own responses'
             $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                          FROM " . $CFG->prefix . "questionnaire_response R\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y' AND\n                               R.username='******'\n                         ORDER BY R.id";
             if (!($records = get_records_sql($sql))) {
                 $records = array();
             }
         } else {
             // download CSV for all participants (or groups if enabled)
             if ($groupid == -1) {
                 // all participants
                 $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                          FROM " . $CFG->prefix . "questionnaire_response R\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y'\n                         ORDER BY R.id";
             } else {
                 if ($groupid == -2) {
                     // all members of any group
                     $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                          FROM " . $CFG->prefix . "questionnaire_response R,\n                                " . $CFG->prefix . "groups_members GM\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y' AND\n                               GM.groupid>0 AND\n                               R.username=GM.userid\n                         ORDER BY R.id";
                 } else {
                     if ($groupid == -3) {
                         // not members of any group
                         $sql = "SELECT R.id, R.survey_id, R.submitted,  U.id AS username\n                          FROM " . $CFG->prefix . "questionnaire_response R,\n                                " . $CFG->prefix . "user U\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y' AND\n                               R.username=U.id\n                         ORDER BY username";
                     } else {
                         // members of a specific group
                         $sql = "SELECT R.id, R.survey_id, R.submitted, R.username\n                          FROM " . $CFG->prefix . "questionnaire_response R,\n                                " . $CFG->prefix . "groups_members GM\n                         WHERE R.survey_id='{$this->survey->id}' AND\n                               R.complete='y' AND\n                               GM.groupid=" . $groupid . " AND\n                               R.username=GM.userid\n                         ORDER BY R.id";
                     }
                 }
             }
             if (!($records = get_records_sql($sql))) {
                 $records = array();
             }
             if ($groupid == -3) {
                 // members of no group
                 foreach ($records as $row => $key) {
                     $userid = $key->username;
                     if (groups_has_membership($this->cm, $userid)) {
                         unset($records[$row]);
                     }
                 }
             }
         }
     }
     $isanonymous = $this->respondenttype == 'anonymous';
     foreach ($records as $record) {
         // get the response
         $response = $this->response_select_name($record->id);
         $qid = $record->id;
         //JR for better compabitility & readability with Excel
         $submitted = date(get_string('strfdateformatcsv', 'questionnaire'), $record->submitted);
         $institution = '';
         $department = '';
         $username = $record->username;
         if ($user = get_record('user', 'id', $username)) {
             $institution = $user->institution;
             $department = $user->department;
         }
         if ($isanonymous) {
             $username = get_string('anonymous', 'questionnaire');
         }
         /// Moodle:
         //  Get the course name that this questionnaire belongs to.
         if ($survey->realm != 'public') {
             $courseid = $this->course->id;
             $coursename = $this->course->fullname;
         } else {
             /// For a public questionnaire, look for the course that used it.
             $sql = 'SELECT q.id, q.course, c.fullname ' . 'FROM ' . $CFG->prefix . 'questionnaire q, ' . $CFG->prefix . 'questionnaire_attempts qa, ' . $CFG->prefix . 'course c ' . 'WHERE qa.rid = ' . $qid . ' AND q.id = qa.qid AND c.id = q.course';
             if ($record = get_record_sql($sql)) {
                 $courseid = $record->course;
                 $coursename = $record->fullname;
             } else {
                 $courseid = $this->course->id;
                 $coursename = $this->course->fullname;
             }
         }
         /// Moodle:
         //  If the username is numeric, try it as a Moodle user id.
         if (is_numeric($username)) {
             if ($user = get_record('user', 'id', $username)) {
                 $uid = $username;
                 $fullname = fullname($user);
                 $username = $user->username;
             } else {
                 $uid = '';
                 $fullname = get_string('anonymous', 'questionnaire');
                 $username = '';
             }
         } else {
             $uid = '';
             $fullname = get_string('anonymous', 'questionnaire');
             $username = '';
         }
         /// Moodle:
         //  Determine if the user is a member of a group in this course or not.
         $groupname = '';
         if ($this->cm->groupmode > 0) {
             if ($groupid > 0) {
                 $groupname = groups_get_group_name($groupid);
             } else {
                 if ($uid) {
                     if ($groups = groups_get_all_groups($courseid, $uid)) {
                         foreach ($groups as $group) {
                             $groupname .= $group->name . ', ';
                         }
                         $groupname = substr($groupname, 0, strlen($groupname) - 2);
                     } else {
                         $groupname = ' (' . get_string('groupnonmembers') . ')';
                     }
                 }
             }
         }
         $arr = array();
         array_push($arr, $qid);
         array_push($arr, $submitted);
         array_push($arr, $institution);
         array_push($arr, $department);
         array_push($arr, $coursename);
         array_push($arr, $groupname);
         array_push($arr, $uid);
         array_push($arr, $fullname);
         array_push($arr, $username);
         // get extra user_info_field user's data
         // 			$uifs = get_records('user_info_field');
         // 			foreach ($uifs as $uif) {
         // 				$tempuifd = get_field('user_info_data', 'data', 'userid', $record->username, 'fieldid', $uif->id);
         // 				array_push($arr,$tempuifd);
         // 				unset($tempuifd);
         // 			}
         // merge it
         for ($i = $nbinfocols; $i < $numcols; $i++) {
             /*if (isset($response[$columns[$i]]) && is_array($response[$columns[$i]])) {
                   $response[$columns[$i]] = join(',', $response[$columns[$i]]);
               }*/
             $qpos = key($columns[$i]);
             $qname = current($columns[$i]);
             if (isset($response[$qpos][$qname]) && $response[$qpos][$qname] != '') {
                 $thisresponse = $response[$qpos][$qname];
             } else {
                 $thisresponse = '';
             }
             switch ($types[$i]) {
                 case 1:
                     //string
                     // Excel seems to allow "\n" inside a quoted string, but
                     // "\r\n" is used as a record separator and so "\r" may
                     // not occur within a cell. So if one would like to preserve
                     // new-lines in a response, remove the "\n" from the
                     // regex below.
                     // email format text is plain text for being displayed in Excel, etc. added by JR
                     // but it must be stripped of carriage returns
                     if ($thisresponse) {
                         $thisresponse = format_text_email($thisresponse, FORMAT_HTML);
                         $thisresponse = ereg_replace("[\r\n\t]", ' ', $thisresponse);
                         $thisresponse = ereg_replace('"', '""', $thisresponse);
                     }
                     // fall through
                 // fall through
                 case 0:
                     //number
                     //array_push($arr,$thisresponse);
                     break;
             }
             array_push($arr, $thisresponse);
         }
         array_push($output, $arr);
     }
     // change table headers to incorporate actual question numbers
     $numcol = 0;
     $numquestion = 0;
     $out = '';
     $nbrespcols = count($output[0]);
     $oldkey = 0;
     for ($i = $nbinfocols; $i < $nbrespcols; $i++) {
         $sep = '';
         $thisoutput = current($output[0][$i]);
         $thiskey = key($output[0][$i]);
         // case of unnamed rate single possible answer (full stop char is used for support)
         if (strstr($thisoutput, '->.')) {
             $thisoutput = str_replace('->.', '', $thisoutput);
         }
         // if variable is not named no separator needed between Question number and potential sub-variables
         if ($thisoutput == '' || strstr($thisoutput, '->.') || substr($thisoutput, 0, 2) == '->' || substr($thisoutput, 0, 1) == '_') {
             $sep = '';
         } else {
             $sep = '_';
         }
         if ($thiskey > $oldkey) {
             $oldkey = $thiskey;
             $numquestion++;
         }
         // abbreviated modality name in multiple or rate questions (COLORS->blue=the color of the sky...)
         $pos = strpos($thisoutput, '=');
         if ($pos) {
             $thisoutput = substr($thisoutput, 0, $pos);
         }
         $other = $sep . $stringother;
         $out = 'Q' . sprintf("%02d", $numquestion) . $sep . $thisoutput;
         $output[0][$i] = $out;
     }
     return $output;
 }