File:  [LON-CAPA] / loncom / interface / statistics / lonstudentsubmissions.pm
Revision 1.65: download - view: text, annotated - select for diffs
Mon Nov 21 20:12:36 2011 UTC (12 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
- Bug 6492.
 - Selections in the multiple select box for "Student Data" generated from
   &Apache::lonstatistics::StudentDataSelect() are now displayed in the
   output for all Output Formats (HTML, CSV, Excel).

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

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