File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.139: download - view: text, annotated - select for diffs
Fri May 5 20:03:43 2006 UTC (18 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Adding groups filter to STATS functionality. New tables added (dom_course_groupnames and dom_course_studentgroups).

    1: # The LearningOnline Network with CAPA
    2: #
    3: # $Id: lonstudentassessment.pm,v 1.139 2006/05/05 20:03:43 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: # LON-CAPA is free software; you can redistribute it and/or modify
    9: # it under the terms of the GNU General Public License as published by
   10: # the Free Software Foundation; either version 2 of the License, or
   11: # (at your option) any later version.
   12: #
   13: # LON-CAPA is distributed in the hope that it will be useful,
   14: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   15: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   16: # GNU General Public License for more details.
   17: #
   18: # You should have received a copy of the GNU General Public License
   19: # along with LON-CAPA; if not, write to the Free Software
   20: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   21: #
   22: # /home/httpd/html/adm/gpl.txt
   23: #
   24: # http://www.lon-capa.org/
   25: #
   26: # (Navigate problems for statistical reports
   27: #
   28: #######################################################
   29: #######################################################
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: lonstudentassessment
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Presents assessment data about a student or a group of students.
   40: 
   41: =head1 Subroutines
   42: 
   43: =over 4 
   44: 
   45: =cut
   46: 
   47: #######################################################
   48: #######################################################
   49: 
   50: package Apache::lonstudentassessment;
   51: 
   52: use strict;
   53: use Apache::lonstatistics();
   54: use Apache::lonhtmlcommon();
   55: use Apache::loncommon();
   56: use Apache::loncoursedata;
   57: use Apache::lonnet; # for logging porpoises
   58: use Apache::lonlocal;
   59: use Apache::grades();
   60: use Apache::lonmsgdisplay();
   61: use Time::HiRes;
   62: use Spreadsheet::WriteExcel;
   63: use Spreadsheet::WriteExcel::Utility();
   64: 
   65: #######################################################
   66: #######################################################
   67: =pod
   68: 
   69: =item Package Variables
   70: 
   71: =over 4
   72: 
   73: =item $Statistics Hash ref to store student data.  Indexed by symb,
   74:       contains hashes with keys 'score' and 'max'.
   75: 
   76: =cut
   77: 
   78: #######################################################
   79: #######################################################
   80: 
   81: my $Statistics;
   82: 
   83: #######################################################
   84: #######################################################
   85: 
   86: =pod
   87: 
   88: =item $show_links 'yes' or 'no' for linking to student performance data
   89: 
   90: =item $output_mode 'html', 'excel', or 'csv' for output mode
   91: 
   92: =item $show 'all', 'totals', or 'scores' determines how much data is output
   93: 
   94: =item $single_student_mode evaluates to true if we are showing only one
   95: student.
   96: 
   97: =cut
   98: 
   99: #######################################################
  100: #######################################################
  101: my $show_links;
  102: my $output_mode;
  103: my $chosen_output;
  104: my $single_student_mode;
  105: 
  106: #######################################################
  107: #######################################################
  108: # End of package variable declarations
  109: 
  110: =pod
  111: 
  112: =back
  113: 
  114: =cut
  115: 
  116: #######################################################
  117: #######################################################
  118: 
  119: =pod
  120: 
  121: =item &BuildStudentAssessmentPage()
  122: 
  123: Inputs: 
  124: 
  125: =over 4
  126: 
  127: =item $r Apache Request
  128: 
  129: =item $c Apache Connection 
  130: 
  131: =back
  132: 
  133: =cut
  134: 
  135: #######################################################
  136: #######################################################
  137: sub BuildStudentAssessmentPage {
  138:     my ($r,$c)=@_;
  139:     #
  140:     undef($Statistics);
  141:     undef($show_links);
  142:     undef($output_mode);
  143:     undef($chosen_output);
  144:     undef($single_student_mode);
  145:     #
  146:     my %Saveable_Parameters = ('Status' => 'scalar',
  147:                                'chartoutputmode' => 'scalar',
  148:                                'chartoutputdata' => 'scalar',
  149:                                'Section' => 'array',
  150:                                'Groups' => 'array',
  151:                                'StudentData' => 'array',
  152:                                'Maps' => 'array');
  153:     &Apache::loncommon::store_course_settings('chart',\%Saveable_Parameters);
  154:     &Apache::loncommon::restore_course_settings('chart',\%Saveable_Parameters);
  155:     #
  156:     &Apache::lonstatistics::PrepareClasslist();
  157:     #
  158:     $single_student_mode = 0;
  159:     $single_student_mode = 1 if ($env{'form.SelectedStudent'});
  160:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  161:                                             ['selectstudent']);
  162:     if ($env{'form.selectstudent'}) {
  163:         &Apache::lonstatistics::DisplayClasslist($r);
  164:         return;
  165:     }
  166:     #
  167:     # Print out the HTML headers for the interface
  168:     #    This also parses the output mode selector
  169:     #    This step must *always* be done.
  170:     $r->print(&CreateInterface());
  171:     $r->print('<input type="hidden" name="notfirstrun" value="true" />');
  172:     $r->print('<input type="hidden" name="sort" value="'.
  173:               $env{'form.sort'}.'" />');
  174:     $r->rflush();
  175:     #
  176:     if (! exists($env{'form.notfirstrun'}) && ! $single_student_mode) {
  177:         return;
  178:     }
  179:     $r->print('<h4>'.
  180:               &Apache::lonstatistics::section_and_enrollment_description().
  181:               '</h4>');
  182:     #
  183:     my $initialize     = \&html_initialize;
  184:     my $output_student = \&html_outputstudent;
  185:     my $finish         = \&html_finish;
  186:     #
  187:     if ($output_mode eq 'excel') {
  188:         $initialize     = \&excel_initialize;
  189:         $output_student = \&excel_outputstudent;
  190:         $finish         = \&excel_finish;
  191:     } elsif ($output_mode eq 'csv') {
  192:         $initialize     = \&csv_initialize;
  193:         $output_student = \&csv_outputstudent;
  194:         $finish         = \&csv_finish;
  195:     }
  196:     #
  197:     if($c->aborted()) {  return ; }
  198:     #
  199:     # Determine which students we want to look at
  200:     my @Students;
  201:     if ($single_student_mode) {
  202:         @Students = (&Apache::lonstatistics::current_student());
  203:         $r->print(&next_and_previous_buttons());
  204:         $r->rflush();
  205:     } else {
  206:         @Students = @Apache::lonstatistics::Students;
  207:     }
  208:     #
  209:     # Perform generic initialization tasks
  210:     #       Since we use lonnet::EXT to retrieve problem weights,
  211:     #       to ensure current data we must clear the caches out.
  212:     #       This makes sure that parameter changes at the student level
  213:     #       are immediately reflected in the chart.
  214:     &Apache::lonnet::clear_EXT_cache_status();
  215:     #
  216:     # Clean out loncoursedata's package data, just to be safe.
  217:     &Apache::loncoursedata::clear_internal_caches();
  218:     #
  219:     # Call the initialize routine selected above
  220:     $initialize->($r);
  221:     foreach my $student (@Students) {
  222:         if($c->aborted()) { 
  223:             $finish->($r);
  224:             return ; 
  225:         }
  226:         # Call the output_student routine selected above
  227:         $output_student->($r,$student);
  228:     }
  229:     # Call the "finish" routine selected above
  230:     $finish->($r);
  231:     #
  232:     return;
  233: }
  234: 
  235: #######################################################
  236: #######################################################
  237: sub next_and_previous_buttons {
  238:     my $Str = '';
  239:     $Str .= '<input type="hidden" name="SelectedStudent" value="'.
  240:         $env{'form.SelectedStudent'}.'" />';
  241:     #
  242:     # Build the previous student link
  243:     my $previous = &Apache::lonstatistics::previous_student();
  244:     my $previousbutton = '';
  245:     if (defined($previous)) {
  246:         my $sname = $previous->{'username'}.':'.$previous->{'domain'};
  247:         $previousbutton .= '<input type="button" value="'.
  248:             'Previous Student ('.
  249:             $previous->{'username'}.'@'.$previous->{'domain'}.')'.
  250:             '" onclick="document.Statistics.SelectedStudent.value='.
  251:             "'".$sname."'".';'.
  252:             'document.Statistics.submit();" />';
  253:     } else {
  254:         $previousbutton .= '<input type="button" value="'.
  255:             'Previous student (none)'.'" />';
  256:     }
  257:     #
  258:     # Build the next student link
  259:     my $next = &Apache::lonstatistics::next_student();
  260:     my $nextbutton = '';
  261:     if (defined($next)) {
  262:         my $sname = $next->{'username'}.':'.$next->{'domain'};
  263:         $nextbutton .= '<input type="button" value="'.
  264:             'Next Student ('.
  265:             $next->{'username'}.'@'.$next->{'domain'}.')'.
  266:             '" onclick="document.Statistics.SelectedStudent.value='.
  267:             "'".$sname."'".';'.
  268:             'document.Statistics.submit();" />';
  269:     } else {
  270:         $nextbutton .= '<input type="button" value="'.
  271:             'Next student (none)'.'" />';
  272:     }
  273:     #
  274:     # Build the 'all students' button
  275:     my $all = '';
  276:     $all .= '<input type="button" value="All Students" '.
  277:             '" onclick="document.Statistics.SelectedStudent.value='.
  278:             "''".';'.'document.Statistics.submit();" />';
  279:     $Str .= $previousbutton.('&nbsp;'x5).$all.('&nbsp;'x5).$nextbutton;
  280:     return $Str;
  281: }
  282: 
  283: #######################################################
  284: #######################################################
  285: 
  286: sub get_student_fields_to_show {
  287:     my @to_show = @Apache::lonstatistics::SelectedStudentData;
  288:     foreach (@to_show) {
  289:         if ($_ eq 'all') {
  290:             @to_show = @Apache::lonstatistics::StudentDataOrder;
  291:             last;
  292:         }
  293:     }
  294:     return @to_show;
  295: }
  296: 
  297: #######################################################
  298: #######################################################
  299: 
  300: =pod
  301: 
  302: =item &CreateInterface()
  303: 
  304: Called by &BuildStudentAssessmentPage to create the top part of the
  305: page which displays the chart.
  306: 
  307: Inputs: None
  308: 
  309: Returns:  A string containing the HTML for the headers and top table for 
  310: the chart page.
  311: 
  312: =cut
  313: 
  314: #######################################################
  315: #######################################################
  316: sub CreateInterface {
  317:     my $Str = '';
  318:     $Str .= &Apache::lonhtmlcommon::breadcrumbs('Chart');
  319: #    $Str .= &CreateLegend();
  320:     $Str .= '<table cellspacing="5">'."\n";
  321:     $Str .= '<tr>';
  322:     $Str .= '<td align="center"><b>'.&mt('Sections').'</b></td>';
  323:     $Str .= '<td align="center"><b>'.&mt('Groups').'</b></td>';
  324:     $Str .= '<td align="center"><b>'.&mt('Student Data</b>').'</td>';
  325:     $Str .= '<td align="center"><b>'.&mt('Enrollment Status').'</b></td>';
  326:     $Str .= '<td align="center"><b>'.&mt('Sequences and Folders').'</b></td>';
  327:     $Str .= '<td align="center"><b>'.&mt('Output Format').'</b>'.
  328:         &Apache::loncommon::help_open_topic("Chart_Output_Formats").
  329:         '</td>';
  330:     $Str .= '<td align="center"><b>'.&mt('Output Data').'</b>'.
  331:         &Apache::loncommon::help_open_topic("Chart_Output_Data").
  332:         '</td>';
  333:     $Str .= '</tr>'."\n";
  334:     #
  335:     $Str .= '<tr><td align="center">'."\n";
  336:     $Str .= &Apache::lonstatistics::SectionSelect('Section','multiple',5);
  337:     $Str .= '</td><td align="center">';
  338:     $Str .= &Apache::lonstatistics::GroupSelect('Group','multiple',5);
  339:     $Str .= '</td><td align="center">';
  340:     $Str .= &Apache::lonstatistics::StudentDataSelect('StudentData','multiple',
  341:                                                       5,undef);
  342:     $Str .= '</td><td>'."\n";
  343:     $Str .= &Apache::lonhtmlcommon::StatusOptions(undef,undef,5);
  344:     $Str .= '</td><td>'."\n";
  345:     $Str .= &Apache::lonstatistics::map_select('Maps','multiple,all',5);
  346:     $Str .= '</td><td>'."\n";
  347:     $Str .= &CreateAndParseOutputSelector();
  348:     $Str .= '</td><td>'."\n";
  349:     $Str .= &CreateAndParseOutputDataSelector();
  350:     $Str .= '</td></tr>'."\n";
  351:     $Str .= '</table>'."\n";
  352:     $Str .= '<input type="submit" name="Generate Chart" value="'.
  353:         &mt('Generate Chart').'" />';
  354:     $Str .= '&nbsp;'x5;
  355:     $Str .= '<input type="submit" name="selectstudent" value="'.
  356:         &mt('Select One Student').'" />';
  357:     $Str .= '&nbsp;'x5;
  358:     $Str .= '<input type="submit" name="ClearCache" value="'.
  359:         &mt('Clear Caches').'" />';
  360:     $Str .= '&nbsp;'x5;
  361:     $Str .= 
  362:         &mt('Status [_1]',
  363:             '<input type="text" name="stats_status" size="60" value="" />');
  364:     $Str .= '<br />';
  365:     return $Str;
  366: }
  367: 
  368: #######################################################
  369: #######################################################
  370: 
  371: =pod
  372: 
  373: =item &CreateAndParseOutputSelector()
  374: 
  375: =cut
  376: 
  377: #######################################################
  378: #######################################################
  379: my @OutputOptions = 
  380:     ({ name  => 'HTML, with links',
  381:        value => 'html, with links',
  382:        description => 'Output HTML with each symbol linked to the problem '.
  383: 	   'which generated it.',
  384:        mode => 'html',
  385:        show_links => 'yes',
  386:        },
  387:      { name  => 'HTML, with all links',
  388:        value => 'html, with all links',
  389:        description => 'Output HTML with each symbol linked to the problem '.
  390: 	   'which generated it.  '.
  391:            'This includes links for unattempted problems.',
  392:        mode => 'html',
  393:        show_links => 'all',
  394:        },
  395:      { name  => 'HTML, without links',
  396:        value => 'html, without links',
  397:        description => 'Output HTML.  By not including links, the size of the'.
  398: 	   ' web page is greatly reduced.  If your browser crashes on the '.
  399: 	   'full display, try this.',
  400:        mode => 'html',
  401:        show_links => 'no',
  402:            },
  403:      { name  => 'Excel',
  404:        value => 'excel',
  405:        description => 'Output an Excel file (compatable with Excel 95).',
  406:        mode => 'excel',
  407:        show_links => 'no',
  408:    },
  409:      { name  => 'CSV',
  410:        value => 'csv',
  411:        description => 'Output a comma separated values file suitable for '.
  412:            'import into a spreadsheet program.  Using this method as opposed '.
  413:            'to Excel output allows you to organize your data before importing'.
  414:            ' it into a spreadsheet program.',
  415:        mode => 'csv',
  416:        show_links => 'no',
  417:            },
  418:      );
  419: 
  420: sub OutputDescriptions {
  421:     my $Str = '';
  422:     $Str .= "<h2>Output Formats</h2>\n";
  423:     $Str .= "<dl>\n";
  424:     foreach my $outputmode (@OutputOptions) {
  425: 	$Str .="    <dt>".$outputmode->{'name'}."</dt>\n";
  426: 	$Str .="        <dd>".$outputmode->{'description'}."</dd>\n";
  427:     }
  428:     $Str .= "</dl>\n";
  429:     return $Str;
  430: }
  431: 
  432: sub CreateAndParseOutputSelector {
  433:     my $Str = '';
  434:     my $elementname = 'chartoutputmode';
  435:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  436:                                             [$elementname]);
  437:     #
  438:     # Format for output options is 'mode, restrictions';
  439:     my $selected = (&Apache::loncommon::get_env_multiple('form.'.$elementname))[0];
  440:     $selected = 'html, without links' if (!$selected);
  441: 
  442:     #
  443:     # Set package variables describing output mode
  444:     $show_links  = 'no';
  445:     $output_mode = 'html';
  446:     foreach my $option (@OutputOptions) {
  447:         next if ($option->{'value'} ne $selected);
  448:         $output_mode = $option->{'mode'};
  449:         $show_links  = $option->{'show_links'};
  450:     }
  451: 
  452:     #
  453:     # Build the form element
  454:     $Str = qq/<select size="5" name="$elementname">/;
  455:     foreach my $option (@OutputOptions) {
  456:         $Str .= "\n".'    <option value="'.$option->{'value'}.'"';
  457:         $Str .= " selected " if ($option->{'value'} eq $selected);
  458:         $Str .= ">".&mt($option->{'name'})."<\/option>";
  459:     }
  460:     $Str .= "\n</select>";
  461:     return $Str;
  462: }
  463: 
  464: ##
  465: ## Data selector stuff
  466: ##
  467: my @OutputDataOptions =
  468:     (
  469:      { name  => 'Scores Summary',
  470:        base  => 'scores',
  471:        value => 'sum and total',
  472:        scores => 1,
  473:        tries  => 0,
  474:        every_problem => 0,
  475:        sequence_sum => 1,
  476:        sequence_max => 1,
  477:        grand_total => 1,
  478:        grand_maximum => 1,
  479:        summary_table => 1,
  480:        maximum_row => 1,
  481:        ignore_weight => 0,
  482:        shortdesc => 'Total Score and Maximum Possible for each '.
  483:            'Sequence or Folder',
  484:        longdesc => 'The score of each student as well as the '.
  485:            ' maximum possible on each Sequence or Folder.',
  486:        },
  487:      { name  => 'Scores Per Problem',
  488:        base  => 'scores',
  489:        value => 'scores',
  490:        scores => 1,
  491:        tries  => 0,
  492:        correct => 0,
  493:        every_problem => 1,
  494:        sequence_sum => 1,
  495:        sequence_max => 1,
  496:        grand_total => 1,
  497:        grand_maximum => 1,
  498:        summary_table => 1,
  499:        maximum_row => 1,
  500:        ignore_weight => 0,
  501:        shortdesc => 'Score on each Problem Part',
  502:        longdesc =>'The students score on each problem part, computed as'.
  503:            'the part weight * part awarded',
  504:        },
  505:      { name  =>'Tries',
  506:        base  =>'tries',
  507:        value => 'tries',
  508:        scores => 0,
  509:        tries  => 1,
  510:        correct => 0,
  511:        every_problem => 1,
  512:        sequence_sum => 0,
  513:        sequence_max => 0,
  514:        grand_total => 0,
  515:        grand_maximum => 0,
  516:        summary_table => 0,
  517:        maximum_row => 0,
  518:        ignore_weight => 0,
  519:        shortdesc => 'Number of Tries before success on each Problem Part',
  520:        longdesc =>'The number of tries before success on each problem part.',
  521:        non_html_notes => 'negative values indicate an incorrect problem',
  522:        },
  523:      { name  =>'Parts Correct',
  524:        base  =>'tries',
  525:        value => 'parts correct total',
  526:        scores => 0,
  527:        tries  => 0,
  528:        correct => 1,
  529:        every_problem => 1,
  530:        sequence_sum => 1,
  531:        sequence_max => 1,
  532:        grand_total => 1,
  533:        grand_maximum => 1,
  534:        summary_table => 1,
  535:        maximum_row => 0,
  536:        ignore_weight => 1,
  537:        shortdesc => 'Number of Problem Parts completed successfully.',
  538:        longdesc => 'The Number of Problem Parts completed successfully and '.
  539:            'the maximum possible for each student',
  540:        },
  541:      );
  542: 
  543: sub HTMLifyOutputDataDescriptions {
  544:     my $Str = '';
  545:     $Str .= "<h2>Output Data</h2>\n";
  546:     $Str .= "<dl>\n";
  547:     foreach my $option (@OutputDataOptions) {
  548:         $Str .= '    <dt>'.$option->{'name'}.'</dt>';
  549:         $Str .= '<dd>'.$option->{'longdesc'}.'</dd>'."\n";
  550:     }
  551:     $Str .= "</dl>\n";
  552:     return $Str;
  553: }
  554: 
  555: sub CreateAndParseOutputDataSelector {
  556:     my $Str = '';
  557:     my $elementname = 'chartoutputdata';
  558:     #
  559:     my $selected = (&Apache::loncommon::get_env_multiple('form.'.$elementname))[0];
  560:     $selected = 'scores' if (!$selected);
  561: 
  562:     #
  563:     $chosen_output = $OutputDataOptions[0];
  564:     foreach my $option (@OutputDataOptions) {
  565:         if ($option->{'value'} eq $selected) {
  566:             $chosen_output = $option;
  567:         }
  568:     }
  569:     #
  570:     # Build the form element
  571:     $Str = qq/<select size="5" name="$elementname">/;
  572:     foreach my $option (@OutputDataOptions) {
  573:         $Str .= "\n".'    <option value="'.$option->{'value'}.'"';
  574:         $Str .= " selected " if ($option->{'value'} eq $chosen_output->{'value'});
  575:         $Str .= ">".&mt($option->{'name'})."<\/option>";
  576:     }
  577:     $Str .= "\n</select>";
  578:     return $Str;
  579: 
  580: }
  581: 
  582: #######################################################
  583: #######################################################
  584: sub count_parts {
  585:     my ($navmap,$sequence) = @_;
  586:     my @resources = &get_resources($navmap,$sequence);
  587:     my $count = 0;
  588:     foreach my $res (@resources) {
  589:         $count += scalar(@{$res->parts});
  590:     }
  591:     return $count;
  592: }
  593: 
  594: sub get_resources {
  595:     my ($navmap,$sequence) = @_;
  596:     my @resources = $navmap->retrieveResources($sequence,
  597:                                                sub { shift->is_problem(); },
  598:                                                0,0,0);
  599:     return @resources;
  600: }
  601: 
  602: #######################################################
  603: #######################################################
  604: 
  605: =pod
  606: 
  607: =head2 HTML output routines
  608: 
  609: =item &html_initialize($r)
  610: 
  611: Create labels for the columns of student data to show.
  612: 
  613: =item &html_outputstudent($r,$student)
  614: 
  615: Return a line of the chart for a student.
  616: 
  617: =item &html_finish($r)
  618: 
  619: =cut
  620: 
  621: #######################################################
  622: #######################################################
  623: {
  624:     my $padding;
  625:     my $count;
  626: 
  627:     my $nodata_count; # The number of students for which there is no data
  628:     my %prog_state;   # progress state used by loncommon PrgWin routines
  629:     my $total_sum_width;
  630: 
  631:     my %width; # Holds sequence width information
  632:     my @sequences;
  633:     my $navmap; # Have to keep this around since weakref is a bit zealous
  634: 
  635: sub html_cleanup {
  636:     undef(%prog_state);
  637:     undef(%width);
  638:     #
  639:     undef($navmap);
  640:     undef(@sequences);
  641: }
  642: 
  643: sub html_initialize {
  644:     my ($r) = @_;
  645:     #
  646:     $padding = ' 'x3;
  647:     $count = 0;
  648:     $nodata_count = 0;
  649:     &html_cleanup();
  650:     ($navmap,@sequences) = 
  651:         &Apache::lonstatistics::selected_sequences_with_assessments();
  652:     if (! ref($navmap)) {
  653:         # Unable to get data, so bail out
  654:         $r->print("<h3>".
  655:                   &mt('Unable to retrieve course information.').
  656:                   '</h3>');
  657:     }
  658: 
  659:     # If we're showing links, show a checkbox to open in new
  660:     # windows.
  661:     if ($show_links ne 'no') {
  662:         $r->print(<<NEW_WINDOW_CHECKBOX);
  663: <script type="text/javascript">new_window = true;</script>
  664: <p><label>Show links in new window: 
  665: <input type="checkbox" checked="1" onclick="new_window=this.checked" />
  666: </label></p>
  667: NEW_WINDOW_CHECKBOX
  668:     }
  669: 
  670:     #
  671:     $r->print("<h3>".$env{'course.'.$env{'request.course.id'}.'.description'}.
  672:               "&nbsp;&nbsp;".localtime(time)."</h3>");
  673:     #
  674:     if ($chosen_output->{'base'} !~ /^final table/) {
  675:         $r->print("<h3>".$chosen_output->{'shortdesc'}."</h3>");        
  676:     }
  677:     my $Str = "<pre>\n";
  678:     # First, the @StudentData fields need to be listed
  679:     my @to_show = &get_student_fields_to_show();
  680:     foreach my $field (@to_show) {
  681:         my $title=$Apache::lonstatistics::StudentData{$field}->{'title'};
  682:         my $base =$Apache::lonstatistics::StudentData{$field}->{'base_width'};
  683:         my $width=$Apache::lonstatistics::StudentData{$field}->{'width'};
  684:         $Str .= $title.' 'x($width-$base).$padding;
  685:     }
  686:     #
  687:     # Compute the column widths and output the sequence titles
  688:     my $total_count;
  689:     #
  690:     # Compute sequence widths
  691:     my $starttime = Time::HiRes::time;
  692:     foreach my $seq (@sequences) {
  693:         my $symb = $seq->symb;
  694:         my $title = $seq->compTitle;
  695:         $width{$symb}->{'width_sum'} = 0;
  696:         # Compute width of sum
  697:         if ($chosen_output->{'sequence_sum'}) {
  698:             if ($chosen_output->{'every_problem'}) {
  699:                 # Use 1 digit for a space
  700:                 $width{$symb}->{'width_sum'} += 1;            
  701:             }
  702: 	    $total_count += &count_parts($navmap,$seq);
  703:             # Use 3 digits for the sum
  704:             $width{$symb}->{'width_sum'} += 3;
  705:         }
  706:         # Compute width of maximum
  707:         if ($chosen_output->{'sequence_max'}) {
  708:             if ($width{$symb}->{'width_sum'}>0) {
  709:                 # One digit for the '/'
  710:                 $width{$symb}->{'width_sum'} +=1;
  711:             }
  712:             # Use 3 digits for the total
  713:             $width{$symb}->{'width_sum'}+=3;
  714:         }
  715: 	#
  716:         if ($chosen_output->{'every_problem'}) {
  717:             # one problem per digit
  718:             $width{$symb}->{'width_parts'}= &count_parts($navmap,$seq);
  719:             $width{$symb}->{'width_problem'} += $width{$symb}->{'width_parts'};
  720:         } else {
  721:             $width{$symb}->{'width_problem'} = 0;
  722:         }
  723:         $width{$symb}->{'width_total'} = $width{$symb}->{'width_problem'} + 
  724:                                      $width{$symb}->{'width_sum'};
  725:         if ($width{$symb}->{'width_total'} < length(&HTML::Entities::decode($title))) {
  726:             $width{$symb}->{'width_total'} = length(&HTML::Entities::decode($title));
  727:         }
  728:         #
  729:         # Output the sequence titles
  730:         $Str .= $title.(' 'x($width{$symb}->{'width_total'}-
  731:                             length($title)
  732:                             )).$padding;
  733:     }
  734:     $total_sum_width = length($total_count)+1;
  735:     $Str .= "    total</pre>\n";
  736:     $Str .= "<pre>";
  737:     $r->print($Str);
  738:     $r->rflush();
  739: 
  740:     $r->print(<<JS);
  741: <script>
  742: // get the left offset of a given widget as an absolute position
  743: function getLeftOffset (element) {
  744:     return collect(element, "offsetLeft");
  745: }
  746: 
  747: // get the top offset of a given widget as an absolute position
  748: function getTopOffset (element) {
  749:     return collect(element, "offsetTop");
  750: }
  751: 
  752: function collect(element, att) {
  753:     var val = 0;
  754:     while(element) {
  755:         val += element[att];
  756:         element = element.offsetParent;
  757:     }
  758:     return val;
  759: }
  760: 
  761: var currentDiv;
  762: var oldBorder;
  763: var currentElement;
  764: function popup_score(element, score) {
  765:     popdown_score();
  766:     var left = getLeftOffset(element);
  767:     var top = getTopOffset(element);
  768:     var div = document.createElement("div");
  769:     div.style.border = "1px solid #8888FF";
  770:     div.style.backgroundColor = "#CCCCFF";
  771:     div.appendChild(document.createTextNode(score));
  772:     div.style.position = "absolute";
  773:     div.style.top = (top - 25) + "px";
  774:     div.style.left = (left - 10) + "px";
  775:     currentDiv = div;
  776:     document.body.insertBefore(div, document.body.childNodes[0]);
  777:     oldBorder = element.style.border;
  778:     element.style.border = "1px solid yellow";
  779:     currentElement = element;
  780: }
  781: 
  782: function popdown_score() {
  783:     if (currentDiv) {
  784:         document.body.removeChild(currentDiv);
  785:     }
  786:     if (currentElement) {
  787:         currentElement.style.border = oldBorder;
  788:     }
  789:     currentDiv = undefined;
  790: }
  791: </script>
  792: JS
  793: 
  794:     #
  795:     # Let the user know what we are doing
  796:     my $studentcount = scalar(@Apache::lonstatistics::Students); 
  797:     if ($env{'form.SelectedStudent'}) {
  798:         $studentcount = '1';
  799:     }
  800:     #
  801:     # Initialize progress window
  802:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
  803:         ($r,'HTML Chart Status',
  804:          'HTML Chart Progress', $studentcount,
  805:          'inline',undef,'Statistics','stats_status');
  806:     #
  807:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
  808:                                           'Processing first student');
  809:     return;
  810: }
  811: 
  812: sub html_outputstudent {
  813:     my ($r,$student) = @_;
  814:     my $Str = '';
  815:     return if (! defined($navmap));
  816:     #
  817:     if($count++ % 5 == 0 && $count > 0) {
  818:         $r->print("</pre><pre>");
  819:     }
  820:     # First, the @StudentData fields need to be listed
  821:     my @to_show = &get_student_fields_to_show();
  822:     foreach my $field (@to_show) {
  823:         my $title=$student->{$field};
  824:         # Deal with 'comments' - how I love special cases
  825:         if ($field eq 'comments') {
  826:             $title = '<a href="/adm/'.$student->{'domain'}.'/'.$student->{'username'}.'/'.'aboutme#coursecomment">'.&mt('Comments').'</a>';
  827:         }
  828:         my $base = length($title);
  829:         my $width=$Apache::lonstatistics::StudentData{$field}->{'width'};
  830:         $Str .= $title.' 'x($width-$base).$padding;
  831:     }
  832:     # Get ALL the students data
  833:     my %StudentsData;
  834:     my @tmp = &Apache::loncoursedata::get_current_state
  835:         ($student->{'username'},$student->{'domain'},undef,
  836:          $env{'request.course.id'});
  837:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
  838:         %StudentsData = @tmp;
  839:     }
  840:     if (scalar(@tmp) < 1) {
  841:         $nodata_count++;
  842:         $Str .= '<font color="blue">No Course Data</font>'."\n";
  843:         $r->print($Str);
  844:         $r->rflush();
  845:         return;
  846:     }
  847:     #
  848:     # By sequence build up the data
  849:     my $studentstats;
  850:     my $PerformanceStr = '';
  851:     foreach my $seq (@sequences) {
  852:         my $symb = $seq->symb;
  853:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
  854:         if ($chosen_output->{'tries'}) {
  855:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
  856:                 &student_tries_on_sequence($student,\%StudentsData,
  857:                                            $navmap,$seq,$show_links);
  858:         } else {
  859:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
  860:                 &student_performance_on_sequence($student,\%StudentsData,
  861:                                                  $navmap,$seq,$show_links,
  862:                                                  $chosen_output->{ignore_weight});
  863:         }
  864:         my $ratio='';
  865:         if ($chosen_output->{'every_problem'} && 
  866:             $chosen_output->{'sequence_sum'}) {
  867:             $ratio .= ' ';
  868:         }
  869:         if ($chosen_output->{'sequence_sum'} && $score ne ' ') {
  870:             my $score .= sprintf("%3.0f",$score);
  871:             $ratio .= (' 'x(3-length($score))).$score;
  872:         } elsif($chosen_output->{'sequence_sum'}) {
  873:             $ratio .= ' 'x3;
  874:         }
  875:         if ($chosen_output->{'sequence_max'}) {
  876:             if ($chosen_output->{'sequence_sum'}) {
  877:                 $ratio .= '/';
  878:             }
  879:             $ratio .= sprintf("%3.0f",$seq_max);
  880:         }
  881:         #
  882:         if (! $chosen_output->{'every_problem'}) {
  883:             $performance = '';
  884: 	    $performance_length=0;
  885:         }
  886:         $performance .= ' 'x($width{$symb}->{'width_total'} -
  887:                              $performance_length -
  888:                              $width{$symb}->{'width_sum'}).
  889:             $ratio;
  890:         #
  891:         $Str .= $performance.$padding;
  892:         #
  893:         $studentstats->{$symb}->{'score'}= $score;
  894:         $studentstats->{$symb}->{'max'}  = $seq_max;
  895:     }
  896:     #
  897:     # Total it up and store the statistics info.
  898:     my ($score,$max);
  899:     while (my ($symb,$seq_stats) = each (%{$studentstats})) {
  900:         $Statistics->{$symb}->{'score'} += $seq_stats->{'score'};
  901:         if ($Statistics->{$symb}->{'max'} < $seq_stats->{'max'}) {
  902:             $Statistics->{$symb}->{'max'} = $seq_stats->{'max'};
  903:         }
  904:         if ($seq_stats->{'score'} ne ' ') {
  905:             $score += $seq_stats->{'score'};
  906:             $Statistics->{$symb}->{'num_students'}++;
  907:         }
  908:         $max   += $seq_stats->{'max'};
  909:     }
  910:     if (! defined($score)) {
  911:         $score = ' ' x $total_sum_width;
  912:     } else {
  913:         $score = sprintf("%.0f",$score);
  914:         $score = (' 'x(3-length($score))).$score;
  915:     }
  916:     $Str .= ' '.' 'x($total_sum_width-length($score)).$score.' / '.$max;
  917:     $Str .= " \n";
  918:     #
  919:     $r->print($Str);
  920:     #
  921:     $r->rflush();
  922:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
  923:     return;
  924: }    
  925: 
  926: sub html_finish {
  927:     my ($r) = @_;
  928:     return if (! defined($navmap));
  929:     #
  930:     # Check for suppressed output and close the progress window if so
  931:     $r->print("</pre>\n"); 
  932:     if ($chosen_output->{'summary_table'}) {
  933:         if ($single_student_mode) {
  934:             $r->print(&SingleStudentTotal());
  935:         } else {
  936:             $r->print(&StudentAverageTotal());
  937:         }
  938:     }
  939:     $r->rflush();
  940:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  941:     &html_cleanup();
  942:     return;
  943: }
  944: 
  945: sub StudentAverageTotal {
  946:     my $Str = '<h3>'.&mt('Summary Tables').'</h3>'.$/;
  947:     $Str .= '<table border=2 cellspacing="1">'."\n";
  948:     $Str .= '<tr>'.
  949:         '<th>'.&mt('Title').'</th>'.
  950:         '<th>'.&mt('Average').'</th>'.
  951:         '<th>'.&mt('Maximum').'</th>'.
  952:         '</tr>'.$/;
  953:     foreach my $seq (@sequences) {
  954:         my $symb = $seq->symb;
  955:         my $ave;
  956:         my $num_students = $Statistics->{$symb}->{'num_students'};
  957:         if ($num_students > 0) {
  958:             $ave = int(100*
  959:                        ($Statistics->{$symb}->{'score'}/$num_students)
  960:                        )/100;
  961:         } else {
  962:             $ave = 0;
  963:         }
  964:         my $max = $Statistics->{$symb}->{'max'};
  965:         $ave = sprintf("%.2f",$ave);
  966:         $Str .= '<tr><td>'.$seq->compTitle.'</td>'.
  967:             '<td align="right">'.$ave.'&nbsp;</td>'.
  968:             '<td align="right">'.$max.'&nbsp;'.'</td></tr>'."\n";
  969:     }
  970:     $Str .= "</table>\n";
  971:     return $Str;
  972: }
  973: 
  974: sub SingleStudentTotal {
  975:     return if (! defined($navmap));
  976:     my $student = &Apache::lonstatistics::current_student();
  977:     my $Str = '<h3>'.&mt('Summary table for [_1] ([_2]@[_3])',
  978:                          $student->{'fullname'},
  979:                          $student->{'username'},$student->{'domain'}).'</h3>';
  980:     $Str .= $/;
  981:     $Str .= '<table border=2 cellspacing="1">'."\n";
  982:     $Str .= 
  983:         '<tr>'.
  984:         '<th>'.&mt('Sequence or Folder').'</th>';
  985:     if ($chosen_output->{'base'} eq 'tries') {
  986:         $Str .= '<th>'.&mt('Parts Correct').'</th>';
  987:     } else {
  988:         $Str .= '<th>'.&mt('Score').'</th>';
  989:     }
  990:     $Str .= '<th>'.&mt('Maximum').'</th>'."</tr>\n";
  991:     my $total = 0;
  992:     my $total_max = 0;
  993:     foreach my $seq (@sequences) {
  994:         my $value = $Statistics->{$seq->symb}->{'score'};
  995:         my $max = $Statistics->{$seq->symb}->{'max'};
  996:         $Str .= '<tr><td>'.&HTML::Entities::encode($seq->compTitle).'</td>'.
  997:             '<td align="right">'.$value.'</td>'.
  998:                 '<td align="right">'.$max.'</td></tr>'."\n";
  999:         $total += $value;
 1000:         $total_max +=$max;
 1001:     }
 1002:     $Str .= '<tr><td><b>'.&mt('Total').'</b></td>'.
 1003:         '<td align="right">'.$total.'</td>'.
 1004:         '<td align="right">'.$total_max."</td></tr>\n";
 1005:     $Str .= "</table>\n";
 1006:     return $Str;
 1007: }
 1008: 
 1009: }
 1010: 
 1011: #######################################################
 1012: #######################################################
 1013: 
 1014: =pod
 1015: 
 1016: =head2 EXCEL subroutines
 1017: 
 1018: =item &excel_initialize($r)
 1019: 
 1020: =item &excel_outputstudent($r,$student)
 1021: 
 1022: =item &excel_finish($r)
 1023: 
 1024: =cut
 1025: 
 1026: #######################################################
 1027: #######################################################
 1028: {
 1029: 
 1030: my $excel_sheet;
 1031: my $excel_workbook;
 1032: my $format;
 1033: 
 1034: my $filename;
 1035: my $rows_output;
 1036: my $cols_output;
 1037: 
 1038: my %prog_state; # progress window state
 1039: my $request_aborted;
 1040: 
 1041: my $total_formula;
 1042: my $maximum_formula;
 1043: my %formula_data;
 1044: 
 1045: my $navmap;
 1046: my @sequences;
 1047: 
 1048: sub excel_cleanup {
 1049:     #
 1050:     undef ($excel_sheet);
 1051:     undef ($excel_workbook);
 1052:     undef ($filename);
 1053:     undef ($rows_output);
 1054:     undef ($cols_output);
 1055:     undef (%prog_state);
 1056:     undef ($request_aborted);
 1057:     undef ($total_formula);
 1058:     undef ($maximum_formula);
 1059:     #
 1060:     undef(%formula_data);
 1061:     #
 1062:     undef($navmap);
 1063:     undef(@sequences);
 1064: }
 1065: 
 1066: sub excel_initialize {
 1067:     my ($r) = @_;
 1068: 
 1069:     &excel_cleanup();
 1070:     ($navmap,@sequences) = 
 1071:         &Apache::lonstatistics::selected_sequences_with_assessments();
 1072:     if (! ref($navmap)) {
 1073:         # Unable to get data, so bail out
 1074:         $r->print("<h3>".
 1075:                   &mt('Unable to retrieve course information.').
 1076:                   '</h3>');
 1077:     }
 1078:     #
 1079:     my $total_columns = scalar(&get_student_fields_to_show());
 1080:     my $num_students = scalar(@Apache::lonstatistics::Students);
 1081:     #
 1082:     foreach my $seq (@sequences) {
 1083:         if ($chosen_output->{'every_problem'}) {
 1084:             $total_columns+=&count_parts($navmap,$seq);
 1085:         }
 1086:         # Add 2 because we need a 'sequence_sum' and 'total' column for each
 1087:         $total_columns += 2;
 1088:     }
 1089:     my $too_many_cols_error_message = 
 1090:         '<h2>'.&mt('Unable to Complete Request').'</h2>'.$/.
 1091:         '<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>'.$/.
 1092:         '<p>'.&mt('You may consider reducing the number of <b>Sequences or Folders</b> you have selected.').'</p>'.$/.
 1093:         '<p>'.&mt('LON-CAPA can produce <b>CSV</b> files of this data or Excel files of the <b>Scores Summary</b> data.').'</p>'.$/;
 1094:     if ($chosen_output->{'base'} eq 'tries' && $total_columns > 255) {
 1095:         $r->print($too_many_cols_error_message);
 1096:         $request_aborted = 1;
 1097:     }
 1098:     if ($chosen_output->{'base'} eq 'scores' && $total_columns > 255) {
 1099:         $r->print($too_many_cols_error_message);
 1100:         $request_aborted = 1;
 1101:     }
 1102:     return if ($request_aborted);
 1103:     #
 1104:     #
 1105:     $excel_workbook = undef;
 1106:     $excel_sheet = undef;
 1107:     #
 1108:     $rows_output = 0;
 1109:     $cols_output = 0;
 1110:     #
 1111:     # Determine rows 
 1112:     my $header_row = $rows_output++;
 1113:     my $description_row = $rows_output++;
 1114:     my $notes_row = $rows_output++;
 1115:     $rows_output++;        # blank row
 1116:     my $summary_header_row;
 1117:     if ($chosen_output->{'summary_table'}) {
 1118:         $summary_header_row = $rows_output++;
 1119:         $rows_output+= scalar(@sequences);
 1120:         $rows_output++;
 1121:     }
 1122:     my $sequence_name_row = $rows_output++;
 1123:     my $resource_name_row = $rows_output++;
 1124:     my $maximum_data_row = $rows_output++;
 1125:     if (! $chosen_output->{'maximum_row'}) {
 1126:         $rows_output--;
 1127:     }
 1128:     my $first_data_row = $rows_output++;
 1129:     #
 1130:     # Create sheet
 1131:     ($excel_workbook,$filename,$format)=
 1132:         &Apache::loncommon::create_workbook($r);
 1133:     return if (! defined($excel_workbook));
 1134:     #
 1135:     # Add a worksheet
 1136:     my $sheetname = $env{'course.'.$env{'request.course.id'}.'.description'};
 1137:     $sheetname = &Apache::loncommon::clean_excel_name($sheetname);
 1138:     $excel_sheet = $excel_workbook->addworksheet($sheetname);
 1139:     #
 1140:     # Put the course description in the header
 1141:     $excel_sheet->write($header_row,$cols_output++,
 1142:                    $env{'course.'.$env{'request.course.id'}.'.description'},
 1143:                         $format->{'h1'});
 1144:     $cols_output += 3;
 1145:     #
 1146:     # Put a description of the sections listed
 1147:     my $sectionstring = '';
 1148:     my @Sections = &Apache::lonstatistics::get_selected_sections();
 1149:     $excel_sheet->write($header_row,$cols_output++,
 1150:                         &Apache::lonstatistics::section_and_enrollment_description('plaintext'),
 1151:                         $format->{'h3'});
 1152:     #
 1153:     # Put the date in there too
 1154:     $excel_sheet->write($header_row,$cols_output++,
 1155:                         'Compiled on '.localtime(time),$format->{'h3'});
 1156:     #
 1157:     $cols_output = 0;
 1158:     $excel_sheet->write($description_row,$cols_output++,
 1159:                         $chosen_output->{'shortdesc'},
 1160:                         $format->{'b'});
 1161:     #
 1162:     $cols_output = 0;
 1163:     $excel_sheet->write($notes_row,$cols_output++,
 1164:                         $chosen_output->{'non_html_notes'},
 1165:                         $format->{'i'});
 1166:     
 1167:     ##############################################
 1168:     # Output headings for the raw data
 1169:     ##############################################
 1170:     #
 1171:     # Add the student headers
 1172:     $cols_output = 0;
 1173:     foreach my $field (&get_student_fields_to_show()) {
 1174:         $excel_sheet->write($resource_name_row,$cols_output++,$field,
 1175:                             $format->{'bold'});
 1176:     }
 1177:     #
 1178:     # Add the remaining column headers
 1179:     my $total_formula_string = '=0';
 1180:     my $maximum_formula_string = '=0';
 1181:     foreach my $seq (@sequences) {
 1182:         my $symb = $seq->symb;
 1183:         $excel_sheet->write($sequence_name_row,,
 1184:                             $cols_output,$seq->compTitle,$format->{'bold'});
 1185:         # Determine starting cell
 1186:         $formula_data{$symb}->{'Excel:startcell'}=
 1187:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1188:             ($first_data_row,$cols_output);
 1189:         $formula_data{$symb}->{'Excel:startcol'}=$cols_output;
 1190:         my $count = 0;
 1191:         if ($chosen_output->{'every_problem'}) {
 1192:             # Put the names of the problems and parts into the sheet
 1193:             foreach my $res (&get_resources($navmap,$seq)) {
 1194:                 if (scalar(@{$res->parts}) > 1) {
 1195:                     foreach my $part (@{$res->parts}) {
 1196:                         $excel_sheet->write($resource_name_row,
 1197:                                             $cols_output++,
 1198:                                             $res->compTitle.' part '.$res->part_display($part),
 1199:                                             $format->{'bold'});
 1200:                         $count++;
 1201:                     }
 1202:                 } else {
 1203:                     $excel_sheet->write($resource_name_row,
 1204:                                         $cols_output++,
 1205:                                         $res->compTitle,$format->{'bold'});
 1206:                     $count++;
 1207:                 }
 1208:             }
 1209:         }
 1210:         # Determine ending cell
 1211:         if ($count <= 1) {
 1212:             $formula_data{$symb}->{'Excel:endcell'} = $formula_data{$symb}->{'Excel:startcell'};
 1213:             $formula_data{$symb}->{'Excel:endcol'}  = $formula_data{$symb}->{'Excel:startcol'};
 1214:         } else {
 1215:             $formula_data{$symb}->{'Excel:endcell'} = 
 1216:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1217:                 ($first_data_row,$cols_output-1);
 1218:             $formula_data{$symb}->{'Excel:endcol'} = $cols_output-1;
 1219:         }
 1220:         # Create the formula for summing up this sequence
 1221:         if (! exists($formula_data{$symb}->{'Excel:endcell'}) ||
 1222:             ! defined($formula_data{$symb}->{'Excel:endcell'})) {
 1223:             $formula_data{$symb}->{'Excel:endcell'} = $formula_data{$symb}->{'Excel:startcell'};
 1224:         }
 1225: 
 1226:         my $start = $formula_data{$symb}->{'Excel:startcell'};
 1227:         my $end = $formula_data{$symb}->{'Excel:endcell'};
 1228:         $formula_data{$symb}->{'Excel:sum'}= $excel_sheet->store_formula
 1229:             ("=IF(COUNT($start\:$end),SUM($start\:$end),\"\")");
 1230:         # Determine cell the score is held in
 1231:         $formula_data{$symb}->{'Excel:scorecell'} = 
 1232:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1233:             ($first_data_row,$cols_output);
 1234:         $formula_data{$symb}->{'Excel:scorecol'}=$cols_output;
 1235:         if ($chosen_output->{'base'} eq 'parts correct total') {
 1236:             $excel_sheet->write($resource_name_row,$cols_output++,
 1237:                                 'parts correct',
 1238:                                 $format->{'bold'});
 1239:         } elsif ($chosen_output->{'sequence_sum'}) {
 1240:             if ($chosen_output->{'correct'}) {
 1241:                 # Only reporting the number correct, so do not call it score
 1242:                 $excel_sheet->write($resource_name_row,$cols_output++,
 1243:                                     'sum',
 1244:                                     $format->{'bold'});
 1245:             } else {
 1246:                 $excel_sheet->write($resource_name_row,$cols_output++,
 1247:                                     'score',
 1248:                                     $format->{'bold'});
 1249:             }
 1250:         }
 1251:         #
 1252:         $total_formula_string.='+'.
 1253:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1254:             ($first_data_row,$cols_output-1);
 1255:         if ($chosen_output->{'sequence_max'}) {
 1256:             $excel_sheet->write($resource_name_row,$cols_output,
 1257:                                 'maximum',
 1258:                                 $format->{'bold'});
 1259:             $formula_data{$symb}->{'Excel:maxcell'} = 
 1260:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1261:                 ($first_data_row,$cols_output);
 1262:             $formula_data{$symb}->{'Excel:maxcol'}=$cols_output;
 1263:             $maximum_formula_string.='+'.
 1264:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1265:                 ($first_data_row,$cols_output);
 1266:             $cols_output++;
 1267: 
 1268:         }
 1269:     }
 1270:     if ($chosen_output->{'grand_total'}) {
 1271:         $excel_sheet->write($resource_name_row,$cols_output++,'Total',
 1272:                             $format->{'bold'});
 1273:     }
 1274:     if ($chosen_output->{'grand_maximum'}) {
 1275:         $excel_sheet->write($resource_name_row,$cols_output++,'Max. Total',
 1276:                             $format->{'bold'});
 1277:     }
 1278:     $total_formula = $excel_sheet->store_formula($total_formula_string);
 1279:     $maximum_formula = $excel_sheet->store_formula($maximum_formula_string);
 1280:     ##############################################
 1281:     # Output a row for MAX, if appropriate
 1282:     ##############################################
 1283:     if ($chosen_output->{'maximum_row'}) {
 1284:         $cols_output = 0;
 1285:         foreach my $field (&get_student_fields_to_show()) {
 1286:             if ($field eq 'username' || $field eq 'fullname' || 
 1287:                 $field eq 'id') {
 1288:                 $excel_sheet->write($maximum_data_row,$cols_output++,'Maximum',
 1289:                                     $format->{'bold'});
 1290:             } else {
 1291:                 $excel_sheet->write($maximum_data_row,$cols_output++,'');
 1292:             }
 1293:         }
 1294:         #
 1295:         # Add the maximums for each sequence or assessment
 1296:         my %total_cell_translation;
 1297:         my %maximum_cell_translation;
 1298:         foreach my $seq (@sequences) {
 1299:             my $symb = $seq->symb;
 1300:             $cols_output=$formula_data{$symb}->{'Excel:startcol'};
 1301:             $total_cell_translation{$formula_data{$symb}->{'Excel:scorecell'}}=
 1302:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1303:                 ($maximum_data_row,$formula_data{$symb}->{'Excel:scorecol'});
 1304:             $maximum_cell_translation{$formula_data{$symb}->{'Excel:maxcell'}}=
 1305:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1306:                 ($maximum_data_row,$formula_data{$symb}->{'Excel:maxcol'});
 1307:             my $weight;
 1308:             my $max = 0;
 1309:             foreach my $resource (&get_resources($navmap,$seq)) {
 1310:                 foreach my $part (@{$resource->parts}){
 1311:                     $weight = 1;
 1312:                     if ($chosen_output->{'scores'}) {
 1313:                         $weight = &Apache::lonnet::EXT
 1314:                             ('resource.'.$part.'.weight',$resource->symb,
 1315:                              undef,undef,undef);
 1316:                         if (!defined($weight) || ($weight eq '')) { 
 1317:                             $weight=1;
 1318:                         }
 1319:                     }
 1320:                     if ($chosen_output->{'scores'} &&
 1321:                         $chosen_output->{'every_problem'}) {
 1322:                         $excel_sheet->write($maximum_data_row,$cols_output++,
 1323:                                             $weight);
 1324:                     }
 1325:                     $max += $weight;
 1326:                 }
 1327:             } 
 1328:             #
 1329:             if ($chosen_output->{'sequence_sum'} && 
 1330:                 $chosen_output->{'every_problem'}) {
 1331: 		my %replaceCells=
 1332: 		    ('^'.$formula_data{$symb}->{'Excel:startcell'}.':'.
 1333: 		         $formula_data{$symb}->{'Excel:endcell'}.'$' =>
 1334: 		     &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($maximum_data_row,$formula_data{$symb}->{'Excel:startcol'}).':'.
 1335: 		     &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($maximum_data_row,$formula_data{$symb}->{'Excel:endcol'}));
 1336:                 $excel_sheet->repeat_formula($maximum_data_row,$cols_output++,
 1337:                                              $formula_data{$symb}->{'Excel:sum'},undef,
 1338: 					     %replaceCells, %replaceCells);
 1339: 			
 1340:             } elsif ($chosen_output->{'sequence_sum'}) {
 1341:                 $excel_sheet->write($maximum_data_row,$cols_output++,$max);
 1342:             }
 1343:             if ($chosen_output->{'sequence_max'}) {
 1344:                 $excel_sheet->write($maximum_data_row,$cols_output++,$max);
 1345:             }
 1346:             #
 1347:         }
 1348:         if ($chosen_output->{'grand_total'}) {
 1349:             $excel_sheet->repeat_formula($maximum_data_row,$cols_output++,
 1350:                                          $total_formula,undef,
 1351:                                          %total_cell_translation);
 1352:         }
 1353:         if ($chosen_output->{'grand_maximum'}) {
 1354:             $excel_sheet->repeat_formula($maximum_data_row,$cols_output++,
 1355:                                          $maximum_formula,undef,
 1356:                                          %maximum_cell_translation);
 1357:         }
 1358:     } # End of MAXIMUM row output  if ($chosen_output->{'maximum_row'}) {
 1359:     $rows_output = $first_data_row;
 1360:     ##############################################
 1361:     # Output summary table, which actually is above the sequence name row.
 1362:     ##############################################
 1363:     if ($chosen_output->{'summary_table'}) {
 1364:         $cols_output = 0;
 1365:         $excel_sheet->write($summary_header_row,$cols_output++,
 1366:                             'Summary Table',$format->{'bold'});
 1367:         if ($chosen_output->{'maximum_row'}) {
 1368:             $excel_sheet->write($summary_header_row,$cols_output++,
 1369:                                 'Maximum',$format->{'bold'});
 1370:         }
 1371:         $excel_sheet->write($summary_header_row,$cols_output++,
 1372:                             'Average',$format->{'bold'});
 1373:         $excel_sheet->write($summary_header_row,$cols_output++,
 1374:                             'Median',$format->{'bold'});
 1375:         $excel_sheet->write($summary_header_row,$cols_output++,
 1376:                             'Std Dev',$format->{'bold'});
 1377:         my $row = $summary_header_row+1;
 1378:         foreach my $seq (@sequences) {
 1379:             my $symb = $seq->symb;
 1380:             $cols_output = 0;
 1381:             $excel_sheet->write($row,$cols_output++,
 1382:                                 $seq->compTitle,
 1383:                                 $format->{'bold'});
 1384:             if ($chosen_output->{'maximum_row'}) {
 1385:                 $excel_sheet->write
 1386:                     ($row,$cols_output++,
 1387:                      '='.
 1388:                      &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1389:                      ($maximum_data_row,$formula_data{$symb}->{'Excel:scorecol'})
 1390:                      );
 1391:             }
 1392:             my $range = 
 1393:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1394:                 ($first_data_row,$formula_data{$symb}->{'Excel:scorecol'}).
 1395:                 ':'.
 1396:                 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1397:                 ($first_data_row+$num_students-1,$formula_data{$symb}->{'Excel:scorecol'});
 1398:             $excel_sheet->write($row,$cols_output++,
 1399:                                 '=AVERAGE('.$range.')');
 1400:             $excel_sheet->write($row,$cols_output++,
 1401:                                 '=MEDIAN('.$range.')');
 1402:             $excel_sheet->write($row,$cols_output++,
 1403:                                 '=STDEV('.$range.')');
 1404:             $row++;
 1405:         }
 1406:     }
 1407:     ##############################################
 1408:     #   Take care of non-excel initialization
 1409:     ##############################################
 1410:     #
 1411:     # Let the user know what we are doing
 1412:     my $studentcount = scalar(@Apache::lonstatistics::Students); 
 1413:     if ($env{'form.SelectedStudent'}) {
 1414:         $studentcount = '1';
 1415:     }
 1416:     if ($studentcount > 1) {
 1417:         $r->print('<h1>'.&mt('Compiling Excel spreadsheet for [_1] students',
 1418:                              $studentcount)."</h1>\n");
 1419:     } else {
 1420:         $r->print('<h1>'.
 1421:                   &mt('Compiling Excel spreadsheet for 1 student').
 1422:                   "</h1>\n");
 1423:     }
 1424:     $r->rflush();
 1425:     #
 1426:     # Initialize progress window
 1427:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1428:         ($r,'Excel File Compilation Status',
 1429:          'Excel File Compilation Progress', $studentcount,
 1430:          'inline',undef,'Statistics','stats_status');
 1431:     #
 1432:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 1433:                                           'Processing first student');
 1434:     return;
 1435: }
 1436: 
 1437: sub excel_outputstudent {
 1438:     my ($r,$student) = @_;
 1439:     if ($request_aborted || ! defined($navmap) || ! defined($excel_sheet)) {
 1440:         return;
 1441:     }
 1442:     $cols_output=0;
 1443:     #
 1444:     # Write out student data
 1445:     my @to_show = &get_student_fields_to_show();
 1446:     foreach my $field (@to_show) {
 1447:         my $value = $student->{$field};
 1448:         if ($field eq 'comments') {
 1449:             $value = &Apache::lonmsgdisplay::retrieve_instructor_comments
 1450:                 ($student->{'username'},$student->{'domain'});
 1451:         }
 1452:         $excel_sheet->write($rows_output,$cols_output++,$value);
 1453:     }
 1454:     #
 1455:     # Get student assessment data
 1456:     my %StudentsData;
 1457:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
 1458:                                                         $student->{'domain'},
 1459:                                                         undef,
 1460:                                                    $env{'request.course.id'});
 1461:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 1462:         %StudentsData = @tmp;
 1463:     }
 1464:     #
 1465:     # Write out sequence scores and totals data
 1466:     my %total_cell_translation;
 1467:     my %maximum_cell_translation;
 1468:     foreach my $seq (@sequences) {
 1469:         my $symb = $seq->symb;
 1470:         $cols_output = $formula_data{$symb}->{'Excel:startcol'};
 1471:         # Keep track of cells to translate in total cell
 1472:         $total_cell_translation{$formula_data{$symb}->{'Excel:scorecell'}} = 
 1473:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1474:                         ($rows_output,$formula_data{$symb}->{'Excel:scorecol'});
 1475:         # and maximum cell
 1476:         $maximum_cell_translation{$formula_data{$symb}->{'Excel:maxcell'}} = 
 1477:             &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell
 1478:             ($rows_output,$formula_data{$symb}->{'Excel:maxcol'});
 1479:         #
 1480:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
 1481:         if ($chosen_output->{'tries'} || $chosen_output->{'correct'}){
 1482:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1483:                 &student_tries_on_sequence($student,\%StudentsData,
 1484:                                            $navmap,$seq,'no');
 1485:         } else {
 1486:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1487:                 &student_performance_on_sequence($student,\%StudentsData,
 1488:                                                  $navmap,$seq,'no',
 1489:                                                  $chosen_output->{ignore_weight});
 1490:         } 
 1491:         if ($chosen_output->{'every_problem'}) {
 1492:             if ($chosen_output->{'correct'}) {
 1493:                 # only indiciate if each item is correct or not
 1494:                 foreach my $value (@$rawdata) {
 1495:                     # positive means correct, 0 or negative means
 1496:                     # incorrect
 1497:                     $value = $value > 0 ? 1 : 0;
 1498:                     $excel_sheet->write($rows_output,$cols_output++,$value);
 1499:                 }
 1500:             } else {
 1501:                 foreach my $value (@$rawdata) {
 1502:                     if ($score eq ' ' || !defined($value)) {
 1503:                         $cols_output++;
 1504:                     } else {                        
 1505:                         $excel_sheet->write($rows_output,$cols_output++,
 1506:                                             $value);
 1507:                     }
 1508:                 }
 1509:             }
 1510:         }
 1511:         if ($chosen_output->{'sequence_sum'} && 
 1512:             $chosen_output->{'every_problem'}) {
 1513:             # Write a formula for the sum of this sequence
 1514:             my %replaceCells=
 1515: 		('^'.$formula_data{$symb}->{'Excel:startcell'}.':'.$formula_data{$symb}->{'Excel:endcell'}.'$'
 1516: 		 => 
 1517: 		 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($rows_output,$formula_data{$symb}->{'Excel:startcol'}).':'.
 1518: 		 &Spreadsheet::WriteExcel::Utility::xl_rowcol_to_cell($rows_output,$formula_data{$symb}->{'Excel:endcol'})
 1519: 		 );
 1520:             # The undef is for the format	    
 1521: 	    $excel_sheet->repeat_formula($rows_output,$cols_output++,
 1522: 					 $formula_data{$symb}->{'Excel:sum'},undef,
 1523: 					 %replaceCells, %replaceCells);
 1524:         } elsif ($chosen_output->{'sequence_sum'}) {
 1525:             if ($score eq ' ') {
 1526:                 $cols_output++;
 1527:             } else {
 1528:                 $excel_sheet->write($rows_output,$cols_output++,$score);
 1529:             }
 1530:         }
 1531:         if ($chosen_output->{'sequence_max'}) {
 1532:             $excel_sheet->write($rows_output,$cols_output++,$seq_max);
 1533:         }
 1534:     }
 1535:     #
 1536:     if ($chosen_output->{'grand_total'}) {
 1537:         $excel_sheet->repeat_formula($rows_output,$cols_output++,
 1538:                                      $total_formula,undef,
 1539:                                      %total_cell_translation);
 1540:     }
 1541:     if ($chosen_output->{'grand_maximum'}) {
 1542:         $excel_sheet->repeat_formula($rows_output,$cols_output++,
 1543:                                      $maximum_formula,undef,
 1544:                                      %maximum_cell_translation);
 1545:     }
 1546:     #
 1547:     # Bookkeeping
 1548:     $rows_output++; 
 1549:     $cols_output=0;
 1550:     #
 1551:     # Update the progress window
 1552:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 1553:     return;
 1554: }
 1555: 
 1556: sub excel_finish {
 1557:     my ($r) = @_;
 1558:     if ($request_aborted || ! defined($navmap) || ! defined($excel_sheet)) {
 1559: 	&excel_cleanup();
 1560:         return;
 1561:     }
 1562:     #
 1563:     # Write the excel file
 1564:     $excel_workbook->close();
 1565:     #
 1566:     # Close the progress window
 1567:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1568:     #
 1569:     # Tell the user where to get their excel file
 1570:     $r->print('<br />'.
 1571:               '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
 1572:     $r->rflush();
 1573:     &excel_cleanup();
 1574:     return;
 1575: }
 1576: 
 1577: }
 1578: #######################################################
 1579: #######################################################
 1580: 
 1581: =pod
 1582: 
 1583: =head2 CSV output routines
 1584: 
 1585: =item &csv_initialize($r)
 1586: 
 1587: =item &csv_outputstudent($r,$student)
 1588: 
 1589: =item &csv_finish($r)
 1590: 
 1591: =cut
 1592: 
 1593: #######################################################
 1594: #######################################################
 1595: {
 1596: 
 1597: my $outputfile;
 1598: my $filename;
 1599: my $request_aborted;
 1600: my %prog_state; # progress window state
 1601: my $navmap;
 1602: my @sequences;
 1603: 
 1604: sub csv_cleanup {
 1605:     undef($outputfile);
 1606:     undef($filename);
 1607:     undef($request_aborted);
 1608:     undef(%prog_state);
 1609:     #
 1610:     undef($navmap);
 1611:     undef(@sequences);
 1612: }
 1613: 
 1614: sub csv_initialize{
 1615:     my ($r) = @_;
 1616: 
 1617:     &csv_cleanup();
 1618:     ($navmap,@sequences) = 
 1619:         &Apache::lonstatistics::selected_sequences_with_assessments();
 1620:     if (! ref($navmap)) {
 1621:         # Unable to get data, so bail out
 1622:         $r->print("<h3>".
 1623:                   &mt('Unable to retrieve course information.').
 1624:                   '</h3>');
 1625:     }
 1626:     #
 1627:     # Deal with unimplemented requests
 1628:     $request_aborted = undef;
 1629:     if ($chosen_output->{'base'} =~ /final table/) {
 1630:         $r->print(<<END);
 1631: <h2>Unable to Complete Request</h2>
 1632: <p>
 1633: The <b>Summary Table (Scores)</b> option is not available for non-HTML output.
 1634: </p>
 1635: END
 1636:        $request_aborted = 1;
 1637:     }
 1638:     return if ($request_aborted);
 1639:     #
 1640:     # Initialize progress window
 1641:     my $studentcount = scalar(@Apache::lonstatistics::Students);
 1642:     %prog_state=&Apache::lonhtmlcommon::Create_PrgWin
 1643:         ($r,'CSV File Compilation Status',
 1644:          'CSV File Compilation Progress', $studentcount,
 1645:          'inline',undef,'Statistics','stats_status');
 1646:     #
 1647:     # Open a file
 1648:     ($outputfile,$filename) = &Apache::loncommon::create_text_file($r,'csv');
 1649:     if (! defined($outputfile)) { return ''; }
 1650:     #
 1651:     # Datestamp
 1652:     my $description = $env{'course.'.$env{'request.course.id'}.'.description'};
 1653:     print $outputfile '"'.&Apache::loncommon::csv_translate($description).'",'.
 1654:         '"'.&Apache::loncommon::csv_translate(scalar(localtime(time))).'"'.
 1655:             "\n";
 1656:     print $outputfile '"'.
 1657:         &Apache::loncommon::csv_translate
 1658:         (&Apache::lonstatistics::section_and_enrollment_description()).
 1659:         '"'."\n";
 1660:     foreach my $item ('shortdesc','non_html_notes') {
 1661:         next if (! exists($chosen_output->{$item}));
 1662:         print $outputfile 
 1663:             '"'.&Apache::loncommon::csv_translate($chosen_output->{$item}).'"'.
 1664:             "\n";
 1665:     }
 1666:     #
 1667:     # Print out the headings
 1668:     my $sequence_row = '';
 1669:     my $resource_row = undef;
 1670:     foreach my $field (&get_student_fields_to_show()) {
 1671:         $sequence_row .='"",';
 1672:         $resource_row .= '"'.&Apache::loncommon::csv_translate($field).'",';
 1673:     }
 1674:     foreach my $seq (@sequences) {
 1675:         $sequence_row .= '"'.
 1676:             &Apache::loncommon::csv_translate($seq->compTitle).'",';
 1677:         my $count = 0;
 1678:         if ($chosen_output->{'every_problem'}) {
 1679:             foreach my $res (&get_resources($navmap,$seq)) {
 1680:                 if (scalar(@{$res->parts}) < 1) {
 1681:                     next;
 1682:                 }
 1683:                 foreach my $part (@{$res->parts}) {
 1684:                     $resource_row .= '"'.
 1685:                         &Apache::loncommon::csv_translate
 1686:                         ($res->compTitle.', Part '.$res->part_display($part)).'",';
 1687:                     $count++;
 1688:                 }
 1689:             }
 1690:         }
 1691:         $sequence_row.='"",'x$count;
 1692:         if ($chosen_output->{'sequence_sum'}) {
 1693:             if($chosen_output->{'correct'}) {
 1694:                 $resource_row .= '"sum",';
 1695:             } else {
 1696:                 $resource_row .= '"score",';
 1697:             }
 1698:         }
 1699:         if ($chosen_output->{'sequence_max'}) {
 1700:             $sequence_row.= '"",';
 1701:             $resource_row .= '"maximum possible",';
 1702:         }
 1703:     }
 1704:     if ($chosen_output->{'grand_total'}) {
 1705:         $sequence_row.= '"",';
 1706:         $resource_row.= '"Total",';
 1707:     } 
 1708:     if ($chosen_output->{'grand_maximum'}) {
 1709:         $sequence_row.= '"",';
 1710:         $resource_row.= '"Maximum",';
 1711:     } 
 1712:     chomp($sequence_row);
 1713:     chomp($resource_row);
 1714:     print $outputfile $sequence_row."\n";
 1715:     print $outputfile $resource_row."\n";
 1716:     return;
 1717: }
 1718: 
 1719: sub csv_outputstudent {
 1720:     my ($r,$student) = @_;
 1721:     if ($request_aborted || ! defined($navmap) || ! defined($outputfile)) {
 1722:         return;
 1723:     }
 1724:     my $Str = '';
 1725:     #
 1726:     # Output student fields
 1727:     my @to_show = &get_student_fields_to_show();
 1728:     foreach my $field (@to_show) {
 1729:         my $value = $student->{$field};
 1730:         if ($field eq 'comments') {
 1731:             $value = &Apache::lonmsgdisplay::retrieve_instructor_comments
 1732:                 ($student->{'username'},$student->{'domain'});
 1733:         }        
 1734:         $Str .= '"'.&Apache::loncommon::csv_translate($value).'",';
 1735:     }
 1736:     #
 1737:     # Get student assessment data
 1738:     my %StudentsData;
 1739:     my @tmp = &Apache::loncoursedata::get_current_state($student->{'username'},
 1740:                                                         $student->{'domain'},
 1741:                                                         undef,
 1742:                                                    $env{'request.course.id'});
 1743:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 1744:         %StudentsData = @tmp;
 1745:     }
 1746:     #
 1747:     # Output performance data
 1748:     my $total = 0;
 1749:     my $maximum = 0;
 1750:     foreach my $seq (@sequences) {
 1751:         my ($performance,$performance_length,$score,$seq_max,$rawdata);
 1752:         if ($chosen_output->{'tries'}){
 1753:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1754:                 &student_tries_on_sequence($student,\%StudentsData,
 1755:                                            $navmap,$seq,'no');
 1756:         } else {
 1757:             ($performance,$performance_length,$score,$seq_max,$rawdata) =
 1758:                 &student_performance_on_sequence($student,\%StudentsData,
 1759:                                                  $navmap,$seq,'no',
 1760:                                                  $chosen_output->{ignore_weight});
 1761:         }
 1762:         if ($chosen_output->{'every_problem'}) {
 1763:             if ($chosen_output->{'correct'}) {
 1764:                 $score = 0;
 1765:                 # Deal with number of parts correct data
 1766:                 $Str .= '"'.join('","',( map { if ($_>0) { 
 1767:                                                    $score += 1;
 1768:                                                    1; 
 1769:                                                } else { 
 1770:                                                    0; 
 1771:                                                }
 1772:                                              } @$rawdata)).'",';
 1773:             } else {
 1774:                 $Str .= '"'.join('","',(@$rawdata)).'",';
 1775:             }
 1776:         }
 1777:         if ($chosen_output->{'sequence_sum'}) {
 1778:             $Str .= '"'.$score.'",';
 1779:         } 
 1780:         if ($chosen_output->{'sequence_max'}) {
 1781:             $Str .= '"'.$seq_max.'",';
 1782:         }
 1783:         $total+=$score;
 1784:         $maximum += $seq_max;
 1785:     }
 1786:     if ($chosen_output->{'grand_total'}) {
 1787:         $Str .= '"'.$total.'",';
 1788:     }
 1789:     if ($chosen_output->{'grand_maximum'}) {
 1790:         $Str .= '"'.$maximum.'",';
 1791:     }
 1792:     chop($Str);
 1793:     $Str .= "\n";
 1794:     print $outputfile $Str;
 1795:     #
 1796:     # Update the progress window
 1797:     &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last student');
 1798:     return;
 1799: }
 1800: 
 1801: sub csv_finish {
 1802:     my ($r) = @_;
 1803:     if ($request_aborted || ! defined($navmap) || ! defined($outputfile)) {
 1804: 	&csv_cleanup();
 1805:         return;
 1806:     }
 1807:     close($outputfile);
 1808:     #
 1809:     # Close the progress window
 1810:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 1811:     #
 1812:     # Tell the user where to get their csv file
 1813:     $r->print('<br />'.
 1814:               '<a href="'.$filename.'">'.&mt('Your csv file.').'</a>'."\n");
 1815:     $r->rflush();
 1816:     &csv_cleanup();
 1817:     return;
 1818:     
 1819: }
 1820: 
 1821: }
 1822: 
 1823: # This function will return an HTML string including a star, with
 1824: # a mouseover popup showing the "real" value. An optional second
 1825: # argument lets you show something other than a star.
 1826: sub show_star {
 1827:     my $popup = shift;
 1828:     my $symbol = shift || '*';
 1829:     # Escape the popup for JS.
 1830:     $popup =~ s/([^-a-zA-Z0-9:;,._ ()|!\/?=&*])/'\\' . sprintf("%lo", ord($1))/ge;
 1831:     
 1832:     return "<span onmouseover='popup_score(this, \"$popup\");return false;' onmouseout='popdown_score();return false;' style='border: 1px solid #339933; margin: -1px;'>$symbol</span>";
 1833: }
 1834: 
 1835: #######################################################
 1836: #######################################################
 1837: 
 1838: =pod
 1839: 
 1840: =item &StudentTriesOnSequence()
 1841: 
 1842: Inputs:
 1843: 
 1844: =over 4
 1845: 
 1846: =item $student
 1847: 
 1848: =item $studentdata Hash ref to all student data
 1849: 
 1850: =item $seq Hash ref, the sequence we are working on
 1851: 
 1852: =item $links if defined we will output links to each resource.
 1853: 
 1854: =back
 1855: 
 1856: =cut
 1857: 
 1858: #######################################################
 1859: #######################################################
 1860: sub student_tries_on_sequence {
 1861:     my ($student,$studentdata,$navmap,$seq,$links) = @_;
 1862:     $links = 'no' if (! defined($links));
 1863:     my $Str = '';
 1864:     my ($sum,$max) = (0,0);
 1865:     my $performance_length = 0;
 1866:     my @TriesData = ();
 1867:     my $tries;
 1868:     my $hasdata = 0; # flag - true if the student has any data on the sequence
 1869:     foreach my $resource (&get_resources($navmap,$seq)) {
 1870:         my $resource_data = $studentdata->{$resource->symb};
 1871:         my $value = '';
 1872:         foreach my $partnum (@{$resource->parts()}) {
 1873:             $tries = undef;
 1874:             $max++;
 1875:             $performance_length++;
 1876:             my $symbol = ' '; # default to space
 1877:             #
 1878:             my $awarded = 0;
 1879:             if (exists($resource_data->{'resource.'.$partnum.'.awarded'})) {
 1880:                 $awarded = $resource_data->{'resource.'.$partnum.'.awarded'};
 1881:                 $awarded = 0 if (! $awarded);
 1882:             }
 1883:             #
 1884:             my $status = '';
 1885:             if (exists($resource_data->{'resource.'.$partnum.'.solved'})) {
 1886:                 $status = $resource_data->{'resource.'.$partnum.'.solved'};
 1887:             }
 1888:             #
 1889:             my $tries = 0;
 1890:             if(exists($resource_data->{'resource.'.$partnum.'.tries'})) {
 1891:                 $tries = $resource_data->{'resource.'.$partnum.'.tries'};
 1892:                 $hasdata =1;
 1893:             }
 1894:             #
 1895:             if ($awarded > 0) {
 1896:                 # The student has gotten the problem correct to some degree
 1897:                 if ($status eq 'excused') {
 1898:                     $symbol = 'x';
 1899:                     $max--;
 1900:                 } elsif ($status eq 'correct_by_override' && !$resource->is_task()) {
 1901:                     $symbol = '+';
 1902:                     $sum++;
 1903:                 } elsif ($tries > 0) {
 1904:                     if ($tries > 9) {
 1905:                         $symbol = show_star($tries);
 1906:                     } else {
 1907:                         $symbol = $tries;
 1908:                     }
 1909:                     $sum++;
 1910:                 } else {
 1911:                     $symbol = '+';
 1912:                     $sum++;
 1913:                 }
 1914:             } else {
 1915:                 # The student has the problem incorrect or it is ungraded
 1916:                 if ($status eq 'excused') {
 1917:                     $symbol = 'x';
 1918:                     $max--;
 1919:                 } elsif ($status eq 'incorrect_by_override') {
 1920:                     $symbol = '-';
 1921:                 } elsif ($status eq 'ungraded_attempted') {
 1922:                     $symbol = 'u';
 1923:                 } elsif ($status eq 'incorrect_attempted' ||
 1924:                          $tries > 0)  {
 1925:                     $symbol = '.';
 1926:                 } else {
 1927:                     # Problem is wrong and has not been attempted.
 1928:                     $symbol=' ';
 1929:                 }
 1930:             }
 1931:             #
 1932:             if (! defined($tries)) {
 1933:                 $tries = 0;
 1934:             }
 1935:             if ($status =~ /^(incorrect|ungraded)/) {
 1936:                 # Bug 3390: show '-' for tries on incorrect problems 
 1937:                 # (csv & excel only)
 1938:                 push(@TriesData,-$tries);
 1939:             } else {
 1940:                 push (@TriesData,$tries);
 1941:             }
 1942:             #
 1943:             if ( ($links eq 'yes' && $symbol ne ' ') ||
 1944:                  ($links eq 'all')) {
 1945:                 if (length($symbol) > 1) {
 1946:                     &Apache::lonnet::logthis('length of symbol "'.$symbol.'" > 1');
 1947:                 }
 1948:                 my $link = '/adm/grades'.
 1949:                     '?symb='.&Apache::lonnet::escape($resource->symb).
 1950:                         '&student='.$student->{'username'}.
 1951:                             '&userdom='.$student->{'domain'}.
 1952:                                 '&command=submission';
 1953:                 $symbol = &link($symbol, $link);
 1954:             }
 1955:             $value .= $symbol;
 1956:         }
 1957:         $Str .= $value;
 1958:     }
 1959:     if ($seq->randompick()) {
 1960:         $max = $seq->randompick();
 1961:     }
 1962:     if (! $hasdata && $sum == 0) {
 1963:         $sum = ' ';
 1964:     }
 1965:     return ($Str,$performance_length,$sum,$max,\@TriesData);
 1966: }
 1967: 
 1968: =pod
 1969: 
 1970: =item &link
 1971: 
 1972: Inputs:
 1973: 
 1974: =over 4
 1975: 
 1976: =item $text
 1977: 
 1978: =item $target
 1979: 
 1980: =back
 1981: 
 1982: Takes the text and creates a link to the $text that honors
 1983: the value of 'new window' if clicked on, but uses a real 
 1984: 'href' so middle and right clicks still work.
 1985: 
 1986: $target and $text are assumed to be already correctly escaped; i.e., it
 1987: can be dumped out directly into the output stream as-is.
 1988: 
 1989: =cut
 1990: 
 1991: sub link {
 1992:     my ($text,$target) = @_;
 1993:     return 
 1994:         "<a href='$target' onclick=\"t=this.href;if(new_window)"
 1995:         ."{window.open(t)}else{return void(window."
 1996:         ."location=t)};return false;\">$text</a>";
 1997: }
 1998: 
 1999: #######################################################
 2000: #######################################################
 2001: 
 2002: =pod
 2003: 
 2004: =item &student_performance_on_sequence
 2005: 
 2006: Inputs:
 2007: 
 2008: =over 4
 2009: 
 2010: =item $student
 2011: 
 2012: =item $studentdata Hash ref to all student data
 2013: 
 2014: =item $seq Hash ref, the sequence we are working on
 2015: 
 2016: =item $links if defined we will output links to each resource.
 2017: 
 2018: =back
 2019: 
 2020: =cut
 2021: 
 2022: #######################################################
 2023: #######################################################
 2024: sub student_performance_on_sequence {
 2025:     my ($student,$studentdata,$navmap,$seq,$links,$awarded_only) = @_;
 2026:     $links = 'no' if (! defined($links));
 2027:     my $Str = ''; # final result string
 2028:     my ($score,$max) = (0,0);
 2029:     my $performance_length = 0;
 2030:     my $symbol;
 2031:     my @ScoreData = ();
 2032:     my $partscore;
 2033:     my $hasdata = 0; # flag, 0 if there were no submissions on the sequence
 2034:     foreach my $resource (&get_resources($navmap,$seq)) {
 2035:         my $symb = $resource->symb;
 2036:         my $resource_data = $studentdata->{$symb};
 2037:         foreach my $part (@{$resource->parts()}) {
 2038:             $partscore = undef;
 2039:             my $weight;
 2040:             if (!$awarded_only){
 2041:                 $weight = &Apache::lonnet::EXT('resource.'.$part.'.weight',
 2042:                                                $symb,
 2043:                                                $student->{'domain'},
 2044:                                                $student->{'username'},
 2045:                                                $student->{'section'});
 2046:             }
 2047:             if (!defined($weight) || ($weight eq '')) { 
 2048:                 $weight=1;
 2049:             }
 2050:             #
 2051:             $max += $weight; # see the 'excused' branch below...
 2052:             $performance_length++; # one character per part
 2053:             $symbol = ' '; # default to space
 2054:             #
 2055:             my $awarded;
 2056:             if (exists($resource_data->{'resource.'.$part.'.awarded'})) {
 2057:                 $awarded = $resource_data->{'resource.'.$part.'.awarded'};
 2058:                 $awarded = 0 if (! $awarded);
 2059:                 $hasdata = 1;
 2060:             }
 2061:             #
 2062:             $partscore = &Apache::grades::compute_points($weight,$awarded);
 2063:             if (! defined($awarded)) {
 2064:                 $partscore = undef;
 2065:             }
 2066:             $score += $partscore;
 2067:             $symbol = $partscore; 
 2068:             if (abs($symbol - sprintf("%.0f",$symbol)) < 0.001) {
 2069:                 $symbol = sprintf("%.0f",$symbol);
 2070:             }
 2071:             if (length($symbol) > 1) {
 2072:                 $symbol = show_star($symbol);
 2073:             }
 2074:             if (exists($resource_data->{'resource.'.$part.'.solved'}) &&
 2075:                 $resource_data->{'resource.'.$part.'.solved'} ne '') {
 2076:                 my $status = $resource_data->{'resource.'.$part.'.solved'};
 2077:                 if ($status eq 'excused') {
 2078:                     $symbol = 'x';
 2079:                     $max -= $weight; # Do not count 'excused' problems.
 2080:                 } elsif ($status eq 'ungraded_attempted') {
 2081:                     $symbol = 'u';
 2082:                 }
 2083:                 $hasdata = 1;
 2084:             } elsif ($resource_data->{'resource.'.$part.'.award'} eq 'DRAFT') {
 2085:                 $symbol = 'd';
 2086:                 $hasdata = 1;
 2087:             } elsif (!exists($resource_data->{'resource.'.$part.'.awarded'})){
 2088:                 # Unsolved.  Did they try?
 2089:                 if (exists($resource_data->{'resource.'.$part.'.tries'})){
 2090:                     $symbol = '.';
 2091:                     $hasdata = 1;
 2092:                 } else {
 2093:                     $symbol = ' ';
 2094:                 }
 2095:             }
 2096:             #
 2097:             if (! defined($partscore)) {
 2098:                 $partscore = $symbol;
 2099:             }
 2100:             push (@ScoreData,$partscore);
 2101:             #
 2102:             if ( ($links eq 'yes' && $symbol ne ' ') || ($links eq 'all')) {
 2103:                 my $link = '/adm/grades' .
 2104:                     '?symb='.&Apache::lonnet::escape($symb).
 2105:                     '&student='.$student->{'username'}.
 2106:                     '&userdom='.$student->{'domain'}.
 2107:                     '&command=submission';
 2108:                 $symbol = &link($symbol, $link);
 2109:             }
 2110:             $Str .= $symbol;
 2111:         }
 2112:     }
 2113:     if (! $hasdata && $score == 0) {
 2114:         $score = ' ';
 2115:     }
 2116:     return ($Str,$performance_length,$score,$max,\@ScoreData);
 2117: }
 2118: 
 2119: #######################################################
 2120: #######################################################
 2121: 
 2122: =pod
 2123: 
 2124: =item &CreateLegend()
 2125: 
 2126: This function returns a formatted string containing the legend for the
 2127: chart.  The legend describes the symbols used to represent grades for
 2128: problems.
 2129: 
 2130: =cut
 2131: 
 2132: #######################################################
 2133: #######################################################
 2134: sub CreateLegend {
 2135:     my $Str = "<p><pre>".
 2136:               " digit score or number of tries to get correct ".
 2137:               "   *  correct by student in more than 9 tries\n".
 2138: 	      "   +  correct by hand grading or override\n".
 2139:               "   -  incorrect by override\n".
 2140: 	      "   .  incorrect attempted\n".
 2141: 	      "   u  ungraded attempted\n".
 2142:               "   d  draft answer saved but not submitted\n".
 2143:               "      not attempted (blank field)\n".
 2144: 	      "   x  excused".
 2145:               "</pre><p>";
 2146:     return $Str;
 2147: }
 2148: 
 2149: #######################################################
 2150: #######################################################
 2151: 
 2152: =pod 
 2153: 
 2154: =back
 2155: 
 2156: =cut
 2157: 
 2158: #######################################################
 2159: #######################################################
 2160: 
 2161: 1;
 2162: 
 2163: __END__

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