File:  [LON-CAPA] / loncom / interface / statistics / lonstudentsubmissions.pm
Revision 1.63.2.3: download - view: text, annotated - select for diffs
Tue Nov 22 01:34:39 2011 UTC (12 years, 8 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_1, loncapaMITrelate_1
- Backport 1.65.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstudentsubmissions.pm,v 1.63.2.3 2011/11/22 01:34:39 raeburn Exp $
    4: #
    5: # Copyright Michigan State University Board of Trustees
    6: #
    7: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    8: #
    9: # LON-CAPA is free software; you can redistribute it and/or modify
   10: # it under the terms of the GNU General Public License as published by
   11: # the Free Software Foundation; either version 2 of the License, or
   12: # (at your option) any later version.
   13: #
   14: # LON-CAPA is distributed in the hope that it will be useful,
   15: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   16: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   17: # GNU General Public License for more details.
   18: #
   19: # You should have received a copy of the GNU General Public License
   20: # along with LON-CAPA; if not, write to the Free Software
   21: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   22: #
   23: # /home/httpd/html/adm/gpl.txt
   24: #
   25: # http://www.lon-capa.org/
   26: #
   27: package Apache::lonstudentsubmissions;
   28: 
   29: use strict;
   30: use Apache::lonnet;
   31: use Apache::loncommon();
   32: use Apache::lonhtmlcommon();
   33: use Apache::loncoursedata();
   34: use Apache::lonstatistics;
   35: use Apache::lonlocal;
   36: use Apache::lonstathelpers;
   37: use Apache::lonmsgdisplay();
   38: use HTML::Entities();
   39: use Time::Local();
   40: use Spreadsheet::WriteExcel();
   41: use lib '/home/httpd/lib/perl/';
   42: use LONCAPA;
   43:   
   44: 
   45: my @SubmitButtons = ({ name => 'SelectAnother',
   46:                        text => 'Choose a different Problem' },
   47:                      { name => 'Generate',
   48:                        text => 'Generate Report'},
   49:                      );
   50: 
   51: sub BuildStudentSubmissionsPage {
   52:     my ($r,$c)=@_;
   53:     #
   54:     my %Saveable_Parameters = ('Status' => 'scalar',
   55:                                'Section' => 'array',
   56:                                'NumPlots' => 'scalar',
   57:                                );
   58:     &Apache::loncommon::store_course_settings('student_submissions',
   59:                                               \%Saveable_Parameters);
   60:     &Apache::loncommon::restore_course_settings('student_submissions',
   61:                                                 \%Saveable_Parameters);
   62:     #
   63:     &Apache::lonstatistics::PrepareClasslist();
   64:     #
   65:     $r->print(&CreateInterface());
   66:     #
   67:     my @Students = @Apache::lonstatistics::Students;
   68:     #
   69:     if (@Students < 1) {
   70:         $r->print('<div class="LC_warning">'
   71:                  .&mt('There are no students in the sections selected.')
   72:                  .'</div>');
   73:     }
   74:     #
   75:     my @CacheButtonHTML = 
   76:         &Apache::lonstathelpers::manage_caches($r,'Statistics','stats_status',
   77:                                    '<div class="LC_info">'.&mt('Loading student data...').'</div>');
   78:     $r->rflush();
   79:     #
   80:     my %anoncounter =
   81:          &Apache::lonnet::dump('nohist_anonsurveys',
   82:                         $env{'course.'.$env{'request.course.id'}.'.domain'},
   83:                         $env{'course.'.$env{'request.course.id'}.'.num'});
   84:     if (exists($env{'form.problemchoice'}) && 
   85:         ! exists($env{'form.SelectAnother'})) {
   86:         foreach my $button (@SubmitButtons) {
   87:             if ($button->{'name'} eq 'break') {
   88:                 $r->print("<br />\n");
   89:             } else {
   90:                 $r->print('<input type="submit" name="'.$button->{'name'}.'" '.
   91:                           'value="'.&mt($button->{'text'}).'" />');
   92:                 $r->print('&nbsp;'x5);
   93:             }
   94:         }
   95:         foreach my $html (@CacheButtonHTML) {
   96:             $r->print($html.('&nbsp;'x5));
   97:         }
   98:         #
   99:         $r->print('<hr />'.$/);
  100:         $r->rflush();
  101:         #
  102:         # Determine which problems we are to analyze
  103:         my @Symbs = 
  104:             &Apache::lonstathelpers::get_selected_symbs('problemchoice');
  105: 
  106:         # If there are multi-part problems with anonymous survey and named
  107:         # parts check if named was picked for display.
  108:         #
  109:         my %mixed_named; 
  110:         foreach my $envkey (%env) {
  111:             if ($envkey =~ /^form\.mixed_(\d+:\d+)$/) {
  112:                 my $item = $1; 
  113:                 if ($env{$envkey} =~ /^symb_(.+)$/) {
  114:                     my $symb = &unescape($1);
  115:                     if (ref($mixed_named{$symb}) eq 'ARRAY') {
  116:                         push(@{$mixed_named{$symb}},$item);
  117:                     } else {
  118:                         @{$mixed_named{$symb}} = ($item);
  119:                     }
  120:                 }
  121:             }
  122:         }
  123:         #
  124:         # Get resource objects
  125:         my $navmap = Apache::lonnavmaps::navmap->new();
  126:         if (!defined($navmap)) {
  127:             foreach my $selected (@Symbs) {
  128:                 $r->print('<input type="hidden" name="problemchoice" value="'.
  129:                           &escape($selected).'" />'.$/);
  130:                 if (ref($mixed_named{$selected}) eq 'ARRAY') {
  131:                     foreach my $item (@{$mixed_named{$selected}}) {
  132:                         $r->print('<input type="hidden" name="mixed_'.$item.'" value="'.&escape($selected).'" />'.$/);
  133:                     }
  134:                 }
  135:             }
  136:             $r->print('<div class="LC_error">'.&mt("Internal error").'</div>');
  137:             return;
  138:         }
  139:         my %already_seen;
  140:         my (@Problems,@anonProbs,@namedProbs,$show_named);
  141:         foreach my $symb (@Symbs) {
  142:             my $resource = $navmap->getBySymb($symb);
  143:             my ($hasanon,$hasnamed);
  144:             if (ref($resource)) {
  145:                 foreach my $partid (@{$resource->parts}) {
  146:                     if (($anoncounter{$symb."\0".$partid}) || ($resource->is_anonsurvey($partid))) {
  147:                         unless (exists($mixed_named{$symb})) {
  148:                             $hasanon = 1;
  149:                         }
  150:                     } else {
  151:                         $hasnamed = 1;
  152:                     }
  153:                 }
  154:                 if ($hasanon) {
  155:                     push(@anonProbs,$resource);
  156:                 } elsif ($hasnamed) {
  157:                     push(@namedProbs,$resource);
  158:                 }
  159:             }
  160:         }
  161:         if (@namedProbs > 0) {
  162:             @Problems = @namedProbs;
  163:             $show_named = 1;
  164:         } elsif (@anonProbs > 0) {
  165:             @Problems = @anonProbs;
  166:         } 
  167:         foreach my $selected (@Symbs) {
  168:             $r->print('<input type="hidden" name="problemchoice" value="'.
  169:                       &escape($selected).'" />'.$/);
  170:             if (ref($mixed_named{$selected}) eq 'ARRAY') {
  171:                 foreach my $item (@{$mixed_named{$selected}}) {
  172:                     $r->print('<input type="hidden" name="mixed_'.$item.'" value="'.&escape($selected).'" />'.$/);
  173:                 }
  174:             }
  175:         }
  176:         # If these are to be anonymized, do a random shuffle of @Students. 
  177:         unless ($show_named) {
  178:             &array_shuffle(\@Students);
  179:         }
  180:         #
  181: 
  182:         my $threshold = $env{'course.'.$env{'request.course.id'}.'.internal.anonsurvey_threshold'};
  183:         if ($threshold eq '') {
  184:             my %domconfig =
  185:                 &Apache::lonnet::get_dom('configuration',['coursedefaults'],
  186:                                         $env{'course.'.$env{'request.course.id'}.'.domain'});
  187:             if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
  188:                 $threshold = $domconfig{'coursedefaults'}{'anonsurvey_threshold'};
  189:                 if ($threshold eq '') {
  190:                     $threshold = 10;
  191:                 }
  192:             } else {
  193:                 $threshold = 10;
  194:             }
  195:         }
  196:         $r->print('<h4>'.
  197:                   &Apache::lonstatistics::section_and_enrollment_description().
  198:                   '</h4>');
  199:         if (! scalar(@Problems) || ! defined($Problems[0])) {
  200:             $r->print(&mt('resource is undefined'));
  201:         } elsif (!$show_named && @Students < $threshold) {
  202:             $r->print(&mt('The number of students matching the selection criteria is too few for display of submission data for anonymous surveys.').'<br />'.&mt('There must be at least [quant,_1,student].',$threshold).' '.&mt('Contact a Domain Coordinator if you need the threshold to be changed for this course.'));
  203:         } else {
  204:             if (scalar(@Problems) == 1) {
  205:                 my $resource = $Problems[0];
  206:                 $r->print('<h1>'.$resource->title.'</h1>');
  207:                 $r->print('<h3>'.$resource->src.'</h3>');
  208:                 if ($env{'form.renderprob'} eq 'true') {
  209:                     $r->print(&Apache::lonstathelpers::render_resource($resource));
  210:                     $r->rflush();
  211:                 }
  212:             }
  213:             if ($env{'form.output'} eq 'excel') {
  214:                 &prepare_excel_output($r,\@Problems,\@Students,\%anoncounter,$show_named);
  215:             } elsif ($env{'form.output'} eq 'csv') {
  216:                 &prepare_csv_output($r,\@Problems,\@Students,\%anoncounter,$show_named);
  217:             } else {
  218:                 &prepare_html_output($r,\@Problems,\@Students,\%anoncounter,$show_named);
  219:             }
  220:         }
  221:         $r->print('<hr />');
  222:     } else {
  223:         $r->print('<input type="submit" name="Generate" value="'.
  224:                   &mt('Prepare Report').'" />');
  225:         $r->print('&nbsp;'x5);
  226:         $r->print('<p>'.
  227:                   &mt('Computing correct answers greatly increases the amount of time required to prepare a report.').
  228:                   '</p>');
  229:         $r->print('<p>'.
  230:                   &mt('Please select problems and use the [_1]Prepare Report[_2] button to continue.','<b>','</b>').
  231:                   '</p>');
  232:         $r->print(&Apache::lonstathelpers::MultipleProblemSelector
  233:                   (undef,'problemchoice','Statistics',\%anoncounter));
  234:     }
  235: }
  236: 
  237: sub array_shuffle {
  238:     my $array = shift;
  239:     return unless (ref($array) eq 'ARRAY');
  240:     my $i = scalar(@$array);
  241:     my $j;
  242:     foreach my $item (@$array) {
  243:         --$i;
  244:         $j = int(rand($i+1));
  245:         next if($i == $j);
  246:         @$array [$i,$j] = @$array[$j,$i];
  247:     }
  248:     return @$array;
  249: }
  250: 
  251: ##
  252: ## get_extra_response_headers
  253: ##
  254: sub get_extra_response_headers {
  255:     my ($show_named) = @_;
  256:     my @extra_resp_headers;
  257:     if ($env{'form.correctans'} eq 'true') {
  258:         push(@extra_resp_headers,'Correct');
  259:     }
  260:     if ($show_named) { 
  261:         if ($env{'form.prob_status'} eq 'true') {
  262:             push(@extra_resp_headers,'Award Detail'); 
  263:             push(@extra_resp_headers,'Time');
  264:             push(@extra_resp_headers,'Attempt');
  265:             push(@extra_resp_headers,'Awarded');
  266:         }
  267:     }
  268:     return @extra_resp_headers;
  269: }
  270: 
  271: ##
  272: ## get_headers:
  273: ##     return the proper headers for the given response 
  274: sub get_headers {
  275:     my ($prob,$partid,$respid,$resptype,$analysis,$output,$purpose,
  276:         @basic_headers) = @_;
  277:     my @headers;
  278:     if ($resptype eq 'essay' && $purpose eq 'display' &&
  279:         ($output eq 'html')) {# || scalar(@{$prob->parts})!=1)) {
  280:         @headers = ();
  281:     } elsif ($resptype =~ /^(option|match|rank)$/) {
  282:         my $prefix = '_';
  283:         if ($purpose eq 'display') {
  284:             $prefix = '';
  285:         }
  286:         my @foils = 
  287:             map { 
  288:                 $prefix.$_; 
  289:             } sort(keys(%{$analysis->{$partid.'.'.$respid}->{'_Foils'}}));
  290:         if (scalar(@basic_headers) && $basic_headers[0] eq 'Correct') {
  291:             @foils = map { ($_ , $_.' Correct') } @foils;
  292:             shift(@basic_headers);  # Get rid of 'Correct'
  293:         }
  294:         @headers = (@foils,@basic_headers);
  295:     } elsif (lc($resptype) eq 'task') {
  296:         @headers = ('Grader','Status',@basic_headers,'Submission');
  297:     } else {
  298:         @headers = ('Submission',@basic_headers);
  299:     }
  300:     return @headers;
  301: }
  302: 
  303: #########################################################
  304: #########################################################
  305: ##
  306: ##    HTML Output Routines
  307: ##
  308: #########################################################
  309: #########################################################
  310: sub prepare_html_output {
  311:     my ($r,$problems,$students,$anoncounter,$show_named) = @_;
  312:     my $c = $r->connection();
  313:     #
  314:     # Set a flag for the case when there is just one problem
  315:     my $single_response = 0;
  316:     if (scalar(@$problems) == 1 &&
  317:         $problems->[0]->countResponses == 1) {
  318:         $single_response = 1;
  319:     }
  320:     #
  321:     # Compute the number of columns per response
  322:     my @extra_resp_headers = &get_extra_response_headers($show_named);
  323:     #
  324:     # Create the table header
  325:     my @student_columns = &get_student_columns($show_named);
  326:     my %headers;
  327:     my $student_column_count = scalar(@student_columns);
  328:     $headers{'problem'} = qq{<th colspan="$student_column_count">\&nbsp;</th>};
  329:     foreach my $field (@student_columns) {
  330:         $headers{'student'}.= '<th>'.ucfirst($field).'</th>';
  331:     }
  332:     #
  333:     # we put the headers into the %headers hash
  334:     my $total_col = $student_column_count;
  335:     my $nonempty_part_headers = 0;
  336:     #
  337:     my %problem_analysis;
  338:     foreach my $prob (@$problems) {
  339:         my %analysis = &Apache::lonstathelpers::get_problem_data($prob->src);
  340:         $problem_analysis{$prob->src}=\%analysis;
  341:         my $symb = $prob->symb();
  342:         #
  343:         my $prob_span = 0;
  344:         my $single_part = 0;
  345:         if (scalar(@{$prob->parts}) == 1) {
  346:             $single_part = 1;
  347:         }
  348:         my $shown_parts = 0;
  349:         foreach my $partid (@{$prob->parts}) {
  350:             if (($prob->is_anonsurvey($partid)) || ($anoncounter->{$symb."\0".$partid})) {
  351:                 next if ($show_named);
  352:             } else {
  353:                 next unless ($show_named);
  354:             }
  355:             $shown_parts ++;
  356:             my $part_span = 0;
  357:             my $responses = [$prob->responseIds($partid)];
  358:             my $resptypes = [$prob->responseType($partid)];
  359:             for (my $i=0;$i<scalar(@$responses);$i++) {
  360:                 my $respid = $responses->[$i];
  361:                 my @headers = &get_headers($prob,$partid,$respid,
  362:                                            $resptypes->[$i],
  363:                                            $problem_analysis{$prob->src},
  364:                                            'html','display',
  365:                                            @extra_resp_headers);
  366:                 if (scalar(@headers)>0) {
  367:                     $total_col += scalar(@headers);
  368:                     $part_span += scalar(@headers);
  369:                     $headers{'response'} .=
  370:                         '<th colspan="'.scalar(@headers).'">'.
  371:                         &mt('Response [_1]',$responses->[$i]).'</th>';
  372:                     $headers{'student'}.= '<th><span class="LC_nobreak">'.
  373:                                           join('</span></th><th><span class="LC_nobreak">',
  374:                                                       @headers).
  375:                                                           '</span></th>';
  376:                 }
  377:             }
  378:             if ($part_span == 0) {
  379:                 next;
  380:             }
  381:             if (! $single_part) {
  382:                 my $tmpname = $partid;
  383:                 if ($partid =~/^\d+$/) {
  384:                     $tmpname = $prob->part_display($partid);
  385:                 }
  386:                 if ($tmpname !~ /^part/) {
  387:                     $tmpname = 'Part '.$tmpname;
  388:                 }
  389:                 $headers{'part'} .= qq{<th colspan="$part_span">$tmpname</th>};
  390:                 $nonempty_part_headers = 1;
  391:             } else {
  392:                 $headers{'part'} .= qq{<th colspan="$part_span">&nbsp;</th>};
  393:             }
  394:             $prob_span += $part_span;
  395:         }
  396:         next if (!$shown_parts);
  397:         my $title = $prob->compTitle;
  398:         if ($prob_span > 0) {
  399:             $headers{'problem'}.= qq{<th colspan="$prob_span">$title</th>};
  400:         } elsif ($single_response) {
  401:             $prob_span = scalar(@student_columns);
  402:             $headers{'problem'} = qq{<th colspan="$prob_span">$title</th>};
  403:         }
  404:     }
  405:     if (exists($headers{'part'})) {
  406:         $headers{'part'} = qq{<th colspan="$student_column_count">\&nbsp;</th>}.
  407:             $headers{'part'};
  408:     }
  409:     if (exists($headers{'response'})) {
  410:         $headers{'response'}=
  411:             qq{<th colspan="$student_column_count">\&nbsp;</th>}.
  412:             $headers{'response'};
  413:     }
  414:     my $full_header = $/.'<table>'.$/;
  415:     $full_header .= '<tr align="left">'.$headers{'problem'}.'</tr>'.$/;
  416:     if ($nonempty_part_headers) {
  417:         $full_header .= '<tr align="left">'.$headers{'part'}.'</tr>'.$/;
  418:     }
  419:     $full_header .= '<tr align="left">'.$headers{'response'}.'</tr>'.$/;
  420:     $full_header .= '<tr align="left">'.$headers{'student'}.'</tr>'.$/;
  421:     #
  422:     # Main loop
  423:     my $count;
  424:     $r->print($/.$full_header.$/);
  425:     my $row_class = 'odd';   # css 
  426:     foreach my $student (@$students) {
  427:         my $student_row_data;
  428:         if ($count++ >= 30) {
  429:             $r->print('</table>'.$/.$full_header.$/);
  430:             $count = 0;
  431:         }
  432:         last if ($c->aborted());
  433:         if ($show_named) {
  434:             foreach my $field (@student_columns) {
  435:                 $student_row_data .= '<td valign="top">';
  436:                 # handle comments like in lonstudentassessment.pm
  437:                 if($field eq 'comments') {
  438:                     $student_row_data .= 
  439:                         '<a href="/adm/'.$student->{'domain'}.'/'.
  440:                         $student->{'username'}.'/'.'aboutme#coursecomment">'.&mt('Comments').'</a>';
  441:                 } else {
  442:                     $student_row_data .= $student->{$field};
  443:                 }
  444:                 $student_row_data .= '</td>';
  445:             }
  446:         } else {
  447:             $student_row_data = '<td valign="top" colspan="'.$student_column_count.'">'.&mt('Anonymized').'</td>';
  448:         }
  449:         #
  450:         # Figure out what it is we need to output for this student
  451:         my @essays;
  452:         my %prob_data;
  453:         my $maxrow;
  454:         foreach my $prob (@$problems) {
  455:             my $symb = $prob->symb;
  456:             $prob_data{$symb}={};
  457:             foreach my $partid (@{$prob->parts}) {
  458:                 if (($prob->is_anonsurvey($partid)) || ($anoncounter->{$symb."\0".$partid})) {
  459:                     next if ($show_named);
  460:                 } else {
  461:                     next unless ($show_named);
  462:                 }
  463:                 my @responses = $prob->responseIds($partid);
  464:                 my @response_type = $prob->responseType($partid);
  465:                 for (my $i=0;$i<=$#responses;$i++) {
  466:                     my $respid  = $responses[$i];
  467:                     my $results = 
  468:                         &Apache::loncoursedata::get_response_data_by_student
  469:                         ($student,$prob->symb(),$respid);
  470:                     my $resptype = $response_type[$i];
  471:                     my @headers = &get_headers($prob,$partid,$respid,
  472:                                                $resptype,
  473:                                                $problem_analysis{$prob->src},
  474:                                                'html','normal',
  475:                                                @extra_resp_headers);
  476:                     my $width = scalar(@headers);
  477:                     next if ($width < 1);
  478:                     my $resp_data;
  479:                     $resp_data->{'fake'} = qq{<td colspan="$width">&nbsp;</td>};
  480:                     if (! defined($results)) {
  481:                         $results = [];
  482:                     }
  483:                     # 
  484:                     if (scalar(@$results) > $maxrow && $resptype ne 'essay') {
  485:                         $maxrow = scalar(@$results);
  486:                     }
  487:                     for (my $j=scalar(@$results)-1;$j>=0;$j--) {
  488:                         if ($env{'form.all_sub'} ne 'true') {
  489:                             next if ($j ne scalar(@$results)-1);
  490:                         }
  491:                         my $response = &hashify_response($results->[$j],
  492:                                                          $prob,
  493:                                                          $student,
  494:                                                          $partid,
  495:                                                          $respid);
  496:                         if ($resptype eq 'essay') {
  497:                             push(@essays,
  498:                                  &html_essay_results(\@headers,
  499:                                                      $prob,$partid,$respid,
  500:                                                      $response,
  501:                                                      $single_response).
  502:                                  '</td>');
  503: 			} elsif (lc($resptype) eq 'task') {
  504: 			    my $results = 
  505: 				&html_task_results(\@headers,
  506: 						   $prob,$partid,$respid,
  507: 						   $response,$resptype);
  508: 			    if ($results) {
  509: 				push(@{$resp_data->{'real'}},$results);
  510: 			    }
  511:                         } else {
  512:                             push(@{$resp_data->{'real'}},
  513:                                  &html_non_essay_results(\@headers,
  514:                                                          $prob,$partid,$respid,
  515:                                                          $response,$resptype));
  516:                         }
  517:                     }
  518:                     $prob_data{$prob->symb}->{$partid}->{$respid}=$resp_data;
  519:                 } # end of $i loop
  520:             } # end of partid loop
  521:         } # end of prob loop
  522:         #
  523:         # if there is no data, skip this student.
  524:         next if (! $maxrow && ! scalar(@essays));
  525:         #
  526:         # Go through the problem data and output a row.
  527:         if ($row_class eq 'even') {
  528:             $row_class = 'odd'; 
  529:         } else {
  530:             $row_class = 'even'; 
  531:         }
  532:         my $printed_something;
  533:         for (my $rows_output = 0;$rows_output<$maxrow;$rows_output++) {
  534:             my $html;
  535:             my $no_data = 1;
  536:             foreach my $prob (@$problems) {
  537:                 foreach my $partid (@{$prob->parts}) {
  538:                     my @responses     = $prob->responseIds($partid);
  539:                     my @response_type = $prob->responseType($partid);
  540:                     for (my $i=0;$i<=$#responses;$i++) {
  541:                         my $respid   = $responses[$i];
  542:                         my $resp_data = 
  543:                             $prob_data{$prob->symb}->{$partid}->{$respid};
  544:                         next if ($response_type[$i] eq 'essay');
  545:                         if (defined($resp_data->{'real'}->[$rows_output])) {
  546:                             $html .= $resp_data->{'real'}->[$rows_output];
  547:                             $no_data = 0;
  548:                         } else {
  549:                             $html .= $resp_data->{'fake'};
  550:                         }
  551:                     }
  552:                 }
  553:             }
  554:             if (! $no_data) {
  555:                 $r->print(qq{<tr class="$row_class">$student_row_data$html</tr>}.$/);
  556:                 $printed_something=1;
  557:             }
  558:         }
  559:         if (@essays) {
  560:             my $tr = qq{<tr class="$row_class">};
  561:             my $td = qq{<td  valign="top" class="essay" colspan="$total_col">};
  562:             if (! $printed_something) {
  563:                 $r->print($tr.$student_row_data.'</tr>'.$/);
  564:             }
  565:             $r->print($tr.$td.
  566:                       join('</td></tr>'.$/.$tr.$td,@essays).'</td></tr>'.$/);
  567:             undef(@essays);
  568:         }
  569:     } # end of student loop
  570:     $r->print('</table>'.$/);
  571:     return;
  572: }
  573: 
  574: sub hashify_response {
  575:     my ($response,$prob,$student,$partid,$respid) =@_;
  576:     my $resp_hash = {};
  577:     if ($env{'form.correctans'} eq 'true') {
  578:         $resp_hash->{'Correct'} = 
  579:             &Apache::lonstathelpers::get_student_answer
  580:             ($prob,$student->{'username'},$student->{'domain'},
  581:              $partid,$respid);
  582:     }
  583:     $resp_hash->{'Submission'} = 
  584:         $response->[&Apache::loncoursedata::RDs_submission()];
  585:     $resp_hash->{'Time'} = 
  586:         $response->[&Apache::loncoursedata::RDs_timestamp()];
  587:     $resp_hash->{'Attempt'} =
  588:         $response->[&Apache::loncoursedata::RDs_tries()];
  589:     $resp_hash->{'Awarded'} = 
  590:         $response->[&Apache::loncoursedata::RDs_awarded()];
  591:     if ($prob->is_task()) {
  592: 	$resp_hash->{'Grader'} = 
  593: 	    $response->[&Apache::loncoursedata::RDs_response_eval_2()];
  594: 	if ($resp_hash->{'Attempt'} eq '0') {
  595: 	    $resp_hash->{'Attempt'} = '';
  596: 	}
  597: 	$resp_hash->{'Award Detail'} = 
  598: 	    $response->[&Apache::loncoursedata::RDs_part_award()];
  599: 	$resp_hash->{'Status'} = 
  600: 	    $response->[&Apache::loncoursedata::RDs_response_eval()];
  601:     } else {
  602: 	$resp_hash->{'Award Detail'} = 
  603: 	    $response->[&Apache::loncoursedata::RDs_awarddetail()];
  604:     }
  605: 
  606:     return $resp_hash;
  607: }
  608: 
  609: #####################################################
  610: ##
  611: ##     HTML helper routines
  612: ##
  613: #####################################################
  614: sub html_essay_results {
  615:     my ($headers,$prob,$partid,$respid,$response,$single_response)=@_;
  616:     if (! ref($headers) || ref($headers) ne 'ARRAY') {
  617:         return '';
  618:     }
  619:     # Start of telling them what problem, part, and response
  620:     my $Str;
  621:     if (! $single_response) {
  622:         my $id = $prob->compTitle;
  623:         if (defined($partid) && $partid ne '0') {
  624:             $id .= ' '.$prob->part_display($partid);
  625:         }
  626:         if (defined($respid)) {
  627:             $id .= ' '.$respid;
  628:         }
  629:         $Str .= '<span class="LC_nobreak">'.$id.'</span>'.('&nbsp;'x4);
  630:     }
  631:     #
  632:     shift(@$headers); # Get rid of the Submission header
  633:     my $correct = '';
  634:     if ($headers->[0] eq 'Correct') {
  635:         $correct = &html_format_essay_sub($response->{'Correct'});
  636:         shift(@$headers);
  637:     }
  638:     $Str .= '<span class="LC_nobreak">'.
  639:         join('',
  640:              map {
  641:                  ('&nbsp;'x4).&mt($_.': [_1]',$response->{$_});
  642:              } @$headers).'</span>';
  643:     if (@$headers || ! $single_response) {
  644:         $Str .= '<br />';
  645:     }
  646:     $Str .= &html_format_essay_sub($response->{'Submission'});
  647:     #
  648:     if (defined($correct) && $correct !~ /^\s*$/) {
  649:         $Str .= '<hr /><b>'.&mt('Correct').'</b>'.$correct
  650:     }
  651:     return $Str;
  652: }
  653: 
  654: sub html_format_essay_sub {
  655:     my ($submission) = @_;
  656:     return '' if (! defined($submission) || $submission eq '');
  657:     $submission = &HTML::Entities::decode($submission);
  658:     $submission =~ s/\\\"/\"/g;
  659:     $submission =~ s/\\\'/\'/g;
  660:     $submission =~ s|\\r\\n|$/|g;
  661:     $submission = &HTML::Entities::encode($submission,'<>&"');
  662:     $submission =~ s|$/\s*$/|$/</p><p>$/|g;
  663:     $submission =~ s|\\||g;
  664:     $submission = '<p>'.$submission.'</p>';
  665:     return $submission;
  666: }
  667: 
  668: sub html_task_results {
  669:     my ($headers,$prob,$partid,$respid,$response,$resptype) = @_;
  670:     if (! ref($headers) || ref($headers) ne 'ARRAY' || ! scalar(@$headers)) {
  671:         return '';
  672:     }
  673: 
  674:     my @values;
  675:     @values = map { $response->{$_}; } @$headers;
  676: 
  677:     my $td = '<td valign="top">';
  678:     my $str = $td.join('</td>'.$td,@values).'</td>';
  679:     return $str;
  680: }
  681: 
  682: sub html_non_essay_results {
  683:     my ($headers,$prob,$partid,$respid,$response,$resptype) = @_;
  684:     if (! ref($headers) || ref($headers) ne 'ARRAY' || ! scalar(@$headers)) {
  685:         return '';
  686:     }
  687:     # 
  688:     my $submission = &HTML::Entities::decode(&unescape($response->{'Submission'})); 
  689:     return '' if (! defined($submission) || $submission eq '');
  690:     $submission =~ s/\\\"/\"/g;
  691:     $submission =~ s/\\\'/\'/g;
  692:     if ($resptype eq 'radiobutton') {
  693:         $submission = &HTML::Entities::encode($submission,'<>&"');
  694:         $submission =~ s/=([^=])$//;
  695:         $submission = '<span class="LC_nobreak">'.$submission.'</span>';
  696:     }
  697:     $response->{'Submission'} = $submission;
  698:     #
  699:     my @values;
  700:     if ($resptype =~ /^(option|match|rank)$/) {
  701:         my %submission = 
  702:             map { 
  703:                 my ($foil,$value) = split('=',&unescape($_));
  704:                 ($foil,$value);
  705:             } split('&',$response->{'Submission'});
  706:         my %correct;
  707:         if (exists($response->{'Correct'})) {
  708:             %correct = 
  709:                 map { 
  710:                     my ($foil,$value)=split('=',&unescape($_));
  711:                     ($foil,$value);
  712:                 } split('&',$response->{'Correct'});
  713:         }
  714:         #
  715:         foreach my $original_header (@$headers) {
  716:             if ($original_header =~ /^_/) {
  717:                 # '_' denotes a foil column
  718:                 my ($header) = ($original_header =~ m/^_(.*)$/);
  719:                 my $option = '';
  720:                 if ( my ($foil) = ($header =~ /(.*) Correct$/)) {
  721:                     if (exists($correct{$foil})) {
  722:                         $option = $correct{$foil};
  723:                     }
  724:                 } elsif (exists($submission{$header})) {
  725:                     $option = $submission{$header};
  726:                 }
  727:                 push(@values,&HTML::Entities::encode($option));
  728:             } elsif ($original_header eq 'Time') {
  729:                 push(@values,&Apache::lonlocal::locallocaltime($response->{$original_header}));
  730:             } else {
  731:                 # A normal column
  732:                 push(@values,$response->{$original_header});
  733:             }
  734:         }
  735:     } else {
  736:         @values = map { $response->{$_}; } @$headers;
  737:     }
  738:     my $td = '<td valign="top">';
  739:     my $str = $td.join('</td>'.$td,@values).'</td>';
  740:     return $str;
  741: }
  742: 
  743: 
  744: #########################################################
  745: #########################################################
  746: ##
  747: ##    Excel Output Routines
  748: ##
  749: #########################################################
  750: #########################################################
  751: sub prepare_excel_output {
  752:     my ($r,$Problems,$Students,$anoncounter,$show_named) = @_;
  753:     my $c = $r->connection();
  754:     #
  755:     #
  756:     # Determine the number of columns in the spreadsheet
  757:     my $columncount = 3; # username, domain, id
  758:     my @extra_resp_headers = &get_extra_response_headers($show_named);
  759:     my $lastprob;
  760:     my %problem_analysis;
  761:     foreach my $prob (@$Problems) {
  762:         my $symb = $prob->symb();
  763:         my %analysis = &Apache::lonstathelpers::get_problem_data($prob->src);
  764:         $problem_analysis{$prob->src}=\%analysis;
  765:         foreach my $partid (@{$prob->parts}) {
  766:             if (($prob->is_anonsurvey($partid)) || ($anoncounter->{$symb."\0".$partid})) {
  767:                 next if ($show_named);
  768:             } else {
  769:                 next unless ($show_named);
  770:             }
  771: 
  772:             my $responses = [$prob->responseIds($partid)];
  773:             my $resptypes = [$prob->responseType($partid)];
  774:             for (my $i=0;$i<scalar(@$responses);$i++) {
  775:                 my @headers = &get_headers($prob,$partid,$responses->[$i],
  776:                                            $resptypes->[$i],
  777:                                            $problem_analysis{$prob->src},
  778:                                            'excel','display',
  779:                                            @extra_resp_headers);
  780:                 $columncount += scalar(@headers);
  781:             }
  782:         }
  783:         last if ($columncount > 255);
  784:         $lastprob = $prob;
  785:     }
  786:     if ($columncount > 255) {
  787:         $r->print('<h1>'.&mt('Unable to complete request').'</h1>'.$/.
  788:                   '<p>'.&mt('LON-CAPA is unable to produce your Excel spreadsheet because your selections will result in more than 255 columns.  Excel allows only 255 columns in a spreadsheet.').'</p>'.$/.
  789:                   '<p>'.&mt('Consider selecting fewer problems to generate reports on, or reducing the number of items per problem.  Or use HTML or CSV output.').'</p>'.$/);
  790:         if (ref($lastprob)) {
  791:             $r->print('<p>'.&mt('The last problem that will fit in the current spreadsheet is [_1].',$lastprob->compTitle).'</p>');
  792:         }
  793:         $r->rflush();
  794:         return;
  795:     }
  796:     #
  797:     # Print out a message telling them what we are doing
  798:     if (scalar(@$Problems) > 1) {
  799:         $r->print('<h2>'.
  800:                   &mt('Preparing Excel spreadsheet of student responses to [_1] problems',
  801:                       scalar(@$Problems)).
  802:                   '</h2>');
  803:     } else {
  804:         $r->print('<h2>'.
  805:                   &mt('Preparing Excel spreadsheet of student responses').
  806:                   '</h2>');
  807:     }
  808:     $r->rflush();
  809:     #
  810:     # Create the excel spreadsheet
  811:     my ($workbook,$filename,$format) = 
  812:         &Apache::loncommon::create_workbook($r);
  813:     return if (! defined($workbook));
  814:     my $worksheet  = $workbook->addworksheet('Student Submission Data');
  815:     #
  816:     # Add headers to the worksheet
  817:     my $rows_output = 0;
  818:     $worksheet->write($rows_output++,0,
  819:                     $env{'course.'.$env{'request.course.id'}.'.description'},
  820:                       $format->{'h1'});
  821:     $rows_output++;
  822:     my $cols_output = 0;
  823:     my $title_row  = $rows_output++;
  824:     my $partid_row = $rows_output++;
  825:     my $respid_row = $rows_output++;
  826:     my $header_row = $rows_output++;
  827:     $worksheet->write($title_row ,0,'Problem Title',$format->{'bold'});
  828:     $worksheet->write($partid_row,0,'Part ID',$format->{'bold'});
  829:     $worksheet->write($respid_row,0,'Response ID',$format->{'bold'});
  830:     # Student headers
  831:     my @StudentColumns = &get_student_columns($show_named);
  832:     foreach my $field (@StudentColumns) {
  833:         $worksheet->write($header_row,$cols_output++,ucfirst($field),
  834:                           $format->{'bold'});
  835:     }
  836:     # Problem headers
  837:     my %start_col;
  838:     foreach my $prob (@$Problems) {
  839:         my $title = $prob->compTitle;
  840:         my $symb = $prob->symb();
  841:         $worksheet->write($title_row,$cols_output,
  842:                           $title,$format->{'h3'});
  843:         foreach my $partid (@{$prob->parts}) {
  844:             if (($prob->is_anonsurvey($partid)) || ($anoncounter->{$symb."\0".$partid})) {
  845:                 next if ($show_named);
  846:             } else {
  847:                 next unless ($show_named);
  848:             }
  849:             $worksheet->write($partid_row,$cols_output,
  850:                               $prob->part_display($partid));
  851:             my $responses = [$prob->responseIds($partid)];
  852:             my $resptypes = [$prob->responseType($partid)];
  853:             for (my $i=0;$i<scalar(@$responses);$i++) {
  854:                 $start_col{$prob->symb}->{$partid}->{$responses->[$i]}=
  855:                     $cols_output;
  856:                 $worksheet->write($respid_row,$cols_output,
  857:                                   $resptypes->[$i].', '.$responses->[$i]);
  858:                 my @headers = &get_headers($prob,$partid,$responses->[$i],
  859:                                            $resptypes->[$i],
  860:                                            $problem_analysis{$prob->src},
  861:                                            'excel','display',
  862:                                            @extra_resp_headers);
  863:                 foreach my $text (@headers) {
  864:                     if ($text eq 'Time') {
  865:                         $worksheet->set_column($cols_output,$cols_output,undef,
  866:                                                $format->{'date'});
  867:                     } 
  868:                     $worksheet->write($header_row,$cols_output++,$text);
  869:                 }
  870:             }
  871:         }
  872:     }
  873:     #
  874:     # Populate the worksheet with the student data
  875:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  876:         ($r,'Excel File Compilation Status',
  877:          'Excel File Compilation Progress', 
  878:          scalar(@$Students),'inline',undef,'Statistics','stats_status');
  879:     my $max_row = $rows_output;
  880:     foreach my $student (@$Students) {
  881:         last if ($c->aborted());
  882:         $cols_output = 0;
  883:         my $student_row = $max_row;
  884:         foreach my $prob (@$Problems) {
  885:             my $symb = $prob->symb();
  886:             foreach my $partid (@{$prob->parts}) {
  887:                 if (($prob->is_anonsurvey($partid)) || ($anoncounter->{$symb."\0".$partid})) {
  888:                     next if ($show_named);
  889:                 } else {
  890:                     next unless ($show_named);
  891:                 }
  892:                 my @Response = $prob->responseIds($partid);
  893:                 my @ResponseType = $prob->responseType($partid);
  894:                 for (my $i=0;$i<=$#Response;$i++) {
  895:                     my $respid   = $Response[$i];
  896:                     my $resptype = $ResponseType[$i];
  897:                     my $results = 
  898:                         &Apache::loncoursedata::get_response_data_by_student
  899:                         ($student,$prob->symb(),$respid);
  900:                     my @headers = &get_headers($prob,$partid,$respid,
  901:                                                $resptype,
  902:                                                $problem_analysis{$prob->src},
  903:                                                'excel','normal',
  904:                                                @extra_resp_headers);
  905: 
  906:                     if (! defined($results)) {
  907:                         $results = [];
  908:                     }
  909:                     #
  910:                     $rows_output = $student_row;
  911:                     #
  912:                     my $response_start_col = $start_col{$prob->symb}->{$partid}->{$respid};
  913:                     for (my $j=scalar(@$results)-1;$j>=0;$j--) {
  914:                         $cols_output = $response_start_col;
  915:                         if ($env{'form.all_sub'} ne 'true') {
  916:                             next if ($j ne scalar(@$results)-1);
  917:                         }
  918:                         my $response = &hashify_response($results->[$j],
  919:                                                          $prob,
  920:                                                          $student,
  921:                                                          $partid,
  922:                                                          $respid);
  923:                         my @response_data = 
  924:                             &compile_response_data(\@headers,$response,
  925:                                                    $prob,$partid,$respid,
  926:                                                    $resptype,
  927:                                                    \&excel_format_item);
  928:                         $worksheet->write_row($rows_output++,$cols_output,
  929:                                               \@response_data);
  930:                         $cols_output+=scalar(@response_data);
  931:                         if ($rows_output > $max_row) {
  932:                             $max_row = $rows_output;
  933:                         }
  934:                     }
  935:                 }
  936:             }
  937:         }
  938:         # Prepend current student's user information to all rows  
  939:         for (my $row = $student_row;$row<$max_row;$row++) {
  940:             my $cols = 0;
  941:             foreach my $field (@StudentColumns) {
  942:                 if ($show_named) {
  943:                     my $value = $student->{$field};
  944:                     if ($field eq 'comments') {
  945:                         $value = &Apache::lonmsgdisplay::retrieve_instructor_comments
  946:                                  ($student->{'username'},$student->{'domain'});
  947:                     }
  948:                     $worksheet->write($row,$cols++,$value);
  949:                 } else {
  950:                     $worksheet->write($row,$cols++,
  951:                                       &mt('Anonymized'));
  952:                 }
  953:             }
  954:         }
  955:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  956:                                                  'last student');
  957:     }
  958:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  959:     #
  960:     # Close the excel file
  961:     $workbook->close();
  962:     #
  963:     # Write a link to allow them to download it
  964:     $r->print('<p><a href="'.$filename.'">'.
  965:               &mt('Your Excel spreadsheet.').
  966:               '</a></p>'."\n");
  967:     $r->print('<script>'.
  968:               'window.document.Statistics.stats_status.value="'.
  969:               'Done compiling spreadsheet.  See link below to download.'.
  970:               '";</script>');
  971:     $r->rflush();
  972:     return;
  973: }
  974: 
  975: sub compile_response_data {
  976:     my ($headers,$response,$prob,$partid,$respid,$resptype,$format) = @_;
  977:     if (! ref($headers) || ref($headers) ne 'ARRAY' || ! scalar(@$headers)) {
  978:         return ();
  979:     }
  980:     if (ref($format) ne 'CODE') {
  981:         $format = sub { return $_[0]; };
  982:     }
  983:     #
  984:     my $submission = 
  985:         &HTML::Entities::decode
  986:         (&unescape($response->{'Submission'}));
  987:     if (!$prob->is_task()) {
  988: 	return () if (! defined($submission) || $submission eq '');
  989:     }
  990:     $submission =~ s/\\\"/\"/g;
  991:     $submission =~ s/\\\'/\'/g;
  992:     if ($resptype eq 'radiobutton') {
  993:         $submission =~ s/=([^=])$//;
  994:     }
  995:     $response->{'Submission'} = $submission;
  996:     #
  997:     my @values;
  998:     if ($resptype =~ /^(option|match|rank)$/) {
  999:         my %submission = 
 1000:             map { 
 1001:                 my ($foil,$value) = split('=',&unescape($_));
 1002:                 ($foil,$value);
 1003:             } split('&',$response->{'Submission'});
 1004:         my %correct;
 1005:         if (exists($response->{'Correct'})) {
 1006:             %correct = 
 1007:                 map { 
 1008:                     my ($foil,$value)=split('=',&unescape($_));
 1009:                     ($foil,$value);
 1010:                 } split('&',$response->{'Correct'});
 1011:         }
 1012:         #
 1013:         foreach my $original_header (@$headers) {
 1014:             if ($original_header =~ /^_/) {
 1015:                 # '_' denotes a foil column
 1016:                 my ($header) = ($original_header =~ m/^_(.*)$/);
 1017:                 my $option = '';
 1018:                 if ( my ($foil) = ($header =~ /(.*) Correct$/)) {
 1019:                     if (exists($correct{$foil})) {
 1020:                         $option = $correct{$foil};
 1021:                     }
 1022:                 } elsif (exists($submission{$header})) {
 1023:                     $option = $submission{$header};
 1024:                 }
 1025:                 push(@values,&{$format}($option,$header));
 1026:             } else {
 1027:                 # A normal column
 1028:                 push(@values,&{$format}($response->{$original_header},
 1029:                                         $original_header));
 1030:             }
 1031:         }
 1032:     } else {
 1033:         @values = map { &{$format}($response->{$_},$_); } @$headers;
 1034:     }
 1035:     return @values;
 1036: }
 1037: 
 1038: sub excel_format_item {
 1039:     my ($item,$type) = @_;
 1040:     if ($type eq 'Time') {
 1041:         $item = &Apache::lonstathelpers::calc_serial($item);
 1042:     } else {
 1043:         if ($item =~ m/^=/) {
 1044:             $item = ' '.$item;
 1045:         }
 1046:         $item =~ s/\\r//g;
 1047:         $item =~ s/\\n/\n/g;
 1048:         $item =~ s/(\s*$|^\s*)//g;
 1049:         $item =~ s/\\\'/\'/g;
 1050:     }
 1051:     return $item;
 1052: }
 1053: 
 1054: #########################################################
 1055: #########################################################
 1056: ##
 1057: ##      CSV output of student answers
 1058: ##
 1059: #########################################################
 1060: #########################################################
 1061: sub prepare_csv_output {
 1062:     my ($r,$problems,$students,$anoncounter,$show_named) = @_;
 1063:     my $c = $r->connection();
 1064:     #
 1065:     $r->print('<h2>'.
 1066:               &mt('Generating CSV report of student responses').'</h2>');
 1067:     #
 1068:     # Progress window
 1069:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1070:         ($r,'CSV File Compilation Status',
 1071:          'CSV File Compilation Progress', 
 1072:          scalar(@$students),'inline',undef,'Statistics','stats_status');
 1073:     
 1074:     $r->rflush();
 1075:     #
 1076:     # Open a file
 1077:     my $outputfile;
 1078:     my $filename = '/prtspool/'.
 1079:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
 1080:             time.'_'.rand(1000000000).'.csv';
 1081:     unless ($outputfile = Apache::File->new('>/home/httpd'.$filename)) {
 1082:         $r->log_error("Couldn't open $filename for output $!");
 1083:         $r->print(
 1084:             '<p class="LC_error">'
 1085:            .&mt('Problems occurred in writing the CSV file.')
 1086:            .' '.&mt('This error has been logged.')
 1087:            .' '.&mt('Please alert your LON-CAPA administrator.')
 1088:            .'</p>'
 1089:         );
 1090:         $outputfile = undef;
 1091:     }
 1092:     #
 1093:     # Compute the number of columns per response
 1094:     my @extra_resp_headers = &get_extra_response_headers($show_named);
 1095:     #
 1096:     # Create the table header
 1097:     my @student_columns = &get_student_columns($show_named);
 1098:     my $student_column_count = scalar(@student_columns);
 1099:     #
 1100:     my %headers;
 1101:     push(@{$headers{'student'}},@student_columns);
 1102:     # Pad for the student data
 1103:     foreach my $row ('problem','part','response') {
 1104:         $headers{$row}=[map {''} @student_columns];
 1105:     }
 1106:     #
 1107:     # we put the headers into the %headers hash
 1108:     my %problem_analysis;
 1109:     my %start_col;
 1110:     my $max_column = $student_column_count;
 1111:     foreach my $prob (@$problems) {
 1112:         my $symb = $prob->symb();
 1113:         my %analysis = &Apache::lonstathelpers::get_problem_data($prob->src);
 1114:         $problem_analysis{$prob->src}=\%analysis;
 1115:         $headers{'problem'}->[$max_column] = $prob->compTitle;
 1116:         foreach my $partid (@{$prob->parts}) {
 1117:             if (($prob->is_anonsurvey($partid)) || ($anoncounter->{$symb."\0".$partid})) {
 1118:                 next if ($show_named);
 1119:             } else {
 1120:                 next unless ($show_named);
 1121:             }
 1122:             $headers{'part'}->[$max_column] = $prob->part_display($partid);
 1123:             my $responses = [$prob->responseIds($partid)];
 1124:             my $resptypes = [$prob->responseType($partid)];
 1125:             for (my $i=0;$i<scalar(@$responses);$i++) {
 1126:                 my @headers = &get_headers($prob,$partid,$responses->[$i],
 1127:                                            $resptypes->[$i],
 1128:                                            $problem_analysis{$prob->src},
 1129:                                            'csv','display',
 1130:                                            @extra_resp_headers);
 1131:                 $start_col{$prob->symb}->{$partid}->{$responses->[$i]}=
 1132:                     $max_column;
 1133:                 $headers{'response'}->[$max_column]=
 1134:                     &mt('Response [_1]',$responses->[$i]);
 1135:                 for (my $j=0;$j<=$#headers;$j++) {
 1136:                     $headers{'student'}->[$max_column+$j]=$headers[$j];
 1137:                 }
 1138:                 $max_column += scalar(@headers);
 1139:             }
 1140:         }
 1141:     }
 1142:     foreach my $row ('problem','part','response','student') {
 1143:         print $outputfile '"'.
 1144:             join('","',
 1145:                  map { 
 1146:                      &Apache::loncommon::csv_translate($_); 
 1147:                  } @{$headers{$row}}).'"'.$/;
 1148:     }
 1149:     #
 1150:     # Main loop
 1151:     foreach my $student (@$students) {
 1152:         last if ($c->aborted());
 1153:         my @rows;
 1154:         foreach my $prob (@$problems) {
 1155:             my $symb = $prob->symb;
 1156:             foreach my $partid (@{$prob->parts}) {
 1157:                 if (($prob->is_anonsurvey($partid)) || ($anoncounter->{$symb."\0".$partid})) {
 1158:                     next if ($show_named); 
 1159:                 } else {
 1160:                     next unless ($show_named);
 1161:                 }
 1162:                 my @responses = $prob->responseIds($partid);
 1163:                 my @response_type = $prob->responseType($partid);
 1164:                 for (my $i=0;$i<=$#responses;$i++) {
 1165:                     my $respid   = $responses[$i];
 1166:                     my $resptype = $response_type[$i];
 1167:                     my @headers = &get_headers($prob,$partid,$respid,$resptype,
 1168:                                                $problem_analysis{$prob->src},
 1169:                                                'csv','normal',
 1170:                                                @extra_resp_headers);
 1171:                     my $results = 
 1172:                         &Apache::loncoursedata::get_response_data_by_student
 1173:                         ($student,$prob->symb(),$respid);
 1174:                     if (! defined($results)) {
 1175:                         $results = [];
 1176:                     }
 1177:                     for (my $j=0; $j<scalar(@$results);$j++) {
 1178:                         if ($env{'form.all_sub'} ne 'true') {
 1179:                             next if ($j != 0);
 1180:                         }
 1181:                         my $idx = scalar(@$results) - $j - 1;
 1182:                         my $response = &hashify_response($results->[$idx],
 1183:                                                          $prob,$student,
 1184:                                                          $partid,$respid);
 1185:                         my @data = &compile_response_data(\@headers,$response,
 1186:                                                           $prob,$partid,
 1187:                                                           $respid,$resptype,
 1188:                                                           \&csv_format_item);
 1189:                         my $resp_start_idx =
 1190:                             $start_col{$prob->symb}->{$partid}->{$respid};
 1191:                         for (my $k=0;$k<=$#data;$k++) {
 1192:                             $rows[$j]->[$resp_start_idx + $k] = $data[$k];
 1193:                         }
 1194:                     }
 1195:                 }
 1196:             }
 1197:         }
 1198:         foreach my $row (@rows) {
 1199:             my $student_row_data = '';
 1200:             if ($show_named) {
 1201:                 foreach my $field (@student_columns) {
 1202:                     my $value = $student->{$field};
 1203:                     if ($field eq 'comments') {
 1204:                         $value = &Apache::lonmsgdisplay::retrieve_instructor_comments
 1205:                                  ($student->{'username'},$student->{'domain'});
 1206:                     }
 1207:                     $student_row_data .= '"'.&Apache::loncommon::csv_translate($value).'",';
 1208:                 }
 1209:                 $student_row_data =~ s/,$//;
 1210:             } else {
 1211:                 $student_row_data = '"'.&mt('Anonymized').'"';
 1212:             }
 1213:             print $outputfile $student_row_data;
 1214:             for (my $i=$student_column_count;$i<$max_column;$i++) {
 1215:                 my $value = &Apache::loncommon::csv_translate($row->[$i]);
 1216:                 $value ||='';
 1217:                 print $outputfile ',"'.$value.'"';
 1218:             }
 1219:             print $outputfile $/;
 1220:         }
 1221:         undef(@rows);
 1222:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 1223:                                                  'last student');
 1224:     }
 1225:     close($outputfile);
 1226:     #
 1227:     # Close the progress window
 1228:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1229:     #
 1230:     # Tell the user where to get their CSV file
 1231:     $r->print('<br />'.
 1232:               '<a href="'.$filename.'">'.&mt('Your CSV file.').'</a>'."\n");
 1233:     $r->rflush();
 1234:     return;
 1235: }
 1236: 
 1237: sub csv_format_item {
 1238:     my ($item,$type) = @_;
 1239:     if ($type eq 'Time') {
 1240:         $item = localtime($item);
 1241:     }
 1242:     $item =&Apache::loncommon::csv_translate($item); 
 1243:     return $item;
 1244: }
 1245: 
 1246: #########################################################
 1247: #########################################################
 1248: ##
 1249: ##   Generic Interface Routines
 1250: ##
 1251: #########################################################
 1252: #########################################################
 1253: sub CreateInterface {
 1254:     ##
 1255:     ## Output Selection
 1256:     my $output_selector = $/.'<select name="output">'.$/;
 1257:     foreach ('HTML','Excel','CSV') {
 1258:         $output_selector .= '    <option value="'.lc($_).'"';
 1259:         if ($env{'form.output'} eq lc($_)) {
 1260:             $output_selector .= ' selected="selected"';
 1261:         }
 1262:         $output_selector .='>'.&mt($_).'</option>'.$/;
 1263:     } 
 1264:     $output_selector .= '</select>'.$/;
 1265:     ##
 1266:     ## Environment variable initialization
 1267:     my $Str = '';
 1268:     $Str .= &Apache::lonhtmlcommon::breadcrumbs('Student Submission Reports');
 1269:     $Str .= '<br />';
 1270:     $Str .= &Apache::loncommon::start_data_table();
 1271:     $Str .= &Apache::loncommon::start_data_table_header_row();
 1272:     $Str .= '<th>'.&mt('Sections').'</th>';
 1273:     $Str .= '<th>'.&mt('Groups').'</th>';
 1274:     $Str .= '<th>'.&mt('Student Data').&Apache::loncommon::help_open_topic("Chart_Student_Data").'</th>';
 1275:     $Str .= '<th>'.&mt('Access Status').'</th>';
 1276:     $Str .= '<th>'.&mt('Options').'</th>';
 1277:     $Str .= '<th>'.&mt('Output Format').'</th>';
 1278:     $Str .= &Apache::loncommon::end_data_table_header_row();
 1279:     #
 1280:     $Str .= &Apache::loncommon::start_data_table_row();
 1281:     $Str .= '<td align="center">'."\n";
 1282:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
 1283:     $Str .= '</td>';
 1284:     #
 1285:     $Str .= '<td align="center">'."\n";
 1286:     $Str .= &Apache::lonstatistics::GroupSelect('Group','multiple',5);
 1287:     $Str .= '</td>';
 1288:     #
 1289:     $Str .= '<td align="center">'."\n";
 1290:     $Str .= &Apache::lonstatistics::StudentDataSelect('StudentData','multiple', 5,undef);
 1291:     $Str .= '</td>';
 1292:     #
 1293:     $Str .= '<td align="center">';
 1294:     $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
 1295:     $Str .= '</td>';
 1296:     #
 1297:     # Render problem checkbox
 1298:     my $prob_checkbox = '<input type="checkbox" name="renderprob" ';
 1299:     if (exists($env{'form.renderprob'}) && $env{'form.renderprob'} eq 'true') {
 1300:         $prob_checkbox .= 'checked="checked" ';
 1301:     }
 1302:     $prob_checkbox .= 'value="true" />';
 1303:     #
 1304:     # Compute correct answers checkbox
 1305:     my $ans_checkbox = '<input type="checkbox" name="correctans" ';
 1306:     if (exists($env{'form.correctans'}) && $env{'form.correctans'} eq 'true') {
 1307:         $ans_checkbox .= 'checked="checked" ';
 1308:     }
 1309:     $ans_checkbox .= 'value="true" />';
 1310:     #
 1311:     # Show all submissions checkbox
 1312:     my $all_sub_checkbox = '<input type="checkbox" name="all_sub" ';
 1313:     if (exists($env{'form.all_sub'}) && 
 1314:         $env{'form.all_sub'} eq 'true') {
 1315:         $all_sub_checkbox .= 'checked="checked" ';
 1316:     }
 1317:     $all_sub_checkbox.= 'value="true" />';
 1318:     #
 1319:     # problem status checkbox
 1320:     my $prob_status_checkbox = '<input type="checkbox" name="prob_status" ';
 1321:     if (exists($env{'form.prob_status'}) && 
 1322:         $env{'form.prob_status'} eq 'true') {
 1323:         $prob_status_checkbox .= 'checked="checked" ';
 1324:     }
 1325:     $prob_status_checkbox .= 'value="true" />';
 1326:     #
 1327:     $Str .=
 1328:         '<td valign="top">'
 1329:        .'<label>'
 1330:        .$prob_checkbox.&mt('Show problem')
 1331:        .'</label><br />'
 1332:        .'<label>'
 1333:        .' '.$ans_checkbox.&mt('Show correct answers')
 1334:        .'</label><br />'
 1335:        .'<label>'
 1336:        .$all_sub_checkbox.&mt('Show all submissions')
 1337:        .'</label><br />'
 1338:        .'<label>'
 1339:        .$prob_status_checkbox.&mt('Show problem grading')
 1340:        .'</label>'
 1341:        .'</td>';
 1342:     #
 1343:     $Str .= '<td align="center" valign="top">'.$output_selector.'</td>';
 1344:     #
 1345:     $Str .= &Apache::loncommon::end_data_table_row();
 1346:     $Str .= &Apache::loncommon::end_data_table();
 1347:     #
 1348:     $Str .= '<p><span class="LC_nobreak">'
 1349:            .&mt('Status: [_1]',
 1350:                     '<input type="text" name="stats_status"'
 1351:                    .' size="60" value="" readonly="readonly" />')
 1352:            .'</span></p>';
 1353:     ##
 1354:     return $Str;
 1355: }
 1356: 
 1357: sub get_student_columns {
 1358:     my ($show_named) = @_;
 1359:     my @student_columns;
 1360:     if ($show_named) {
 1361:         @student_columns = @Apache::lonstatistics::SelectedStudentData;
 1362:         if (grep(/^all$/,@student_columns)) {
 1363:             @student_columns = qw(fullname username domain id section status groups comments);
 1364:         }
 1365:     } else {
 1366:         @student_columns = ('username');
 1367:     }
 1368:     return @student_columns;
 1369: }
 1370: 
 1371: 1;
 1372: 
 1373: __END__

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>