File:  [LON-CAPA] / loncom / interface / statistics / lonstudentsubmissions.pm
Revision 1.37: download - view: text, annotated - select for diffs
Mon Mar 14 20:28:22 2005 UTC (19 years, 3 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
lonstatistics.pm:Removed package variable @SelectedSections.
    Added &get_selected_sections
    Added &section_and_enrollment_description to provide a brief
        description of those students selected for statistics work
        (hopefully this descriptive line will make it in to bug reports).
Added &section_and_enrollment_description to all statistics pages
Replaced use of @SelectedSections with &get_selected_sections in statistics
    pages.

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

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