File:  [LON-CAPA] / loncom / interface / statistics / lonstudentsubmissions.pm
Revision 1.29: download - view: text, annotated - select for diffs
Mon Dec 6 16:53:39 2004 UTC (19 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: version_1_3_X, version_1_3_3, version_1_3_2, version_1_3_1, version_1_3_0, version_1_2_99_1, HEAD
Unescape results in csv output.

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstudentsubmissions.pm,v 1.29 2004/12/06 16:53:39 matthew 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: 
   41: my @SubmitButtons = ({ name => 'SelectAnother',
   42:                        text => 'Choose a different Problem' },
   43:                      { name => 'Generate',
   44:                        text => 'Generate Report'},
   45:                      );
   46: 
   47: sub BuildStudentSubmissionsPage {
   48:     my ($r,$c)=@_;
   49:     #
   50:     my %Saveable_Parameters = ('Status' => 'scalar',
   51:                                'Section' => 'array',
   52:                                'NumPlots' => 'scalar',
   53:                                );
   54:     &Apache::loncommon::store_course_settings('student_submissions',
   55:                                               \%Saveable_Parameters);
   56:     &Apache::loncommon::restore_course_settings('student_submissions',
   57:                                                 \%Saveable_Parameters);
   58:     #
   59:     &Apache::lonstatistics::PrepareClasslist();
   60:     #
   61:     $r->print(&CreateInterface());
   62:     #
   63:     my @Students = @Apache::lonstatistics::Students;
   64:     #
   65:     if (@Students < 1) {
   66:         $r->print('<h2>There are no students in the sections selected</h2>');
   67:     }
   68:     #
   69:     my @CacheButtonHTML = 
   70:         &Apache::lonstathelpers::manage_caches($r,'Statistics','stats_status',
   71:                                    '<h3>'.&mt('Loading student data').'</h3>');
   72:     $r->rflush();
   73:     #
   74:     if (exists($ENV{'form.problemchoice'}) && 
   75:         ! exists($ENV{'form.SelectAnother'})) {
   76:         foreach my $button (@SubmitButtons) {
   77:             if ($button->{'name'} eq 'break') {
   78:                 $r->print("<br />\n");
   79:             } else {
   80:                 $r->print('<input type="submit" name="'.$button->{'name'}.'" '.
   81:                           'value="'.&mt($button->{'text'}).'" />');
   82:                 $r->print('&nbsp;'x5);
   83:             }
   84:         }
   85:         foreach my $html (@CacheButtonHTML) {
   86:             $r->print($html.('&nbsp;'x5));
   87:         }
   88:         #
   89:         $r->print('<hr />'.$/);
   90:         $r->rflush();
   91:         #
   92:         # Determine which problems we are to analyze
   93:         my @Symbs = 
   94:             &Apache::lonstathelpers::get_selected_symbs('problemchoice');
   95:         foreach my $selected (@Symbs) {
   96:             $r->print('<input type="hidden" name="problemchoice" value="'.
   97:                       $selected.'" />'.$/);
   98:         }
   99:         #
  100:         # Get resource objects
  101:         my $navmap = Apache::lonnavmaps::navmap->new();
  102:         if (!defined($navmap)) {
  103:             $r->print('<h1>'.&mt("Internal error").'</h1>');
  104:             return;
  105:         }
  106:         my %already_seen;
  107:         my @Problems;
  108:         foreach my $symb (@Symbs) {
  109:             my $resource = $navmap->getBySymb($symb);
  110:             push(@Problems,$resource);
  111:         }
  112:         # 
  113:         if (! scalar(@Problems) || ! defined($Problems[0])) {
  114:             $r->print('resource is undefined');
  115:         } else {
  116:             if (scalar(@Problems) == 1) {
  117:                 my $resource = $Problems[0];
  118:                 $r->print('<h1>'.$resource->title.'</h1>');
  119:                 $r->print('<h3>'.$resource->src.'</h3>');
  120:                 if ($ENV{'form.renderprob'} eq 'true') {
  121:                     $r->print(
  122:                               &Apache::lonstathelpers::render_resource({src => $resource->src})
  123:                               );
  124:                     $r->rflush();
  125:                 }
  126:             }
  127:             if ($ENV{'form.output'} eq 'excel') {
  128:                 &prepare_excel_output($r,\@Problems,\@Students);
  129:             } elsif ($ENV{'form.output'} eq 'csv') {
  130:                 &prepare_csv_output($r,\@Problems,\@Students);
  131:             } else {
  132:                 &prepare_html_output($r,\@Problems,\@Students);
  133:             }
  134:         }
  135:         $r->print('<hr />');
  136:     } else {
  137:         $r->print('<input type="submit" name="Generate" value="'.
  138:                   &mt('Prepare Report').'" />');
  139:         $r->print('&nbsp;'x5);
  140:         $r->print('<p>'.
  141:                   &mt('Computing correct answers greatly increasese the amount of time required to prepare a report.').
  142:                   '</p>');
  143:         $r->print('<p>'.
  144:                   &mt('please select problems and use the <b>Prepare Report</b> button to continue.').
  145:                   '</p>');
  146:         $r->print(&Apache::lonstathelpers::MultipleProblemSelector
  147:                   (undef,'problemchoice','Statistics'));
  148:     }
  149: }
  150: 
  151: #########################################################
  152: #########################################################
  153: ##
  154: ##    HTML Output Routines
  155: ##
  156: #########################################################
  157: #########################################################
  158: sub prepare_html_output {
  159:     my ($r,$problems,$students) = @_;
  160:     my $c = $r->connection();
  161:     #
  162:     # Set a flag for the case when there is just one problem
  163:     my $single_response = 0;
  164:     if (scalar(@$problems) == 1 &&
  165:         $problems->[0]->countResponses == 1) {
  166:         $single_response = 1;
  167:     }
  168:     #
  169:     # Compute the number of columns per response
  170:     my @response_headers = ('Submission');
  171:     if ($ENV{'form.correctans'} eq 'true') {
  172:         push(@response_headers,'Correct');
  173:     } 
  174:     if ($ENV{'form.prob_status'} eq 'true') {
  175:         push(@response_headers,'Award Detail'); 
  176:         push(@response_headers,'Time');
  177:         push(@response_headers,'Attempt');
  178:         push(@response_headers,'Awarded');
  179:     }
  180:     my $response_multiplier = scalar(@response_headers);
  181:     #
  182:     # Create the table header
  183:     my @student_columns = ('username','domain','id');
  184:     #
  185:     my %headers;
  186:     my $student_column_count = scalar(@student_columns);
  187:     $headers{'problem'} = qq{<th colspan="$student_column_count">\&nbsp;</th>};
  188:     foreach (@student_columns) {
  189:         $headers{'student'}.= '<th>'.ucfirst($_).'</th>';
  190:     }
  191:     #
  192:     # we put the headers into the %headers hash
  193:     my $total_col = scalar(@student_columns);
  194:     my $nonempty_part_headers = 0;
  195:     foreach my $prob (@$problems) {
  196:         my $prob_span = 0;
  197:         my $single_part = 0;
  198:         if (scalar(@{$prob->parts}) == 1) {
  199:             $single_part = 1;
  200:         }
  201:         foreach my $partid (@{$prob->parts}) {
  202:             my $part_span = 0;
  203:             my $responses = [$prob->responseIds($partid)];
  204:             my $resptypes = [$prob->responseType($partid)];
  205:             for (my $i=0;$i<scalar(@$responses);$i++) {
  206:                 if ($resptypes->[$i] eq 'essay') {
  207:                     # do something clever, like shut up.
  208:                 } else {
  209:                     $total_col += scalar(@response_headers);
  210:                     $headers{'response'} .=
  211:                         '<th colspan="'.scalar(@response_headers).'">'.
  212:                         &mt('Response [_1]',$responses->[$i]).'</th>';
  213:                     $headers{'student'}.= '<th>'.join('</th><th>',
  214:                                                       @response_headers).
  215:                                                           '</th>';
  216:                     $part_span += scalar(@response_headers);
  217:                 }
  218:             }
  219:             if (! $single_part) {
  220:                 my $tmpname = $partid;
  221:                 if ($partid =~/^\d+$/) {
  222:                     $tmpname = $prob->part_display($partid);
  223:                 }
  224:                 $headers{'part'} .= qq{<th colspan="$part_span">$tmpname</th>};
  225:                 $nonempty_part_headers = 1;
  226:             } else {
  227:                 $headers{'part'} .= qq{<th colspan="$part_span">&nbsp</th>};
  228:             }
  229:             $prob_span += $part_span;
  230:         }
  231:         my $title = $prob->compTitle;
  232:         if ($prob_span > 0) {
  233:             $headers{'problem'}.= qq{<th colspan="$prob_span">$title</th>};
  234:         } elsif ($single_response) {
  235:             $prob_span = scalar(@student_columns);
  236:             $headers{'problem'} = qq{<th colspan="$prob_span">$title</th>};
  237:         }
  238:     }
  239:     if (exists($headers{'part'})) {
  240:         $headers{'part'} = qq{<th colspan="$student_column_count">\&nbsp;</th>}.
  241:             $headers{'part'};
  242:     }
  243:     if (exists($headers{'response'})) {
  244:         $headers{'response'}=
  245:             qq{<th colspan="$student_column_count">\&nbsp;</th>}.
  246:             $headers{'response'};
  247:     }
  248:     my $full_header = $/.'<table>'.$/;
  249:     $full_header .= '<tr align="left">'.$headers{'problem'}.'</tr>'.$/;
  250:     if ($nonempty_part_headers) {
  251:         $full_header .= '<tr align="left">'.$headers{'part'}.'</tr>'.$/;
  252:     }
  253:     $full_header .= '<tr align="left">'.$headers{'response'}.'</tr>'.$/;
  254:     $full_header .= '<tr align="left">'.$headers{'student'}.'</tr>'.$/;
  255:     #
  256:     # Main loop
  257:     my $count;
  258:     $r->print($/.$full_header.$/);
  259:     my $row_class = 'odd';   # css 
  260:     foreach my $student (@$students) {
  261:         my $student_row_data;
  262:         if ($count++ >= 30) {
  263:             $r->print('</table>'.$/.$full_header.$/);
  264:             $count = 0;
  265:         }
  266:         last if ($c->aborted());
  267:         foreach my $field (@student_columns) {
  268:             $student_row_data .= 
  269:                 '<td valign="top">'.$student->{$field}.'</td>';
  270:         }
  271:         #
  272:         # Figure out what it is we need to output for this student
  273:         my @essays;
  274:         my %problem_data;
  275:         my $maxrow;
  276:         foreach my $prob (@$problems) {
  277:             my $symb = $prob->symb;
  278:             $problem_data{$symb}={};
  279:             foreach my $partid (@{$prob->parts}) {
  280:                 my @responses = $prob->responseIds($partid);
  281:                 my @response_type = $prob->responseType($partid);
  282:                 for (my $i=0;$i<=$#responses;$i++) {
  283:                     my $respid   = $responses[$i];
  284:                     my $resptype = $response_type[$i];
  285:                     my $width = scalar(@response_headers);
  286:                     $problem_data{$symb}->{$partid}->{$respid}={};
  287:                     my $resp_data = $problem_data{$symb}->{$partid}->{$respid};
  288:                     $resp_data->{'fake'} = qq{<td colspan="$width">&nbsp</td>};
  289:                     my $results = 
  290:                         &Apache::loncoursedata::get_response_data_by_student
  291:                         ($student,$prob->symb(),$respid);
  292:                     if (! defined($results)) {
  293:                         $results = [];
  294:                     }
  295:                     #
  296:                     if (scalar(@$results) > $maxrow && $resptype ne 'essay') {
  297:                         $maxrow = scalar(@$results);
  298:                     }
  299:                     for (my $j=scalar(@$results)-1;$j>=0;$j--) {
  300:                         my $response = $results->[$j];
  301:                         if ($ENV{'form.all_sub'} ne 'true') {
  302:                             next if ($j ne scalar(@$results)-1);
  303:                         }
  304:                         if ($resptype eq 'essay') {
  305:                             push(@essays,
  306:                                  &html_essay_results($student,
  307:                                                      $prob,$partid,$respid,
  308:                                                      $response,
  309:                                                      $single_response).
  310:                                  '</td>');
  311:                         } else {
  312:                             push(@{$resp_data->{'real'}},
  313:                                  &html_results($student,
  314:                                                $prob,$partid,$respid,
  315:                                                $response,$resptype));
  316:                         }
  317:                     } 
  318:                 } # end of $i loop
  319:             } # end of partid loop
  320:         } # end of prob loop
  321:         #
  322:         # if there is no data, skip this student.
  323:         next if (! $maxrow && ! scalar(@essays));
  324:         #
  325:         # Go through the problem data and output a row.
  326:         if ($row_class eq 'even') {
  327:             $row_class = 'odd'; 
  328:         } else {
  329:             $row_class = 'even'; 
  330:         }
  331:         my $printed_something;
  332:         for (my $rows_output = 0;$rows_output<$maxrow;$rows_output++) {
  333:             my $html;
  334:             my $no_data = 1;
  335:             foreach my $prob (@$problems) {
  336:                 my $symb = $prob->symb;
  337:                 foreach my $partid (@{$prob->parts}) {
  338:                     my @responses     = $prob->responseIds($partid);
  339:                     my @response_type = $prob->responseType($partid);
  340:                     for (my $i=0;$i<=$#responses;$i++) {
  341:                         my $respid   = $responses[$i];
  342:                         my $resp_data = 
  343:                             $problem_data{$symb}->{$partid}->{$respid};
  344:                         next if ($response_type[$i] eq 'essay');
  345:                         if (defined($resp_data->{'real'}->[$rows_output])) {
  346:                             $html .= $resp_data->{'real'}->[$rows_output];
  347:                             $no_data = 0;
  348:                         } else {
  349:                             $html .= $resp_data->{'fake'};
  350:                         }
  351:                     }
  352:                 }
  353:             }
  354:             if (! $no_data) {
  355:                 $r->print(qq{<tr class="$row_class">$student_row_data$html</tr>}.$/);
  356:                 $printed_something=1;
  357:             }
  358:         }
  359:         if (@essays) {
  360:             my $tr = qq{<tr class="$row_class">};
  361:             my $td = qq{<td  valign="top" class="essay" colspan="$total_col">};
  362:             if (! $printed_something) {
  363:                 $r->print($tr.$student_row_data.'</tr>'.$/);
  364:             }
  365:             $r->print($tr.$td.
  366:                       join('</td></tr>'.$/.$tr.$td,@essays).'</td></tr>'.$/);
  367:             undef(@essays);
  368:         }
  369:     } # end of student loop
  370:     return;
  371: }
  372: 
  373: #####################################################
  374: ##
  375: ##     HTML helper routines
  376: ##
  377: #####################################################
  378: sub html_essay_results {
  379:     my ($student,$prob,$partid,$respid,$response,$single_response)=@_;
  380:     #
  381:     my $submission =$response->[&Apache::loncoursedata::RDs_submission()];
  382:     $submission = &html_format_sub($submission,'essay');
  383:     #
  384:     my $correct = '';
  385:     if ($ENV{'form.correctans'} eq 'true') {
  386:         $correct = &Apache::lonstathelpers::get_student_answer
  387:             ($prob,$student->{'username'},$student->{'domain'},
  388:              $partid,$respid);
  389:         $correct = &html_format_sub($correct,'essay');
  390:     }
  391:     my $Str;
  392:     if (! $single_response) {
  393:         my $id = $prob->compTitle;
  394:         if (defined($partid) && $partid ne '0') {
  395:             $id .= ' '.$prob->part_display($partid);
  396:         }
  397:         if (defined($respid)) {
  398:             $id .= ' '.$respid;
  399:         }
  400:         $Str .= '<nobr>'.$id.'</nobr>'.('&nbsp;'x4);
  401:     }
  402:     if ($ENV{'form.prob_status'} eq 'true') {
  403:         $Str .= '<nobr>';
  404:         $Str .= $response->[&Apache::loncoursedata::RDs_awarddetail()].
  405:             ('&nbsp;'x4);
  406:         $Str .= &mt('Attempt [_1]',
  407:                     $response->[&Apache::loncoursedata::RDs_tries()]).
  408:                         ('&nbsp;'x4);
  409:         $Str .= &Apache::lonlocal::locallocaltime
  410:             ($response->[&Apache::loncoursedata::RDs_timestamp()]).
  411:             ('&nbsp;'x4);
  412:         $Str .= &mt('Awarded: [_1]',
  413:                     $response->[&Apache::loncoursedata::RDs_awarded()]).
  414:                         ('&nbsp;'x4);
  415:         $Str .= '</nobr><br />';
  416:     }
  417:     $Str .= $submission;
  418:     if (defined($correct) && $correct !~ /^\s*$/) {
  419:         $Str .= '<hr /><b>'.&mt('Correct').'</b>'.$correct
  420:     }
  421:     return $Str;
  422: }
  423: 
  424: sub html_results {
  425:     my ($student,$prob,$partid,$respid,$response,$resptype) = @_;
  426:     my $submission =$response->[&Apache::loncoursedata::RDs_submission()];
  427:     $submission = &html_format_sub($submission,$resptype);
  428:     my $correct = '';
  429:     if ($ENV{'form.correctans'} eq 'true') {
  430:         $correct = &Apache::lonstathelpers::get_student_answer
  431:             ($prob,$student->{'username'},$student->{'domain'},
  432:              $partid,$respid);
  433:         $correct = &html_format_sub($correct,$resptype);
  434:     }
  435:     my $Str;
  436:     $Str .= '<td valign="top">'.$submission.'</td>';
  437:     if ($ENV{'form.correctans'} eq 'true') {
  438:         $Str .= '<td valign="top">'.$correct.'</td>';
  439:     }
  440:     if ($ENV{'form.prob_status'} eq 'true') {
  441:         $Str .= '<td valign="top">'.
  442:             $response->[&Apache::loncoursedata::RDs_awarddetail()].
  443:             '</td>';
  444:         $Str .= '<td valign="top"><nobr>'.
  445:             &Apache::lonlocal::locallocaltime
  446:             ($response->[&Apache::loncoursedata::RDs_timestamp()]).
  447:             '</nobr></td>';
  448:         $Str .= '<td valign="top">'.
  449:             $response->[&Apache::loncoursedata::RDs_tries()].
  450:             '</td>';
  451:         $Str .= '<td valign="top">'.
  452:             $response->[&Apache::loncoursedata::RDs_awarded()].
  453:             '</td>';
  454:     }
  455:     return $Str;
  456: }
  457: 
  458: sub html_format_sub {
  459:     my ($submission,$resptype) = @_;
  460:     return '' if (! defined($submission) || $submission eq '');
  461:     $submission = &HTML::Entities::decode($submission);
  462:     $submission =~ s/\\\"/\"/g;
  463:     $submission =~ s/\\\'/\'/g;
  464:     if ($resptype eq 'essay') {
  465:         $submission =~ s|\\r\\n|$/|g;
  466:         $submission = &HTML::Entities::encode($submission,'<>&"');
  467:         $submission =~ s|$/\s*$/|$/</p><p>$/|g;
  468:         $submission =~ s|\\||g;
  469:         $submission = '<p>'.$submission.'</p>';
  470:     } elsif ($resptype eq 'radiobutton') {
  471:         $submission = &HTML::Entities::encode($submission,'<>&"');
  472:         $submission =~ s/=([^=])$//;
  473:     } elsif ($resptype =~ /^(option|match|rank)$/) {
  474:         $submission = 
  475:             '<ul class="sub_studentans">'.
  476:             '<li>'.join('</li><li>',
  477:                         map { &HTML::Entities::encode($_,'<>&"'); 
  478:                           } map { 
  479:                               &Apache::lonnet::unescape($_) ;
  480:                           } sort split('&',$submission)
  481:                         ).
  482:                         '</li><ul>';
  483:     } else {
  484:         $submission = &HTML::Entities::encode($submission,'<>&"');
  485:     }
  486:     return $submission;
  487: }
  488: 
  489: #########################################################
  490: #########################################################
  491: ##
  492: ##    Excel Output Routines
  493: ##
  494: #########################################################
  495: #########################################################
  496: sub prepare_excel_output {
  497:     my ($r,$Problems,$Students) = @_;
  498:     my $c = $r->connection();
  499:     #
  500:     #
  501:     # Determine the number of columns in the spreadsheet
  502:     my $columncount = 3; # username, domain, id
  503:     my $response_multiplier = 1;
  504:     $response_multiplier ++   if ($ENV{'form.correctans'} eq 'true');
  505:     $response_multiplier += 4 if ($ENV{'form.prob_status'} eq 'true');
  506:     my $lastprob;
  507:     foreach my $prob (@$Problems) {
  508:         $columncount += ($response_multiplier * $prob->countResponses);
  509:         last if ($columncount > 255);
  510:         $lastprob = $prob;
  511:     }
  512:     if ($columncount > 255) {
  513:         $r->print('<h1>'.&mt('Unable to complete request').'</h1>'.$/.
  514:                   '<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>'.$/.
  515:                   '<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>'.$/.
  516:                   '<p>'.&mt('The last problem that will fit in the current spreadsheet is [_1].',$lastprob->compTitle).'</p>');
  517:         $r->rflush();
  518:         return;
  519:     }
  520:     #
  521:     # Print out a message telling them what we are doing
  522:     if (scalar(@$Problems) > 1) {
  523:         $r->print('<h2>'.
  524:                   &mt('Preparing Excel spreadsheet of student responses to [_1] problems',
  525:                       scalar(@$Problems)).
  526:                   '</h2>');
  527:     } else {
  528:         $r->print('<h2>'.
  529:                   &mt('Preparing Excel spreadsheet of student responses').
  530:                   '</h2>');
  531:     }
  532:     $r->rflush();
  533:     #
  534:     # Create the excel spreadsheet
  535:     my $filename = '/prtspool/'.
  536:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
  537:         time.'_'.rand(1000000000).'.xls';
  538:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
  539:     if (! defined($workbook)) {
  540:         $r->log_error("Error creating excel spreadsheet $filename: $!");
  541:         $r->print('<p>'.&mt("Unable to create new Excel file.  ".
  542:                             "This error has been logged.  ".
  543:                             "Please alert your LON-CAPA administrator").
  544:                   '</p>');
  545:         return undef;
  546:     }
  547:     #
  548:     $workbook->set_tempdir('/home/httpd/perl/tmp');
  549:     #
  550:     my $format = &Apache::loncommon::define_excel_formats($workbook);
  551:     my $worksheet  = $workbook->addworksheet('Student Submission Data');
  552:     #
  553:     # Add headers to the worksheet
  554:     my $rows_output = 0;
  555:     $worksheet->write($rows_output++,0,
  556:                     $ENV{'course.'.$ENV{'request.course.id'}.'.description'},
  557:                       $format->{'h1'});
  558:     $rows_output++;
  559:     my $cols_output = 0;
  560:     my $title_row  = $rows_output++;
  561:     my $partid_row = $rows_output++;
  562:     my $respid_row = $rows_output++;
  563:     my $header_row = $rows_output++;
  564:     $worksheet->write($title_row ,0,'Problem Title',$format->{'bold'});
  565:     $worksheet->write($partid_row,0,'Part ID',$format->{'bold'});
  566:     $worksheet->write($respid_row,0,'Response ID',$format->{'bold'});
  567:     # Student headers
  568:     my @StudentColumns = ('username','domain','id');
  569:     foreach (@StudentColumns) {
  570:         $worksheet->write($header_row,$cols_output++,ucfirst($_),
  571:                           $format->{'bold'});
  572:     }
  573:     # Problem headers
  574:     foreach my $prob (@$Problems) {
  575:         my $title = $prob->compTitle;
  576:         $worksheet->write($title_row,$cols_output,
  577:                           $title,$format->{'h3'});
  578:         foreach my $partid (@{$prob->parts}) {
  579:             $worksheet->write($partid_row,$cols_output,
  580:                               $prob->part_display($partid));
  581:             my $responses = [$prob->responseIds($partid)];
  582:             my $resptypes = [$prob->responseType($partid)];
  583:             for (my $i=0;$i<scalar(@$responses);$i++) {
  584:                 $worksheet->write($respid_row,$cols_output,
  585:                                   $resptypes->[$i].', '.$responses->[$i]);
  586:                 $worksheet->write($header_row,$cols_output,'Submission');
  587:                 $cols_output++;
  588:                 if ($ENV{'form.correctans'} eq 'true') {
  589:                     $worksheet->write($header_row,$cols_output,'Correct');
  590:                     $cols_output++;
  591:                 }
  592:                 if ($ENV{'form.prob_status'} eq 'true') {
  593:                     $worksheet->write($header_row,$cols_output++,
  594:                                       'Award Detail');
  595:                     $worksheet->write($header_row,$cols_output++,'Attempt');
  596:                     $worksheet->write($header_row,$cols_output++,'Time');
  597:                     $worksheet->write($header_row,$cols_output++,'Awarded');
  598:                 }
  599:             }
  600:         }
  601:     }
  602:     #
  603:     # Populate the worksheet with the student data
  604:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  605:         ($r,'Excel File Compilation Status',
  606:          'Excel File Compilation Progress', 
  607:          scalar(@$Students),'inline',undef,'Statistics','stats_status');
  608:     my $max_row = $rows_output;
  609:     foreach my $student (@$Students) {
  610:         last if ($c->aborted());
  611:         $cols_output = 0;
  612:         my $student_row = $max_row;
  613:         foreach my $field (@StudentColumns) {
  614:             $worksheet->write($student_row,$cols_output++,
  615:                               $student->{$field});
  616:         }
  617:         my $last_student_col = $cols_output-1;
  618:         my $response_count;
  619:         foreach my $prob (@$Problems) {
  620:             foreach my $partid (@{$prob->parts}) {
  621:                 my @Response = $prob->responseIds($partid);
  622:                 my @ResponseType = $prob->responseType($partid);
  623:                 for (my $i=0;$i<=$#Response;$i++) {
  624:                     my $response_start_col = $last_student_col + 
  625:                         $response_count * $response_multiplier + 1;
  626:                     $response_count++;
  627:                     my $respid   = $Response[$i];
  628:                     my $resptype = $ResponseType[$i];
  629:                     my $results = 
  630:                         &Apache::loncoursedata::get_response_data_by_student
  631:                         ($student,$prob->symb(),$respid);
  632:                     if (! defined($results)) {
  633:                         $results = [];
  634:                     }
  635:                     #
  636:                     $rows_output = $student_row;
  637:                     #
  638:                     for (my $j=scalar(@$results)-1;$j>=0;$j--) {
  639:                         $cols_output = $response_start_col;
  640:                         my $response = $results->[$j];
  641:                         if ($ENV{'form.all_sub'} ne 'true') {
  642:                             next if ($j ne scalar(@$results)-1);
  643:                         }
  644:                         my $cols_output = &write_excel_row
  645:                             ($worksheet,
  646:                              $rows_output++,$cols_output,
  647:                              $response,$student,
  648:                              $prob,$partid,$respid,
  649:                              $format,$resptype);
  650:                         if ($rows_output > $max_row) {
  651:                             $max_row = $rows_output;
  652:                         }
  653:                     }
  654:                 }
  655:             }
  656:         }
  657:         # Fill in the remaining rows with the students data
  658:         for (my $row = $student_row+1;$row<=$max_row;$row++) {
  659:             my $cols = 0;
  660:             foreach my $field (@StudentColumns) {
  661:                 $worksheet->write($row,$cols++,
  662:                                   $student->{$field});
  663:             }
  664:         }
  665:         $rows_output++;
  666:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  667:                                                  'last student');
  668:     }
  669:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  670:     #
  671:     # Close the excel file
  672:     $workbook->close();
  673:     #
  674:     # Write a link to allow them to download it
  675:     $r->print('<p><a href="'.$filename.'">'.
  676:               &mt('Your Excel spreadsheet.').
  677:               '</a></p>'."\n");
  678:     $r->print('<script>'.
  679:               'window.document.Statistics.stats_status.value="'.
  680:               'Done compiling spreadsheet.  See link below to download.'.
  681:               '";</script>');
  682:     $r->rflush();
  683:     return;
  684: }
  685: 
  686: sub write_excel_row {
  687:     my ($worksheet,$row,$col,$response,$student,$prob,$partid,$respid,
  688:         $format,$resptype) = @_;
  689:     # 
  690:     my $submission =$response->[&Apache::loncoursedata::RDs_submission()];
  691:     $submission = &excel_format_response($submission,$resptype);
  692:     $worksheet->write($row,$col++,$submission);
  693:     if ($ENV{'form.correctans'} eq 'true') {
  694:         my $correct = &Apache::lonstathelpers::get_student_answer
  695:             ($prob,$student->{'username'},$student->{'domain'},
  696:              $partid,$respid);
  697:         $correct =&excel_format_response($correct,$resptype);
  698:         $worksheet->write($row,$col++,$correct);
  699:     }
  700:     if ($ENV{'form.prob_status'} eq 'true') {
  701:         $worksheet->write
  702:             ($row,$col++,
  703:              $response->[&Apache::loncoursedata::RDs_awarddetail()]);
  704:         $worksheet->write
  705:             ($row,$col++,$response->[&Apache::loncoursedata::RDs_tries()]);
  706:         $worksheet->write
  707:             ($row,$col++,
  708:              &Apache::lonstathelpers::calc_serial
  709:              ($response->[&Apache::loncoursedata::RDs_timestamp()]),
  710:              $format->{'date'});
  711:         $worksheet->write
  712:             ($row,$col++,$response->[&Apache::loncoursedata::RDs_awarded()]);
  713:     }
  714:     return $col;
  715: }
  716: 
  717: sub excel_format_response {
  718:     my ($answer,$responsetype) = @_;
  719:     if ($responsetype eq 'radiobutton') {
  720:         $answer =~ s/=([^=])$//;
  721:     } elsif ($responsetype =~ /^(option|match)$/) {
  722:         $answer = join("\n",
  723:                        map { 
  724:                            &Apache::lonnet::unescape($_) ;
  725:                        } sort split('&',$answer)
  726:                        );
  727:     } elsif ($responsetype eq 'string') {
  728:         $answer =~ s/\\(n|r)/\n/g;
  729:         $answer =~ s/(\s*$|^\s*)//g;
  730:         $answer =~ s/\\\'/\'/g;
  731:     }
  732:     if ($answer =~ m/^=/) {
  733:         $answer = ' '.$answer;
  734:     }
  735:     return $answer;
  736: }
  737: 
  738: #########################################################
  739: #########################################################
  740: ##
  741: ##      CSV output of student answers
  742: ##
  743: #########################################################
  744: #########################################################
  745: sub prepare_csv_output {
  746:     my ($r,$problems,$students) = @_;
  747:     my $c = $r->connection();
  748:     #
  749:     $r->print('<h2>'.
  750:               &mt('Generating CSV report of student responses').'</h2>');
  751:     #
  752:     # Progress window
  753:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  754:         ($r,'CSV File Compilation Status',
  755:          'CSV File Compilation Progress', 
  756:          scalar(@$students),'inline',undef,'Statistics','stats_status');
  757:     
  758:     $r->rflush();
  759:     #
  760:     # Open a file
  761:     my $outputfile;
  762:     my $filename = '/prtspool/'.
  763:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
  764:             time.'_'.rand(1000000000).'.csv';
  765:     unless ($outputfile = Apache::File->new('>/home/httpd'.$filename)) {
  766:         $r->log_error("Couldn't open $filename for output $!");
  767:         $r->print("Problems occured in writing the csv file.  ".
  768:                   "This error has been logged.  ".
  769:                   "Please alert your LON-CAPA administrator.");
  770:         $outputfile = undef;
  771:     }
  772:     #
  773:     # Compute the number of columns per response
  774:     my @response_headers = ('Submission');
  775:     if ($ENV{'form.correctans'} eq 'true') {
  776:         push(@response_headers,'Correct');
  777:     } 
  778:     if ($ENV{'form.prob_status'} eq 'true') {
  779:         push(@response_headers,'Award Detail'); 
  780:         push(@response_headers,'Time');
  781:         push(@response_headers,'Attempt');
  782:         push(@response_headers,'Awarded');
  783:     }
  784:     my $response_multiplier = scalar(@response_headers);
  785:     #
  786:     # Create the table header
  787:     my @student_columns = ('username','domain','id');
  788:     #
  789:     my %headers;
  790:     push(@{$headers{'student'}},@student_columns);
  791:     # Pad for the student data
  792:     foreach my $row ('problem','part','response') {
  793:         foreach (@student_columns) {
  794:             push(@{$headers{$row}},'');
  795:         }
  796:     }
  797:     #
  798:     # we put the headers into the %headers hash
  799:     my $prob_start_idx = 0;
  800:     foreach my $prob (@$problems) {
  801:         $headers{'problem'}->[$prob_start_idx] = $prob->compTitle;
  802:         my $part_start_idx = $prob_start_idx;
  803:         foreach my $partid (@{$prob->parts}) {
  804:             $headers{'part'}->[$part_start_idx] = $prob->part_display($partid);
  805:             my $responses = [$prob->responseIds($partid)];
  806:             for (my $i=0;$i<scalar(@$responses);$i++) {
  807:                 my $resp_idx = $prob_start_idx + $response_multiplier * $i;
  808:                 $headers{'response'}->[$resp_idx]=
  809:                     &mt('Response [_1]',$responses->[$i]);
  810:                 for (my $j=0;$j<=$#response_headers;$j++) {
  811:                     $headers{'student'}->[$resp_idx+$j]=$response_headers[$j];
  812:                 }
  813:             }
  814:             $part_start_idx += scalar(@$responses)*$response_multiplier;
  815:         }
  816:         $prob_start_idx += $prob->countResponses * $response_multiplier;
  817:     }
  818:     foreach my $row ('problem','part','response','student') {
  819:         print $outputfile '"'.join('","',map { ''; } @student_columns).'","'.
  820:             join('","',
  821:                  map { 
  822:                      &Apache::loncommon::csv_translate($_); 
  823:                  } @{$headers{$row}}).'"'.$/;
  824:     }
  825:     #
  826:     # Main loop
  827:     foreach my $student (@$students) {
  828:         last if ($c->aborted());
  829:         my @rows;
  830:         my $prob_start_idx = 0;
  831:         foreach my $prob (@$problems) {
  832:             my $part_start_idx = 0;
  833:             foreach my $partid (@{$prob->parts}) {
  834:                 my @responses = $prob->responseIds($partid);
  835:                 my @response_type = $prob->responseType($partid);
  836:                 for (my $i=0;$i<=$#responses;$i++) {
  837:                     my $resp_start_idx = $response_multiplier * $i;
  838:                     my $respid   = $responses[$i];
  839:                     my $results = 
  840:                         &Apache::loncoursedata::get_response_data_by_student
  841:                         ($student,$prob->symb(),$respid);
  842:                     if (! defined($results)) {
  843:                         $results = [];
  844:                     }
  845:                     for (my $j=0; $j<scalar(@$results);$j++) {
  846:                         if ($ENV{'form.all_sub'} ne 'true') {
  847:                             next if ($j != 0);
  848:                         }
  849:                         my $idx = scalar(@$results) - $j - 1;
  850:                         my $response = $results->[$idx];
  851:                         my @data = &compile_response_data($response,$student,
  852:                                                           $prob,$partid,
  853:                                                           $respid);
  854:                         for (my $k=0;$k<=$#data;$k++) {
  855:                             $rows[$j]->[$prob_start_idx + $part_start_idx +
  856:                                         $resp_start_idx + $k] = $data[$k];
  857:                         }
  858:                     }
  859:                 }
  860:                 $part_start_idx += scalar(@responses)*$response_multiplier;
  861:             }
  862:             $prob_start_idx += $prob->countResponses * $response_multiplier;
  863:         }
  864:         foreach my $row (@rows) {
  865:             print $outputfile '"'.join('","',
  866:                                        map { $student->{$_}; }
  867:                                        @student_columns).'"';
  868:                                            
  869:             for (my $i=0;$i<$prob_start_idx;$i++) {
  870:                 my $value = &Apache::loncommon::csv_translate($row->[$i]);
  871:                 $value ||='';
  872:                 print $outputfile ',"'.$value.'"';
  873:             }
  874:             print $outputfile $/;
  875:         }
  876:         undef(@rows);
  877:         &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
  878:                                                  'last student');
  879:     }
  880:     close($outputfile);
  881:     #
  882:     # Close the progress window
  883:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  884:     #
  885:     # Tell the user where to get their csv file
  886:     $r->print('<br />'.
  887:               '<a href="'.$filename.'">'.&mt('Your csv file.').'</a>'."\n");
  888:     $r->rflush();
  889:     return;
  890: }
  891: 
  892: sub compile_response_data {
  893:     my ($response,$student,$prob,$partid,$respid) = @_;
  894:     my @rowdata;
  895:     push(@rowdata,&Apache::lonnet::unescape($response->[&Apache::loncoursedata::RDs_submission()]));
  896:     if ($ENV{'form.correctans'} eq 'true') {
  897:         my $correct = &Apache::lonstathelpers::get_student_answer
  898:             ($prob,$student->{'username'},$student->{'domain'},
  899:              $partid,$respid);
  900:         push(@rowdata,$correct);
  901:     }
  902:     if ($ENV{'form.prob_status'}) {
  903:         push(@rowdata,$response->[&Apache::loncoursedata::RDs_awarddetail()]);
  904:         push(@rowdata,&Apache::lonlocal::locallocaltime
  905:              ($response->[&Apache::loncoursedata::RDs_timestamp()]));
  906:         push(@rowdata,$response->[&Apache::loncoursedata::RDs_tries()]);
  907:         push(@rowdata,$response->[&Apache::loncoursedata::RDs_awarded()]);
  908:     }
  909:     return @rowdata;
  910: }
  911: 
  912: #########################################################
  913: #########################################################
  914: ##
  915: ##   Generic Interface Routines
  916: ##
  917: #########################################################
  918: #########################################################
  919: sub CreateInterface {
  920:     ##
  921:     ## Output Selection
  922:     my $output_selector = $/.'<select name="output">'.$/;
  923:     foreach ('HTML','Excel','CSV') {
  924:         $output_selector .= '    <option value="'.lc($_).'"';
  925:         if ($ENV{'form.output'} eq lc($_)) {
  926:             $output_selector .= ' selected ';
  927:         }
  928:         $output_selector .='>'.&mt($_).'</option>'.$/;
  929:     } 
  930:     $output_selector .= '</select>'.$/;
  931:     ##
  932:     ## Environment variable initialization
  933:     my $Str = '';
  934:     $Str .= &Apache::lonhtmlcommon::breadcrumbs
  935:         (undef,'Student Submission Reports');
  936:     $Str .= '<p>';
  937:     $Str .= '<table cellspacing="5">'."\n";
  938:     $Str .= '<tr>';
  939:     $Str .= '<th>'.&mt('Sections').'</th>';
  940:     $Str .= '<th>'.&mt('Enrollment Status').'</th>';
  941:     $Str .= '<th>'.&mt('Output as [_1]',$output_selector).'</th>';
  942:     $Str .= '</tr>'."\n";
  943:     #
  944:     $Str .= '<tr><td align="center">'."\n";
  945:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
  946:     $Str .= '</td>';
  947:     #
  948:     $Str .= '<td align="center">';
  949:     $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
  950:     $Str .= '</td>';
  951:     #
  952:     # Render problem checkbox
  953:     my $prob_checkbox = '<input type="checkbox" name="renderprob" ';
  954:     if (exists($ENV{'form.renderprob'}) && $ENV{'form.renderprob'} eq 'true') {
  955:         $prob_checkbox .= 'checked ';
  956:     }
  957:     $prob_checkbox .= 'value="true" />';
  958:     #
  959:     # Compute correct answers checkbox
  960:     my $ans_checkbox = '<input type="checkbox" name="correctans" ';
  961:     if (exists($ENV{'form.correctans'}) && $ENV{'form.correctans'} eq 'true') {
  962:         $ans_checkbox .= 'checked ';
  963:     }
  964:     $ans_checkbox .= 'value="true" />';
  965:     #
  966:     # Show all submissions checkbox
  967:     my $all_sub_checkbox = '<input type="checkbox" name="all_sub" ';
  968:     if (exists($ENV{'form.all_sub'}) && 
  969:         $ENV{'form.all_sub'} eq 'true') {
  970:         $all_sub_checkbox .= 'checked ';
  971:     }
  972:     $all_sub_checkbox.= 'value="true" />';
  973:     #
  974:     # problem status checkbox
  975:     my $prob_status_checkbox = '<input type="checkbox" name="prob_status" ';
  976:     if (exists($ENV{'form.prob_status'}) && 
  977:         $ENV{'form.prob_status'} eq 'true') {
  978:         $prob_status_checkbox .= 'checked ';
  979:     }
  980:     $prob_status_checkbox .= 'value="true" />';
  981:     #
  982:     $Str .= '<td align="right" halign="top">'.
  983:         '<label><b>'.
  984:         &mt('Show problem [_1]',$prob_checkbox).'</b></label><br />'.
  985:         '<label><b>'.
  986:         &mt('Show correct answers [_1]',$ans_checkbox).'</b></label><br />'.
  987:         '<label><b>'.
  988:         &mt('Show all submissions [_1]',$all_sub_checkbox).
  989:         '</b></label><br />'.
  990:         '<label><b>'.
  991:         &mt('Show problem grading [_1]',$prob_status_checkbox).
  992:         '</b></label><br />'.
  993:         '</td>';
  994:     #
  995:     $Str .= '</tr>'."\n";
  996:     $Str .= '</table>'."\n";
  997:     #
  998:     $Str .= '<nobr>'.&mt('Status: [_1]',
  999:                          '<input type="text" '.
 1000:                          'name="stats_status" size="60" value="" />').
 1001:             '</nobr>'.'</p>';    
 1002:     ##
 1003:     return $Str;
 1004: }
 1005: 
 1006: 1;
 1007: 
 1008: __END__

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