File:  [LON-CAPA] / loncom / interface / statistics / lonstudentsubmissions.pm
Revision 1.30: download - view: text, annotated - select for diffs
Wed Feb 2 18:53:32 2005 UTC (19 years, 5 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
HTML output of each foil item is done.  Excel & CSV output remain to do.

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

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