File:  [LON-CAPA] / loncom / interface / statistics / lonstudentsubmissions.pm
Revision 1.60: download - view: text, annotated - select for diffs
Wed Aug 4 01:56:07 2010 UTC (13 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6119.
  - identifying information about user not displayed for problem parts
    with type set to anonymous survey (with/without credit).
  - all items must be either anonymous survey items, or named items
    when displaying submissions for selected items.
  - rows of students is randomized when showing rows of submission data
    for anonymous survey items.

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

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