File:  [LON-CAPA] / loncom / interface / statistics / lonstudentsubmissions.pm
Revision 1.63: download - view: text, annotated - select for diffs
Mon Sep 19 04:02:20 2011 UTC (12 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_10_X, HEAD
- Bug 6243.
  - Delay writing student name information in initial column(s) in a row,
    until results got from loncoursedata::get_response_data_by_student()
    for the student.
  - Avoid incomplete last row for a student without submissions.
  - Remove unused scalar: $last_student_col (last used in rev 1.30).

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

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