File:  [LON-CAPA] / loncom / interface / statistics / lonstudentassessment.pm
Revision 1.164: download - view: text, annotated - select for diffs
Wed Oct 5 18:56:00 2011 UTC (12 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
- CHART now shows correct total possible points where folder is using
  randompick and all items included in folder carry equal points.

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

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