File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.128: download - view: text, annotated - select for diffs
Tue Dec 10 04:52:30 2024 UTC (2 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Change in args that can be passed to navmap->new(). Third arg is now
  user's section. Supports case where a navmap object is instantiated for a
  specific user (who may be in a different section).

    1: # The LearningOnline Network with CAPA
    2: # Quick Student Grades Display
    3: #
    4: # $Id: lonquickgrades.pm,v 1.128 2024/12/10 04:52:30 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::lonquickgrades;
   30: 
   31: use strict;
   32: use Apache::Constants qw(:common :http REDIRECT);
   33: use POSIX;
   34: use Apache::loncommon;
   35: use Apache::lonlocal;
   36: use Apache::lonnet;
   37: use Apache::grades;
   38: use Apache::loncoursedata;
   39: use Apache::lonstudentassessment;
   40: use Apache::lonuserstate;
   41: 
   42: use Time::HiRes;
   43: use Spreadsheet::WriteExcel;
   44: use Spreadsheet::WriteExcel::Utility();
   45: #
   46: # Excel data
   47: #
   48: my $excel_sheet;
   49: my $excel_workbook;
   50: my $filename;
   51: my $format;
   52: my $request_aborted;
   53: my $header_row;
   54: my $cols_output;
   55: my %prog_state;
   56: 
   57: 
   58: sub handler {
   59:     my $r = shift;
   60:     return real_handler($r);
   61: }
   62: 
   63: sub real_handler {
   64:     my $r = shift;
   65: 
   66:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
   67: 
   68:     # Handle header-only request
   69:     if ($env{'browser.mathml'}) {
   70: 	&Apache::loncommon::content_type($r,'text/xml');
   71:     } else {
   72: 	&Apache::loncommon::content_type($r,'text/html');
   73:     }
   74:     if ($r->header_only) {
   75: 	$r->send_http_header;
   76:         return OK;
   77:     }
   78: 
   79:     my $cangrade=&Apache::lonnet::allowed('mgr');
   80:     my $showPoints =
   81:         (($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'standard')
   82:       || ($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'categories'));
   83: 
   84:     my $reinitresult;
   85: 
   86:     if ($env{'request.course.id'}) {
   87:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
   88:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
   89:         my $clientip = &Apache::lonnet::get_requestor_ip($r);
   90:         my ($blocked,$blocktext) =
   91:             &Apache::loncommon::blocking_status('grades',$clientip,$cnum,$cdom);
   92:         if ($blocked) {
   93:             my $checkrole = "cm./$cdom/$cnum";
   94:             if ($env{'request.course.sec'} ne '') {
   95:                 $checkrole .= "/$env{'request.course.sec'}";
   96:             }
   97:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
   98:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
   99:                 &grades_blocked($r,$blocktext,$showPoints);
  100:                 return OK;
  101:             }
  102:         }
  103:     }
  104: 
  105:     unless ($cangrade) {
  106:         # Check for critical messages and redirect if present.
  107:         my ($redirect,$url) = &Apache::loncommon::critical_redirect(300,'grades');
  108:         if ($redirect) {
  109:             &Apache::loncommon::content_type($r,'text/html');
  110:             $r->header_out(Location => $url);
  111:             return REDIRECT;
  112:         }
  113: 
  114:         # Check if course needs to be re-initialized
  115:         my $loncaparev = $r->dir_config('lonVersion');
  116:         ($reinitresult,my @reinit) = &Apache::loncommon::needs_coursereinit($loncaparev);
  117: 
  118:         if ($reinitresult eq 'switch') {
  119:             &Apache::loncommon::content_type($r,'text/html');
  120:             $r->send_http_header;
  121:             $r->print(&Apache::loncommon::check_release_result(@reinit));
  122:             return OK;
  123:         }
  124:         my ($cid,$cnum,$cdom);
  125:         if ($reinitresult) {
  126:             $cid = $env{'request.course.id'};
  127:             $cnum = $env{'course.'.$cid.'.num'};
  128:             $cdom = $env{'course.'.$cid.'.domain'};
  129:         }
  130:         if (($reinitresult eq 'main') || ($reinitresult eq 'both')) {
  131:             &Apache::loncommon::content_type($r,'text/html');
  132:             $r->send_http_header;
  133:             &startpage($r,$showPoints);
  134:             my $preamble = '<div id="LC_update_'.$cid.'" class="LC_info">'.
  135:                            '<br />'.
  136:                            &mt('Your course session is being updated because of recent changes by course personnel.').
  137:                            ' '.&mt('Please be patient').'.<br /></div>'.
  138:                            '<div style="padding:0;clear:both;margin:0;border:0"></div>';
  139:             %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,undef,$preamble);
  140:             &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,&mt('Updating course'));
  141:             $r->rflush();
  142:             my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
  143:             &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,&mt('Finished!')); 
  144:             &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  145:             my $closure = <<ENDCLOSE;
  146: <script type="text/javascript">
  147: // <![CDATA[
  148: \$("#LC_update_$cid").hide('slow');
  149: // ]]>
  150: </script>
  151: ENDCLOSE
  152:             if ($ferr) {
  153:                 $r->print($closure.&Apache::loncommon::end_page());
  154:                 my $requrl = $r->uri;
  155:                 $env{'user.error.msg'}="$requrl:bre:0:0:Course not initialized";
  156:                 $env{'user.reinit'} = 1;
  157:                 return HTTP_NOT_ACCEPTABLE;
  158:             } else {
  159:                $r->print($closure);
  160:             }
  161:         } elsif ((&Apache::loncommon::course_type() eq 'Placement') &&
  162:                  (!$env{'request.role.adv'})) {
  163:             my $furl = &Apache::lonpageflip::first_accessible_resource();
  164:             &Apache::loncommon::content_type($r,'text/html');
  165:             $r->header_out(Location => $furl);
  166:             return REDIRECT;
  167:         }
  168:         if (($reinitresult eq 'supp') || ($reinitresult eq 'both')) {
  169:             my $possdel;
  170:             if ($reinitresult eq 'supp') {
  171:                 $possdel = 1;
  172:             }
  173:             my ($supplemental,$refs_updated) = &Apache::loncommon::get_supplemental($cnum,$cdom,'',$possdel);
  174:             unless ($refs_updated) {
  175:                 &Apache::loncommon::set_supp_httprefs($cnum,$cdom,$supplemental);
  176:             }
  177:         }
  178:     }
  179: 
  180:     unless (($reinitresult eq 'main') || ($reinitresult eq 'both')) {
  181:         # Send header, don't cache this page
  182:         &Apache::loncommon::no_cache($r);
  183:         $r->send_http_header;
  184:         &startpage($r,$showPoints);
  185:     }
  186:     $r->rflush();
  187: 
  188:     &startGradeScreen($r,'quick');
  189: 
  190: #
  191: # Pick student
  192: #
  193:     my $uname;
  194:     my $udom;
  195:     my $stdid;
  196:     if ($cangrade) {
  197:         $r->print("<h2>".&mt("Download Multiple")."</h2>".
  198:                   '<table cellspacing="5">'."\n".
  199:                   '<tr>'.
  200:                   '<td align="center"><b>'.&mt('Sections').'</b>'.
  201:                   &Apache::loncommon::help_open_topic("Chart_Sections").
  202:                   '</td>'.
  203:                   '<td align="center"><b>'.&mt('Groups').'</b>'.
  204:                   '</td>'.
  205:                   '<td align="center"><b>'.&mt('Student Data').'</b>'.
  206:                   &Apache::loncommon::help_open_topic("Chart_Student_Data").
  207:                   '</td>'.
  208:                   '<td align="center"><b>'.&mt('Access Status').'</b>'.
  209:                   &Apache::loncommon::help_open_topic("Chart_Enrollment_Status").
  210:                   '</td>'.
  211:                   '<td align="center"><b>'.&mt('Output Format').'</b>'.
  212:                   &Apache::loncommon::help_open_topic("Chart_Output_Formats").
  213:                   '</td><td>&nbsp;</td></tr>'."\n".
  214:                   '<tr><td align="center">'."\n".
  215:                   &Apache::lonstatistics::SectionSelect('Section','multiple',5).
  216:                   '</td><td align="center">'.
  217:                   &Apache::lonstatistics::GroupSelect('Group','multiple',5).
  218:                   '</td><td align="center">'.
  219:                   &Apache::lonstatistics::StudentDataSelect('StudentData','multiple',5,undef).
  220:                   '</td><td>'."\n".
  221:                   &Apache::lonhtmlcommon::StatusOptions(undef,undef,5).
  222:                   '</td><td>'."\n".
  223:                   &Apache::lonstudentassessment::CreateAndParseOutputSelector().
  224:                   '</td><td>'.
  225:                   '<input type="submit" name="download" value="'.&mt('Display/Download Multiple Students').'" />'.
  226:                   '</td></tr>'."\n".
  227:                   '</table>'."\n"
  228:                  );
  229:         $r->print("<hr /><h2>".&mt("Display Individual")."</h2>");
  230:         if ($env{'form.uname'}) { $uname=$env{'form.uname'}; }
  231:         if ($env{'form.udom'}) { $udom=$env{'form.udom'}; }
  232:         if ($env{'form.id'}) { $stdid=$env{'form.id'}; }
  233:         if (($stdid) && ($udom)) {
  234:             $uname=(&Apache::lonnet::idget($udom,[$stdid],'ids'))[1];
  235:         }
  236:         if (($stdid) && (!$uname)) {
  237:             $r->print('<p><span class="LC_warning">'.&mt("Unknown Student/Employee ID: [_1]",$stdid).'</span></p>');
  238:             $stdid='';
  239:         }
  240:         if (($uname eq '') && ($udom eq '')) {
  241:             $uname = $env{'user.name'};
  242:             $udom = $env{'user.domain'};
  243:         }
  244:         $r->print('<form method="post" name="quickform" action="/adm/quickgrades">');
  245:         my $chooseopt=&Apache::loncommon::select_dom_form($udom,'udom').' '.
  246:            &Apache::loncommon::selectstudent_link('quickform','uname','udom');
  247:         $r->print("<p>\n".&Apache::loncommon::studentbrowser_javascript()."\n");
  248:         $r->print(&mt('For User [_1] or Student/Employee ID [_2] at Domain [_3]'
  249:                  ,'<input type="text" value="'.$uname.'" size="12" name="uname" />'
  250:                  ,'<input type="text" value="'.$stdid.'" size="12" name="id" /> '
  251:                  ,$chooseopt).
  252:                  '&nbsp;&nbsp;<input type="submit" name="display" value="'.&mt('Display Individual Student').'" /></p>');
  253:         if (($uname) && ($udom)) {
  254:             $r->print('<p>'.&mt('Full Name: [_1]',&Apache::loncommon::plainname($uname,$udom)).'</p>');
  255:         }
  256:     }
  257:     $r->rflush();
  258: 
  259:     my $notshowTotals=
  260:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'externalnototals';
  261:     my $showCategories=
  262:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'categories';
  263: 
  264:     my $usec;
  265:     if ($cangrade) {
  266:         if (($uname eq $env{'user.name'}) && ($udom eq $env{'user.domain'})) {
  267:             $usec = $env{'request.course.sec'};
  268:         } else {
  269:             $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
  270:         }
  271:     } else {
  272:         $usec = $env{'request.course.sec'};
  273:     }
  274: 
  275:     my ($navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,
  276:         $topLevelRight,$topLevelAttempted) = &getData($showPoints,$uname,$udom,$usec);
  277: 
  278:     if (ref($navmap)) {
  279:         if ($showCategories) {
  280:             &outputCategories($r,$showPoints,$notshowTotals,$navmap,$totalParts,$totalPossible,
  281:                               $totalRight,$totalAttempted,$topLevelParts,$topLevelRight,
  282:                               $topLevelAttempted);
  283:         } else {
  284:             my $nostdtotals;
  285:             if ($showPoints) {
  286:                 if ($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'standard') {
  287:                     my $hidetotals = $env{'course.'.$env{'request.course.id'}.'.hidetotals'};
  288:                     if ($hidetotals eq 'all') {
  289:                         $nostdtotals = 1;
  290:                     } elsif ($hidetotals ne '') {
  291:                         if ($usec ne '') {
  292:                             my %secnototals;
  293:                             map { $secnototals{$_} = 1; } split(/,/,$hidetotals);
  294:                             if ($secnototals{$usec}) {
  295:                                 $nostdtotals = 1;
  296:                             }
  297:                         }
  298:                     }
  299:                 }
  300:             }
  301:             &outputTable($r,$showPoints,$notshowTotals,$nostdtotals,$navmap,
  302:                          $totalParts,$totalPossible,$totalRight,$totalAttempted,
  303:                          $topLevelParts,$topLevelRight,$topLevelAttempted);
  304:         }
  305:     } else {
  306:         if ($cangrade) { $r->print("\n</form>\n"); }
  307:         my $requrl = $r->uri;
  308:         $env{'user.error.msg'} = "$requrl:bre:0:0:Navmap initialization failed.";
  309:         return HTTP_NOT_ACCEPTABLE;
  310:     }
  311:     if ($cangrade) { $r->print("\n</form>\n"); }
  312:     &endGradeScreen($r);
  313:     return OK;
  314: }
  315: 
  316: sub grades_blocked {
  317:     my ($r,$blocktext,$caller) = @_;
  318:     my $title = 'Points Display';
  319:     if ($caller eq 'spreadsheet') {
  320:         $title = 'Spreadsheet';
  321:     } elsif ($env{'course.'.$env{'request.course.id'}.'.grading'} ne 'standard') {
  322:         $title = 'Completed Problems Display';
  323:     }
  324:     my $brcrum = [{href=>"/adm/quickgrades",text => $title}];
  325:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  326:     &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/quickgrades',
  327:                                             text=> $title});
  328:     my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs($title);
  329:     &Apache::loncommon::content_type($r,'text/html');
  330:     &Apache::loncommon::no_cache($r);
  331:     $r->send_http_header;
  332:     $r->print(&Apache::loncommon::start_page($title).
  333:               $breadcrumbs.
  334:               $blocktext.
  335:               &Apache::loncommon::end_page());
  336:     return;
  337: }
  338: 
  339: sub getStudentCatGrade {
  340:     my ($uname,$udom,$usec,%categories)=@_;
  341:     my ($navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted)=
  342:        &getData(1,$uname,$udom,$usec);
  343:     return &output_category_table(undef,0,$navmap,0,%categories);
  344: }
  345: 
  346: sub getAllStudentData {
  347:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  348:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  349: 
  350:     my %categories=&Apache::lonnet::dump('grading_categories',$cdom,$cnum);
  351: 
  352:     my $classlist = &Apache::loncoursedata::get_classlist();
  353: 
  354:     my $statusidx   = &Apache::loncoursedata::CL_STATUS();
  355:     my $usernameidx = &Apache::loncoursedata::CL_SNAME();
  356:     my $domainidx   = &Apache::loncoursedata::CL_SDOM();
  357:     my $fullnameidx = &Apache::loncoursedata::CL_FULLNAME();
  358:     my $sectionidx  = &Apache::loncoursedata::CL_SECTION();
  359: 
  360:     foreach my $key (keys(%{$classlist})) {
  361:         my $student = $classlist->{$key};
  362:         my $perc=&getStudentCatGrade($classlist->{$student}->[$usernameidx],
  363:                                      $classlist->{$student}->[$domainidx],
  364:                                      $classlist->{$student}->[$sectionidx],
  365:                                      %categories);
  366:     }
  367: }
  368: 
  369: sub startpage {
  370:     my ($r,$showPoints) = @_;
  371:     my $title = "Grading and Statistics";#$showPoints ? "Points Display" : "Completed Problems Display";
  372:     my $brcrum = [{href=>"/adm/quickgrades",text => "Points Display"}];
  373:     $r->print(&Apache::loncommon::start_page($title,undef,
  374:                                             {'bread_crumbs' => $brcrum})
  375:              );
  376: }
  377: 
  378: sub startGradeScreen {
  379:     my ($r,$mode)=@_;
  380: 
  381:     my $showPoints =
  382:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'standard';
  383:     my $hidetotals =
  384:         $env{'course.'.$env{'request.course.id'}.'.hidetotals'};
  385:     my $notshowSPRSlink =
  386:         (($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'external')
  387:       || ($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'externalnototals')
  388:       || ($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'categories'));
  389:     my $notshowTotals =
  390:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'externalnototals';
  391:     my $showSPRSlink =
  392:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'spreadsheet';
  393:     my $showCategories =
  394:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'categories';
  395:  
  396:     my $allowed_to_view = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
  397:     if ((!$allowed_to_view) && ($env{'request.course.sec'} ne '')) {
  398:         $allowed_to_view = &Apache::lonnet::allowed('vgr',
  399:                                "$env{'request.course.id'}/$env{'request.course.sec'}");
  400:     }
  401: 
  402:     my $allowed_to_edit = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
  403:     if ((!$allowed_to_edit) && ($env{'request.course.sec'} ne '')) {
  404:         $allowed_to_edit = &Apache::lonnet::allowed('mgr',
  405:                                "$env{'request.course.id'}/$env{'request.course.sec'}");
  406:     }
  407: 
  408:     if ($allowed_to_view) {
  409:        my @notes;
  410:        push(@notes,&mt('Students do not see total points.')) if ($notshowTotals);
  411:        push(@notes,&mt('Students do not see link to spreadsheet.')) if ($notshowSPRSlink);
  412:        push(@notes,&mt('Students will see points based on problem weights.')) if ($showPoints);
  413:        if (($showPoints) && ($hidetotals ne '')) {
  414:            if ($hidetotals eq 'all') {
  415:                push(@notes,&mt('Students do not see course totals.'));
  416:            } else {
  417:                my @secs = split(/,/,$hidetotals);
  418:                if (@secs == 1) {
  419:                    push(@notes,&mt('Students in section [_1] do not see course totals.',
  420:                                    $hidetotals));
  421:                } elsif (@secs > 1) {
  422:                    push(@notes,&mt('Students in sections [_1] do not see course totals.',
  423:                                    join(', ',@secs)));
  424:                }
  425:            }
  426:        }
  427:        push(@notes,&mt('Students will see points based on categories.')) if ($showCategories);
  428:        push(@notes,&mt('Students will see link to spreadsheet.')) if ($showSPRSlink);
  429:        push(@notes, &Apache::lonhtmlcommon::coursepreflink(&mt('Grade display settings'),'grading'));
  430:        $r->print(&Apache::loncommon::head_subbox(join('&nbsp;&nbsp;',@notes)));
  431:     }
  432: 
  433: 
  434:     $r->print("\n".'<ul class="LC_TabContentBigger" id="main">');
  435:     $r->print("\n".'<li'.($mode eq 'quick'?' class="active"':'').'><a href="/adm/quickgrades"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.
  436:                                           ($showPoints?&mt('Individual Points Overview'):($showCategories?&mt('Grades Overview'):&mt('Completion Overview'))).
  437:                                           '&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>');
  438: 
  439:     if (!($showPoints || $notshowSPRSlink) || ($allowed_to_view)) {
  440:        $r->print("\n".'<li'.($mode eq 'spreadsheet'?' class="active"':'').'><a href="/adm/'.($allowed_to_view?'classcalc':'studentcalc').'"><b>'.
  441:                                                                  &mt('Spreadsheet (Detailed)').'</b></a></li>');
  442:     }
  443:     if ($allowed_to_view) {
  444:        $r->print("\n".'<li'.($mode eq 'statistics'?' class="active"':'').'><a href="/adm/statistics"><b>'.
  445:                                                                  &mt('Statistics and Reports').'</b></a></li>');
  446: 
  447:        $r->print("\n".'<li'.($mode eq 'chart'?' class="active"':'').'><a href="/adm/statistics?reportSelected=student_assessment"><b>'.
  448:                                                                  &mt('Assessment Chart').'</b></a></li>');
  449: 
  450:     }
  451:     if ($allowed_to_edit) {
  452:        $r->print("\n".'<li'.($mode eq 'grading'?' class="active"':'').'><a href="/adm/grades"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.
  453:                                                                  &mt('Content Grading').'&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>');
  454:        if ($env{'form.symb'}) {
  455:           $r->print("\n".'<li'.($mode eq 'probgrading'?' class="active"':'').'><a href="/adm/grades?symb='.
  456:                                               &Apache::lonhtmlcommon::entity_encode($env{'form.symb'}).
  457:                                               '&amp;command=gradingmenu"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.
  458:                                               &mt('Problem Grading').'&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>');
  459: 
  460:        }
  461:     }
  462:     $r->print("\n".'</ul>'."\n");
  463:     $r->print('<div class="LC_Box" style="clear:both;margin:0;"><div id="maincoursedoc" style="margin:0 0;padding:0 0;"><div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">');
  464: }
  465: 
  466: sub endGradeScreen {
  467:     my ($r)=@_;
  468:     $r->print('</div></div></div>'.&Apache::loncommon::end_page());
  469:     return;
  470: }
  471: 
  472: # -----------
  473: 
  474: 
  475: sub excel_cleanup {
  476:     undef ($excel_sheet);
  477:     undef ($excel_workbook);
  478:     undef ($filename);
  479:     undef ($format);
  480: }
  481: 
  482: 
  483: sub excel_initialize {
  484:     my ($r) = @_;
  485: 
  486:     &excel_cleanup();
  487: 
  488:     # Create sheet
  489:     ($excel_workbook,$filename,$format)=
  490:         &Apache::loncommon::create_workbook($r);
  491:     return if (! defined($excel_workbook));
  492:    #
  493:    # Add a worksheet
  494:     my $sheetname = $env{'course.'.$env{'request.course.id'}.'.description'};
  495:     $sheetname = &Apache::loncommon::clean_excel_name($sheetname);
  496:     $excel_sheet = $excel_workbook->addworksheet($sheetname);
  497:    #
  498:    # Put the course description in the header
  499:     $excel_sheet->write($header_row,$cols_output++,
  500:                    $env{'course.'.$env{'request.course.id'}.'.description'},
  501:                         $format->{'h1'});
  502: } 
  503: 
  504: sub excel_finish {
  505:     my ($r) = @_;
  506:     if ($request_aborted || ! defined($excel_sheet)) {
  507:         &excel_cleanup();
  508:         return;
  509:     }
  510:     #
  511:     # Write the excel file
  512:     $excel_workbook->close();
  513:     #
  514:     # Close the progress window
  515:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  516:     #
  517:     # Tell the user where to get their excel file
  518:     $r->print('<br />'.
  519:               '<a href="'.$filename.'">'.&mt('Your Excel spreadsheet').'</a>'."\n");
  520:     $r->rflush();
  521:     &excel_cleanup();
  522:     return;
  523: }
  524: 
  525: 
  526: #
  527: # CSV data
  528: #
  529: # -----------
  530: 
  531: #
  532: # Go through the complete course and collect data
  533: #
  534: 
  535: sub getData {
  536: 
  537:     my ($showPoints,$uname,$udom,$usec)=@_;
  538: 
  539:     # Create the nav map
  540:     my $navmap = Apache::lonnavmaps::navmap->new($uname,$udom,$usec);
  541: 
  542:     if (!defined($navmap)) {
  543:         return ();
  544:     }
  545: 
  546:     my $res = $navmap->firstResource(); # temp resource to access constants
  547: 
  548:     my $deeplinkcond = 1;
  549:     my $iterator = $navmap->getIterator(undef, undef, undef, 1, undef, undef, $deeplinkcond);
  550:     my $depth = 1;
  551:     $iterator->next(); # ignore first BEGIN_MAP
  552:     my $curRes = $iterator->next();
  553: 
  554:     # General overview of the following: Walk along the course resources.
  555:     # For every problem in the resource, tell its parent maps how many
  556:     # parts and how many parts correct it has. After that, each map will
  557:     # have a count of the total parts underneath it, correct and otherwise.
  558:     # After that, we will walk through the course again and read off
  559:     # maps in order, with their data. 
  560:     # (If in the future people decide not to be cumulative, only add
  561:     #  the counts to the parent map.)
  562:     # For convenience, "totalParts" is also "totalPoints" when we're looking
  563:     #  at points; I can't come up with a variable name that makes sense
  564:     #  equally for both cases.
  565: 
  566:     my $totalParts = 0; my $totalPossible = 0; my $totalRight = 0;
  567:     my $totalAttempted = 0;
  568:     my $now = time();
  569:     my $topLevelParts = 0; my $topLevelRight = 0; my $topLevelAttempted = 0;
  570: 
  571:     # Pre-run: Count parts correct
  572:     while ( $depth > 0 ) {
  573:         if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
  574:         if ($curRes == $iterator->END_MAP()) { $depth--; }
  575:         my ($deeplink,$nodeeplinkcheck,$symb);
  576:         $nodeeplinkcheck = 1;
  577:         if (ref($curRes)) {
  578:             $symb = $curRes->symb();
  579:             $deeplink = $curRes->deeplink('quickgrades');
  580:             if ($deeplink eq 'absent') {
  581:                 $nodeeplinkcheck = 0;
  582:             }
  583:         }
  584:         if (ref($curRes) && $curRes->is_gradable() && !$curRes->randomout &&
  585:             ($nodeeplinkcheck))
  586:         {
  587:             # Get number of correct, incorrect parts
  588:             my $parts = $curRes->parts();
  589:             my $partsRight = 0;
  590: 	    my $partsCount = 0;
  591: 	    my $partsAttempted = 0;
  592:             my $stack = $iterator->getStack();
  593:             
  594:             for my $part (@{$parts}) {
  595: 		my $dateStatus = $curRes->getDateStatus($part);
  596:                 my $weight = $curRes->weight($part);
  597:                 my $problemstatus = $curRes->problemstatus($part);
  598: 
  599:                 if ($curRes->solved($part) eq 'excused') {
  600:                     next;
  601:                 }
  602: 		if ($showPoints) {
  603: 		    my $score = 0;
  604: 		    # If we're not telling status and the answer date isn't passed yet, 
  605: 		    # it's an "attempted" point
  606: 		    if ((($problemstatus eq 'no') ||
  607:                          ($problemstatus eq 'no_feedback_ever')) &&
  608: 			($dateStatus != $curRes->ANSWER_OPEN)) {
  609: 			my $status = $curRes->simpleStatus($part);
  610: 			if ($status == $curRes->ATTEMPTED) {
  611: 			    $partsAttempted += $weight;
  612: 			    $totalAttempted += $partsAttempted;
  613: 			}
  614: 		    } else {
  615: 			$score = &Apache::grades::compute_points($weight, $curRes->awarded($part));
  616: 		    }
  617: 		    $partsRight += $score;
  618: 		    $totalRight += $score;
  619: 		    $partsCount += $weight;
  620: 
  621:                     $curRes->{DATA}->{PROB_SCORE}  += $score;
  622:                     $curRes->{DATA}->{PROB_WEIGHT} += $weight;
  623: 
  624: 		    if ($curRes->opendate($part) < $now) {
  625: 			$totalPossible += $weight;
  626:                         $curRes->{DATA}->{PROB_POSSIBLE} += $weight;
  627: 		    }
  628: 		    $totalParts += $weight;
  629: 		} else {
  630: 		    my $status = $curRes->simpleStatus($part);
  631: 		    my $thisright = 0;
  632: 		    $partsCount++;
  633: 		    if ($status == $curRes->CORRECT ||
  634: 			$status == $curRes->PARTIALLY_CORRECT ) {
  635: 			$partsRight++;
  636: 			$totalRight++;
  637: 			$thisright = 1;
  638: 		    }
  639: 
  640: 		    if ($status == $curRes->ATTEMPTED) {
  641: 			$partsAttempted++;
  642: 			$totalAttempted++;
  643: 		    }
  644: 		    
  645: 		    $totalParts++;
  646: 		    if ($curRes->opendate($part) < $now) {
  647: 			$totalPossible++;
  648: 		    }
  649: 		}
  650:             }
  651: 
  652:             if ($depth == 1) { # in top-level only
  653: 		$topLevelParts += $partsCount;
  654: 		$topLevelRight += $partsRight;
  655: 		$topLevelAttempted += $partsAttempted;
  656: 	    }
  657: 
  658:             # Crawl down stack and record parts correct and total
  659:             for my $res (@{$stack}) {
  660:                 if (ref($res) && $res->is_map()) {
  661:                     if (!defined($res->{DATA}->{CHILD_PARTS})) {
  662:                         $res->{DATA}->{CHILD_PARTS} = 0;
  663:                         $res->{DATA}->{CHILD_CORRECT} = 0;
  664: 			$res->{DATA}->{CHILD_ATTEMPTED} = 0;
  665:                     }
  666:                     
  667:                     $res->{DATA}->{CHILD_PARTS} += $partsCount;
  668:                     $res->{DATA}->{CHILD_CORRECT} += $partsRight;
  669: 		    $res->{DATA}->{CHILD_ATTEMPTED} += $partsAttempted;
  670:                 }
  671:             }
  672:         }
  673:         $curRes = $iterator->next();
  674:     }
  675:     return ($navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,
  676:             $topLevelParts,$topLevelRight,$topLevelAttempted);
  677: }
  678: 
  679: #
  680: # Outputting everything.
  681: #
  682: 
  683: sub outputTable {
  684: 
  685:     my ($r,$showPoints,$notshowTotals,$nostdtotals,$navmap,$totalParts,$totalPossible,
  686:         $totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted)=@_;
  687: 
  688:     my @start = (255, 255, 192);
  689:     my @end   = (0, 192, 0);
  690: 
  691:     my $indentString = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  692: 
  693:     # Second pass: Print the maps.
  694:     $r->print(&Apache::loncommon::start_data_table()
  695:              .&Apache::loncommon::start_data_table_header_row()
  696:              .'<th>'.&mt('Folder').'</th>');
  697:     my $title = &mt($showPoints ? "Points Scored" : "Done");
  698:     if ($totalAttempted) {
  699:         $title .= " / " . &mt("Attempted");
  700:     }
  701:     $r->print("<th>$title".($notshowTotals?'':" / ".&mt('Total')).'</th>'
  702:              .&Apache::loncommon::end_data_table_header_row());
  703: #
  704: # Output of folder scores
  705: #
  706: 
  707:     my $deeplinkcond = 1;
  708:     my $iterator = $navmap->getIterator(undef, undef, undef, 1, undef, undef, $deeplinkcond);
  709:     my $depth = 1;
  710:     $iterator->next(); # ignore first BEGIN_MAP
  711:     my $curRes = $iterator->next();
  712: 
  713:     while ($depth > 0) {
  714:         if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
  715:         if ($curRes == $iterator->END_MAP()) { $depth--; }
  716: 
  717:         if (ref($curRes) && $curRes->is_map()) {
  718:             my $title = $curRes->compTitle();
  719:             
  720:             my $correct = $curRes->{DATA}->{CHILD_CORRECT};
  721:             my $total = $curRes->{DATA}->{CHILD_PARTS};
  722: 	    my $attempted = $curRes->{DATA}->{CHILD_ATTEMPTED};
  723: 
  724:             if ($total > 0) {
  725:                 my $ratio;
  726:                 $ratio = $correct / $total;
  727:                 my $color = &mixColors(\@start, \@end, $ratio);
  728:                 $r->print(&Apache::loncommon::start_data_table_row()
  729:                          .'<td style="background-color:'.$color.';">');
  730:                 
  731: 		my $thisIndent = '';
  732:                 for (my $i = 1; $i < $depth; $i++) { $thisIndent .= $indentString; }
  733:                 
  734:                 $r->print("$thisIndent$title</td>");
  735: 		if ($totalAttempted) {
  736: 		    $r->print('<td valign="top">'
  737:                              .$thisIndent
  738:                              .'<span class="LC_nobreak">'
  739:                              .$correct.' / '.$attempted.($notshowTotals?'':' / '.$total)
  740:                              .'</span></td>'
  741:                              .&Apache::loncommon::end_data_table_row()
  742:                     );
  743: 		} else {
  744: 		    $r->print('<td valign="top">'
  745:                              .$thisIndent
  746:                              .'<span class="LC_nobreak">'
  747:                              .$correct.($notshowTotals?'':' / '.$total)
  748:                              .'</span></td>'
  749:                              .&Apache::loncommon::end_data_table_row());
  750: 		}
  751:             }
  752:         }
  753: 
  754:         $curRes = $iterator->next();
  755:     }
  756: 
  757:     # If there were any problems at the top level, print an extra "catchall"
  758:     if ($topLevelParts > 0) {
  759:         my $ratio = $topLevelRight / $topLevelParts;
  760:         my $color = &mixColors(\@start, \@end, $ratio);
  761:         $r->print(&Apache::loncommon::start_data_table_row()
  762:                  .'<td style="background-color:'.$color.';">');
  763:         $r->print(&mt("Problems Not Contained In A Folder")."</td><td>");
  764:         $r->print("$topLevelRight / $topLevelParts</td>"
  765:                  .&Apache::loncommon::end_data_table_row());
  766:     }
  767: 
  768: #
  769: # show totals (if applicable), close table
  770: #
  771:     if ($showPoints) {
  772:         unless ($nostdtotals) {
  773:             my $maxHelpLink = &Apache::loncommon::help_open_topic("Quick_Grades_Possibly_Correct");
  774: 
  775:             $title = $showPoints ? "Points" : "Parts Done";
  776:             my $totaltitle = $showPoints ? &mt("Awarded Total Points") : &mt("Total Parts Done");
  777:             $r->print(&Apache::loncommon::start_data_table_row()
  778:                      .'<td colspan="2" align="right">'.$totaltitle.': <b>'.$totalRight.'</b><br />');
  779:             $r->print(&mt('Max Possible To Date')." $maxHelpLink: <b>$totalPossible</b><br />");
  780:             $title = $showPoints ? "Points" : "Parts";
  781:             $r->print(&mt("Total $title In Course").': <b>'.$totalParts.'</b></td>'
  782:                      .&Apache::loncommon::end_data_table_row());
  783:         }
  784:     }
  785: 
  786:     $r->print(&Apache::loncommon::end_data_table());
  787:     return;
  788: }
  789: 
  790: #
  791: # === Outputting category-based grades.
  792: #
  793: # $category{'order'}: output order of categories by id
  794: # $category{'all'}: complete list of all categories 
  795: # $category{$id.'_name'}: display-name of category
  796: #
  797: 
  798: sub outputCategories {
  799: 
  800:     my ($r,$showPoints,$notshowTotals,
  801:            $navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted)=@_;
  802: # Take care of storing and retrieving categories
  803: 
  804:     my $cangrade=&Apache::lonnet::allowed('mgr');
  805: 
  806:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  807:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  808:     my %categories=();
  809: # Loading old categories
  810:     %categories=&Apache::lonnet::dump('grading_categories',$cdom,$cnum);
  811: # Storing
  812:     if (($cangrade) && (($env{'form.storechanges'}) || ($env{'form.storemove'} ne '') || ($env{'form.cmd'} ne ''))) {
  813: # Process the changes
  814:         %categories=&process_category_edits($r,$cangrade,%categories);
  815: # Actually store
  816:         &Apache::lonnet::put('grading_categories',\%categories,$cdom,$cnum);
  817:     }
  818: # new categories loaded now
  819:     &output_category_table($r,$cangrade,$navmap,1,%categories);
  820: #
  821:     if ($cangrade) {
  822:         $r->print(&Apache::loncommon::resourcebrowser_javascript().
  823:                   '<input type="hidden" name="storemove" value="" />'.
  824:                   '<input type="hidden" name="cmd" value="" />'.
  825:                   '<input type="hidden" name="resourcesymb" value="" />'.
  826:                   '<input type="submit" name="storechanges" value="'.&mt("Save changes to grading categories").'" />'.
  827:                   '<script>function storecmd (cmd) { document.quickform.cmd.value=cmd; document.quickform.submit(); }</script>');
  828:     }
  829: }
  830: 
  831: #
  832: # Get data for all symbs
  833: #
  834: 
  835: sub dumpdata {
  836:     my ($navmap)=@_;
  837:     my %returndata=();
  838: 
  839: # Run through the map and get all data
  840: 
  841:     my $deeplinkcond = 1;
  842:     my $iterator = $navmap->getIterator(undef, undef, undef, 1, undef, undef, $deeplinkcond);
  843:     my $depth = 1;
  844:     $iterator->next(); # ignore first BEGIN_MAP
  845:     my $curRes = $iterator->next();
  846: 
  847:     while ($depth > 0) {
  848:         if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
  849:         if ($curRes == $iterator->END_MAP()) { $depth--; }
  850:         if (ref($curRes)) {
  851:             if ($curRes->is_map()) {
  852:                 $returndata{$curRes->symb()}='folder:'.$curRes->{DATA}->{CHILD_PARTS}.':'.$curRes->{DATA}->{CHILD_ATTEMPTED}.':'.$curRes->{DATA}->{CHILD_CORRECT};
  853:             } else {
  854:                 $returndata{$curRes->symb()}='res:'.$curRes->{DATA}->{PROB_WEIGHT}.':'.$curRes->{DATA}->{PROB_POSSIBLE}.':'.$curRes->{DATA}->{PROB_SCORE};
  855:             } 
  856:         }
  857:         $curRes = $iterator->next();
  858:     }
  859:     return %returndata;
  860: }
  861: 
  862: #
  863: # Process editing commands, update category hash
  864: #
  865: 
  866: sub process_category_edits {
  867:     my ($r,$cangrade,%categories)=@_;
  868:     unless ($cangrade) { return %categories; }
  869: # First store everything
  870:     foreach my $id (split(/\,/,$categories{'order'})) {
  871: # Set names, types, and weight (there is only one of each per category)
  872:         %categories=&set_category_name($cangrade,$id,$env{'form.name_'.$id},%categories);
  873:         %categories=&set_category_total($cangrade,$id,$env{'form.totaltype_'.$id},$env{'form.total_'.$id},%categories);
  874:         %categories=&set_category_weight($cangrade,$id,$env{'form.weight_'.$id},%categories);
  875:         %categories=&set_category_displayachieved($cangrade,$id,$env{'form.displayachieved_'.$id},%categories);
  876: # Set values for category rules (before names may change)
  877:         %categories=&set_category_rules($cangrade,$id,%categories);
  878:     }
  879: 
  880: # Now deal with commands
  881:     my $cmd=$env{'form.cmd'};
  882:     if ($cmd eq 'createnewcat') {
  883:         %categories=&make_new_category($r,$cangrade,undef,%categories);
  884:     } elsif ($cmd=~/^up\_(.+)$/) {
  885:         %categories=&move_up_category($1,$cangrade,%categories);
  886:     } elsif ($cmd=~/^down\_(.+)$/) {
  887:         %categories=&move_down_category($1,$cangrade,%categories);
  888:     } elsif ($cmd=~/^delcat\_(.+)$/) {
  889:         %categories=&del_category($1,$cangrade,%categories);
  890:     } elsif ($cmd=~/^addcont\_(.+)$/) {
  891:         %categories=&add_category_content($1,$cangrade,$env{'form.resourcesymb'},%categories);
  892:     } elsif ($cmd=~/^delcont\_(.+)\_\_\_\_\_\_(.+)$/) {
  893:         %categories=&del_category_content($1,$cangrade,$2,%categories);
  894:     } elsif ($cmd=~/^newrule\_(.+)$/) {
  895:         %categories=&add_calculation_rule($1,$cangrade,':',%categories);
  896:     } elsif ($cmd=~/^delrule\_(.+)\_\_\_\_\_\_(.*)$/) {
  897:         %categories=&del_calculation_rule($1,$cangrade,$2,%categories);
  898:     }
  899: # Move to a new position
  900:     my $moveid=$env{'form.storemove'};
  901:     if ($moveid) {
  902:         %categories=&move_category($moveid,$cangrade,$env{'form.newpos_'.$moveid},%categories);
  903:     } 
  904:     return %categories;
  905: }
  906: 
  907: #
  908: # Output the table
  909: #
  910: 
  911: sub output_category_table {
  912:     my ($r,$cangrade,$navmaps,$output,%categories)=@_;
  913:     
  914:     my $totalweight=0;
  915:     my $totalpoints=0;
  916: 
  917:     if ($output) { 
  918:        $r->print(&Apache::loncommon::start_data_table());
  919: #
  920:        &output_category_table_header($r,$cangrade);
  921:     }
  922: #
  923:     my @order=split(/\,/,$categories{'order'});
  924: #
  925:     my %performance=&dumpdata($navmaps);
  926:     my $maxpos=$#order;
  927:     for (my $i=0;$i<=$maxpos;$i++) {
  928:         my ($correct,$possible,$type,$weight)=&output_and_calc_category($r,$cangrade,$navmaps,$order[$i],$i,$maxpos,\%performance,$output,%categories);
  929:         unless ($possible) { next; }
  930:         $totalpoints+=$weight*$correct/$possible;
  931:         $totalweight+=$weight;
  932:     }
  933: #
  934:     my $perc=0;
  935:     if ($totalweight) { $perc=100.*$totalpoints/$totalweight; }
  936: 
  937:     if ($output) { 
  938:         &bottom_line_category($r,$cangrade,$perc); 
  939:         $r->print(&Apache::loncommon::end_data_table());
  940:     }
  941:     return $perc;
  942: }
  943: 
  944: sub output_category_table_header {
  945:     my ($r,$cangrade)=@_;
  946:     $r->print(&Apache::loncommon::start_data_table_header_row());
  947:     if ($cangrade) {
  948:         $r->print('<th colspan="2">'.&mt("Move").'</th><th>'.&mt('Action').'</th>');
  949:     }
  950:     $r->print('<th>'.&mt('Category').'</th>'.
  951:               '<th>'.&mt('Contents').'</th>'.
  952:               '<th>'.&mt('Total Points').'</th>'.
  953:               '<th>'.&mt('Calculation').'</th>'.
  954:               '<th>'.&mt('Relative Weight').'</th>'.
  955:               '<th>'.&mt('Achieved').'</th>');
  956:     $r->print(&Apache::loncommon::end_data_table_header_row());
  957: }
  958: 
  959: 
  960: #
  961: # Output one category to table
  962: #
  963: 
  964: sub output_and_calc_category {
  965:     my ($r,$cangrade,$navmaps,$id,$currentpos,$maxpos,$performance,$output,%categories)=@_;
  966:     
  967:     if ($output) { $r->print("\n".&Apache::loncommon::start_data_table_row()); }
  968: 
  969:     if ($output && $cangrade) {
  970:         my $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
  971:         my %lt=&Apache::lonlocal::texthash(
  972:            'up' => 'Move Up',
  973:            'dw' => 'Move Down');
  974: 
  975:         $r->print(<<ENDMOVE);
  976: <td>
  977: <div class="LC_docs_entry_move">
  978:   <a href='javascript:storecmd("up_$id");'>
  979:     <img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" />
  980:   </a>
  981: </div>
  982: <div class="LC_docs_entry_move">
  983:   <a href='javascript:storecmd("down_$id");'>
  984:     <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" />
  985:   </a>
  986: </div>
  987: </td>
  988: ENDMOVE
  989:         $r->print("\n<td>\n<select name='newpos_$id' onchange='this.form.storemove.value=\"$id\";this.form.submit()'>");
  990:         for (my $i=0;$i<=$maxpos;$i++) {
  991:             if ($i==$currentpos) {
  992:                 $r->print('<option value="" selected="selected">('.$i.')</option>');
  993:             } else {
  994:                 $r->print('<option value="'.$i.'">'.$i.'</option>');
  995:             }
  996:         }
  997:         $r->print("\n</select>\n</td>\n");
  998:         $r->print('<td><a href="javascript:storecmd(\'delcat_'.$id.'\');">'.&mt('Delete').'</a></td>');
  999:         $r->print('<td><input type="text" name="name_'.$id.
 1000:                   '" value="'.&Apache::lonhtmlcommon::entity_encode($categories{$id.'_name'}).'" /></td>');
 1001:     } elsif ($output) {
 1002:         $r->print('<td>'.$categories{$id.'_name'}.'</td>');
 1003:     }
 1004: # Content display and summing up of points
 1005:     my $totalpossible=0;
 1006:     my $totalcorrect=0;
 1007:     my @individual=();
 1008:     if ($output) { $r->print('<td><ul>'); }
 1009:     foreach my $contentid (split(/\,/,$categories{$id.'_content'})) {
 1010:         my ($type,$possible,$attempted,$correct)=split(/\:/,$$performance{$contentid});
 1011:         $totalpossible+=$possible;
 1012:         $totalcorrect+=$correct;
 1013:         if ($possible>0) { push(@individual,"$possible:$correct"); }
 1014:         if ($output) {
 1015:            $r->print('<li>');
 1016:            $r->print(&Apache::lonnet::gettitle($contentid).' ('.&numberout($correct).'/'.&numberout($possible).')');
 1017:            if ($cangrade) {
 1018:               $r->print(' <a href="javascript:storecmd(\'delcont_'.$id.'______'.$contentid.'\');">'.&mt('Delete').'</a>');
 1019:            }
 1020:            $r->print('</li>');
 1021:         }
 1022:     }
 1023:     if ($output) {
 1024:        $r->print('</ul>');
 1025:        if ($cangrade) {
 1026:            $r->print('<br />'.&Apache::loncommon::selectresource_link('quickform','addcont_'.$id,&mt('Add Problem or Folder')).'<br />');
 1027:        }
 1028:        $r->print('<p><b>'.&mt('Total raw points: [_1]/[_2]',&numberout($totalcorrect),&numberout($totalpossible)).'</b></p>');
 1029:        $r->print('</td>'); 
 1030:     }
 1031: # Total
 1032:     if ($output) { $r->print('<td>'); }
 1033:     if ($cangrade) {
 1034:        if ($output) { 
 1035:           $r->print(
 1036:                   '<select name="totaltype_'.$id.'">'.
 1037:                   '<option value="default"'.($categories{$id.'_totaltype'} eq 'default'?' selected="selected"':'').'>'.&mt('default').'</option>'.
 1038:                   '<option value="typein"'.($categories{$id.'_totaltype'} eq 'typein'?' selected="selected"':'').'>'.&mt('Type-in value').'</option>'.
 1039:                   '</select>'.
 1040:                   '<input type="text" size="4" name="total_'.$id.
 1041:                   '" value="'.&Apache::lonhtmlcommon::entity_encode($categories{$id.'_total'}).'" />'); 
 1042:        }
 1043:     } else {
 1044:        if ($output) {
 1045:           $r->print('<td>'.($categories{$id.'_totaltype'} eq 'default'?&mt('default'):$categories{$id.'_total'}));
 1046:        }
 1047:     }
 1048: # Adjust total points
 1049:     if ($categories{$id.'_totaltype'} eq 'typein') {
 1050:        $totalpossible=1.*$categories{$id.'_total'};
 1051:     }
 1052:     if ($output) {
 1053:        $r->print('<p><b>'.&mt('Adjusted raw points: [_1]/[_2]',&numberout($totalcorrect),&numberout($totalpossible)).'</b></p>');
 1054:     }
 1055: 
 1056: 
 1057: # Calculation
 1058:     if ($output) { $r->print('<td><ul>'); }
 1059:     foreach my $calcrule (split(/\,/,$categories{$id.'_calculations'})) {
 1060:         if ($output) { $r->print('<li>'); }
 1061:         my ($code,$value)=split(/\:/,$calcrule);
 1062:         if ($output) { $r->print(&pretty_prt_rule($cangrade,$id,$code,$value)); }
 1063:         if ($cangrade) {
 1064:            if ($output) { $r->print(' <a href="javascript:storecmd(\'delrule_'.$id.'______'.$code.'\');">'.&mt('Delete').'</a>'); }
 1065:         }
 1066:         if ($code eq 'capabove') {
 1067:             if ($totalpossible>0) {
 1068:                 if ($totalcorrect/$totalpossible>$value/100.) {
 1069:                     $totalcorrect=$totalpossible*$value/100.;
 1070:                 }
 1071:             }
 1072:         } elsif ($code eq 'capbelow') {
 1073:             if ($totalpossible>0) {
 1074:                 if ($totalcorrect/$totalpossible<$value/100.) {
 1075:                     $totalcorrect=$totalpossible*$value/100.;
 1076:                 }
 1077:             }
 1078:         } elsif ($code eq 'droplow') {
 1079:             ($totalpossible,$totalcorrect,@individual)=&drop(0,0,$value,@individual);
 1080:         } elsif ($code eq 'drophigh') {
 1081:             ($totalpossible,$totalcorrect,@individual)=&drop(1,0,$value,@individual);
 1082:         } elsif ($code eq 'droplowperc') {
 1083:             ($totalpossible,$totalcorrect,@individual)=&drop(0,1,$value,@individual);
 1084:         } elsif ($code eq 'drophighperc') {
 1085:             ($totalpossible,$totalcorrect,@individual)=&drop(1,1,$value,@individual);
 1086:         }
 1087:         if ($output) { $r->print('</li>'); }
 1088:     }
 1089: # Re-adjust total points if force total
 1090:     if ($categories{$id.'_totaltype'} eq 'typein') {
 1091:        $totalpossible=1.*$categories{$id.'_total'};
 1092:     }
 1093: 
 1094:     if ($output) { 
 1095:         $r->print('</ul>'); 
 1096:         if ($cangrade) { $r->print('<br />'.&new_calc_rule_form($id)); }
 1097:         $r->print('<p><b>'.&mt('Calculated points: [_1]/[_2]',&numberout($totalcorrect),&numberout($totalpossible)).'</b></p>');
 1098:         $r->print('</td>'); 
 1099:     }
 1100: #
 1101: # Prepare for export
 1102: #
 1103: # Weight
 1104:     my $weight=$categories{$id.'_weight'};
 1105:     unless (1.*$weight>0) { $weight=0; }
 1106:     if ($cangrade) {
 1107:        if ($output) { 
 1108:           $r->print('<td>'.
 1109:                   '<input type="text" size="4" name="weight_'.$id.
 1110:                   '" value="'.&Apache::lonhtmlcommon::entity_encode($weight).'" /></td>');
 1111:        }
 1112:     } else {
 1113:        if ($output) {
 1114:           $r->print('<td>'.$weight.'</td>');
 1115:        }
 1116:     }
 1117: # Achieved
 1118:     my $type=$categories{$id.'_displayachieved'};
 1119:     unless (($type eq 'percent') || ($type eq 'points')) { $type='points'; }
 1120:     if ($output) { $r->print('<td>'); }
 1121:     if ($cangrade) {
 1122:         if ($output) {
 1123:            $r->print('<select name="displayachieved_'.$id.'">'.
 1124:                   '<option value="percent"'.($type eq 'percent'?' selected="selected"':'').'>'.&mt('percent').'</option>'.
 1125:                   '<option value="points"'.($type eq 'points'?' selected="selected"':'').'>'.&mt('points').'</option>'.
 1126:                   '</select>');
 1127:         }
 1128:     }
 1129:     if ($output) {
 1130:         $r->print('<p><b>');
 1131:         if ($type eq 'percent') {
 1132:             my $perc='---';
 1133:             if ($totalpossible) {
 1134:                 $perc=100.*$totalcorrect/$totalpossible;
 1135:             }
 1136:             $r->print(&mt('[_1] percent',&numberout($perc)));
 1137:         } else {
 1138:             $r->print(&mt('[_1]/[_2] points',&numberout($totalcorrect),&numberout($totalpossible)));
 1139:         }
 1140:         $r->print('</b></p>');
 1141:     }
 1142:     if ($output) { $r->print('</td>'); }
 1143: 
 1144:     return ($totalcorrect,$totalpossible,$type,$weight);
 1145: }
 1146: 
 1147: #
 1148: # Drop folders and problems
 1149: #
 1150: 
 1151: sub drop {
 1152:     my ($high,$percent,$n,@individual)=@_;
 1153: # Sort assignments by points or percent
 1154:     my @newindividual=sort {
 1155:         my ($pa,$ca)=split(/\:/,$a);
 1156:         my ($pb,$cb)=split(/\:/,$b);
 1157:         if ($percent) {
 1158:             my $perca=0;
 1159:             if ($pa>0) { $perca=$ca/$pa; }
 1160:             my $percb=0;
 1161:             if ($pb>0) { $percb=$cb/$pb; }
 1162:             $perca<=>$percb;
 1163:         } else {
 1164:             $ca<=>$cb;
 1165:         }
 1166:     } @individual;
 1167: # Drop the ones we don't want
 1168:     if ($#newindividual>=$n) {
 1169:         if ($high) {
 1170:            splice(@newindividual,$#newindividual+1-$n,$n);
 1171:         } else {
 1172:            splice(@newindividual,0,$n);
 1173:         }
 1174:     } else {
 1175:         @newindividual=();
 1176:     }
 1177: # Re-calculate how many points possible and achieved
 1178:     my $newpossible=0;
 1179:     my $newcorrect=0;
 1180:     for my $score (@newindividual) {
 1181:         my ($thispossible,$thiscorrect)=(split(/\:/,$score));
 1182:         $newpossible+=$thispossible;
 1183:         $newcorrect+=$thiscorrect;
 1184:     }
 1185:     return ($newpossible,$newcorrect,@newindividual);
 1186: } 
 1187: #
 1188: # Bottom line with grades
 1189: #
 1190: 
 1191: sub bottom_line_category {
 1192:     my ($r,$cangrade,$perc)=@_;
 1193:     $r->print(&Apache::loncommon::start_data_table_row());
 1194:     if ($cangrade) {
 1195:         $r->print('<td colspan="3"><a href="javascript:storecmd(\'createnewcat\');">'.&mt('Create New Category').'</a></td>');
 1196:     }
 1197:     $r->print('<td colspan="6"><b>'.&mt('Total: [_1] percent',&numberout($perc)).'</b></td>');
 1198: }
 1199: 
 1200: sub numberout {
 1201:     my ($number)=@_;
 1202:     my $printout=sprintf("%.3f", $number);
 1203:     $printout=~s/0+$//;
 1204:     $printout=~s/\.$//;
 1205:     return $printout;
 1206: }
 1207: #
 1208: # Make one new category
 1209: #
 1210: 
 1211: sub make_new_category {
 1212:     my ($r,$cangrade,$ordernum,%categories)=@_;
 1213:     unless ($cangrade) { return %categories; }
 1214: # Generate new ID
 1215:     my $id=time.'_'.$$.'_'.rand(10000);
 1216: # Add new ID to list of all IDs ever created in this course
 1217:     $categories{'all'}.=','.$id;
 1218:     $categories{'all'}=~s/^\,//;
 1219: # Add new ID to ordered list of displayed and evaluated categories
 1220:     $categories{'order'}.=','.$id;
 1221:     $categories{'order'}=~s/^\,//;
 1222: # Move it into desired space
 1223:     if (defined($ordernum)) {
 1224:         %categories=&move_category($id,$cangrade,$ordernum,%categories);
 1225:     }
 1226:     $categories{$id.'_weight'}=0;
 1227:     $categories{$id.'_totaltype'}='default';
 1228:     $categories{$id.'_displayachieved'}='percent';
 1229:     return %categories;
 1230: }
 1231: 
 1232: 
 1233: # === Calculation Rule Editing
 1234: 
 1235: sub category_rule_codes {
 1236:     return &Apache::lonlocal::texthash(
 1237:                 'droplowperc'  => 'Drop N lowest grade percentage problems/folders',
 1238:                 'drophighperc' => 'Drop N highest grade percentage problems/folderss',
 1239:                 'droplow'  => 'Drop N lowest point problems/folders',
 1240:                 'drophigh' => 'Drop N highest point problems/folders',
 1241:                 'capabove' => 'Cap percentage above N percent',
 1242:                 'capbelow' => 'Cap percentage below N percent');
 1243: }
 1244: 
 1245: sub pretty_prt_rule {
 1246:     my ($cangrade,$id,$code,$value)=@_;
 1247:     my $cid=$id.'_'.$code;
 1248:     my %lt=&category_rule_codes();
 1249:     my $ret='<span class="LC_nobreak">';
 1250:     if ($cangrade) {
 1251:         $ret.='<select name="sel_'.$cid.'">';
 1252:         foreach my $calc (''=>'',sort(keys(%lt))) {
 1253:             $ret.='<option value="'.$calc.'"'.($calc eq $code?' selected="selected"':'').' />'.$lt{$calc}.'</input>';
 1254:         }
 1255:         $ret.='</select> N=<input type="text" size="5" name="val_'.$cid.'" value="'.$value.'" /></span>';
 1256:     } else {
 1257:         $ret.=$lt{$code}.'; N='.$value;
 1258:     }
 1259:     $ret.='</span>';
 1260:     return $ret;
 1261: }
 1262: 
 1263: sub new_calc_rule_form {
 1264:     my ($id)=@_;
 1265:     return '<a href="javascript:storecmd(\'newrule_'.$id.'\');">'.&mt('New Calculation Rule').'</a>';
 1266: }
 1267: 
 1268: #
 1269: # Add a calculation rule
 1270: #
 1271: 
 1272: sub add_calculation_rule {
 1273:     my ($id,$cangrade,$newcontent,%categories)=@_;
 1274:     unless ($cangrade) { return %categories; }
 1275:     my %newcontent=($newcontent => 1);
 1276:     foreach my $current (split(/\,/,$categories{$id.'_calculations'})) {
 1277:         $newcontent{$current}=1;
 1278:     }
 1279:     $categories{$id.'_calculations'}=join(',',sort(keys(%newcontent)));
 1280:     return %categories;
 1281: }
 1282: 
 1283: #
 1284: # Delete a calculation rule
 1285: #
 1286: 
 1287: sub del_calculation_rule {
 1288:     my ($id,$cangrade,$delcontent,%categories)=@_;
 1289:     unless ($cangrade) { return %categories; }
 1290:     my @newcontent=();
 1291:     foreach my $current (split(/\,/,$categories{$id.'_calculations'})) {
 1292:         unless ($current=~/^\Q$delcontent\E\:/) {
 1293:             push(@newcontent,$current);
 1294:         }
 1295:     }
 1296:     $categories{$id.'_calculations'}=join(',',@newcontent);
 1297:     return %categories;
 1298: }
 1299: 
 1300: sub set_category_rules {
 1301:     my ($cangrade,$id,%categories)=@_;
 1302:     unless ($cangrade) { return %categories; }
 1303:     my %lt=&category_rule_codes();
 1304:     my @newrules=();
 1305:     foreach my $code ('',(keys(%lt))) {
 1306:         if ($env{'form.sel_'.$id.'_'.$code}) {
 1307:             push(@newrules,$env{'form.sel_'.$id.'_'.$code}.':'.$env{'form.val_'.$id.'_'.$code});
 1308:         }
 1309:     }
 1310:     $categories{$id.'_calculations'}=join(',',sort(@newrules));
 1311:     return %categories;
 1312: }
 1313: 
 1314: 
 1315: # === Category Editing
 1316: 
 1317: #
 1318: # Add to category content
 1319: #
 1320: 
 1321: sub add_category_content {
 1322:     my ($id,$cangrade,$newcontent,%categories)=@_;
 1323:     unless ($cangrade) { return %categories; }
 1324:     &Apache::lonnet::logthis("In here $newcontent");
 1325:     my %newcontent=($newcontent => 1);
 1326:     foreach my $current (split(/\,/,$categories{$id.'_content'})) {
 1327:         $newcontent{$current}=1;
 1328:     }
 1329:     $categories{$id.'_content'}=join(',',sort(keys(%newcontent)));
 1330:     return %categories;
 1331: }
 1332: 
 1333: #
 1334: # Delete from category content
 1335: #
 1336: 
 1337: sub del_category_content {
 1338:     my ($id,$cangrade,$delcontent,%categories)=@_;
 1339:     unless ($cangrade) { return %categories; }
 1340:     my @newcontent=();
 1341:     foreach my $current (split(/\,/,$categories{$id.'_content'})) {
 1342:         unless ($current eq $delcontent) {
 1343:             push(@newcontent,$current);
 1344:         }
 1345:     }
 1346:     $categories{$id.'_content'}=join(',',@newcontent);
 1347:     return %categories;
 1348: }
 1349: 
 1350: #
 1351: # Delete category
 1352: #
 1353: 
 1354: sub del_category {
 1355:     my ($id,$cangrade,%categories)=@_;
 1356:     unless ($cangrade) { return %categories; }
 1357:     my @neworder=();
 1358:     foreach my $currentid (split(/\,/,$categories{'order'})) {
 1359:         unless ($currentid eq $id) {
 1360:             push(@neworder,$currentid);
 1361:         }
 1362:     }
 1363:     $categories{'order'}=join(',',@neworder);
 1364:     return %categories;
 1365: }
 1366: 
 1367: #
 1368: # Move category up
 1369: #
 1370: 
 1371: sub move_up_category {
 1372:     my ($id,$cangrade,%categories)=@_;
 1373:     my $currentpos=&current_pos_category($id,%categories);
 1374:     if ($currentpos<1) { return %categories; }
 1375:     return &move_category($id,$cangrade,$currentpos-1,%categories);
 1376: }
 1377: 
 1378: #
 1379: # Move category down
 1380: #
 1381: 
 1382: sub move_down_category {
 1383:     my ($id,$cangrade,%categories)=@_;
 1384:     my $currentpos=&current_pos_category($id,%categories);
 1385:     my @order=split(/\,/,$categories{'order'});
 1386:     if ($currentpos>=$#order) { return %categories; }
 1387:     return &move_category($id,$cangrade,$currentpos+1,%categories);
 1388: }
 1389: 
 1390: #
 1391: # Move a category to a desired position n the display order
 1392: #
 1393: 
 1394: sub move_category {
 1395:     my ($id,$cangrade,$ordernum,%categories)=@_;
 1396:     unless ($cangrade) { return %categories; }
 1397:     my @order=split(/\,/,$categories{'order'});
 1398: # Where is the index currently?
 1399:     my $currentpos=&current_pos_category($id,%categories);
 1400:     if (defined($currentpos)) {
 1401:         if ($currentpos<$ordernum) {
 1402: # This is moving to a higher index
 1403: # ....X1234....
 1404: # ....1234X....
 1405:             for (my $i=$currentpos;$i<$ordernum;$i++) {
 1406:                 $order[$i]=$order[$i+1];
 1407:             }
 1408:             $order[$ordernum]=$id;
 1409:         }
 1410:         if ($currentpos>$ordernum) {
 1411: # This is moving to a lower index
 1412: # ....1234X....
 1413: # ....X1234....
 1414:             for (my $i=$currentpos;$i>$ordernum;$i--) {
 1415:                 $order[$i]=$order[$i-1];
 1416:             }
 1417:             $order[$ordernum]=$id;
 1418:         }
 1419:     }
 1420:     $categories{'order'}=join(',',@order);
 1421:     return %categories;
 1422: }
 1423: 
 1424: #
 1425: #  Find current postion of a category in the order
 1426: #
 1427: 
 1428: sub current_pos_category {
 1429:     my ($id,%categories)=@_;
 1430:     my @order=split(/\,/,$categories{'order'});
 1431:     for (my $i=0;$i<=$#order;$i++) {
 1432:         if ($order[$i] eq $id) { return $i; }
 1433:     }
 1434: # not found
 1435:     return undef;
 1436: }
 1437: 
 1438: #
 1439: # Set name of a category
 1440: #
 1441: sub set_category_name {
 1442:     my ($cangrade,$id,$name,%categories)=@_;
 1443:     unless ($cangrade) { return %categories; }
 1444:     $categories{$id.'_name'}=$name;
 1445:     return %categories;
 1446: }
 1447: 
 1448: #
 1449: # Set total of a category
 1450: #
 1451: sub set_category_total {
 1452:     my ($cangrade,$id,$totaltype,$total,%categories)=@_;
 1453:     unless ($cangrade) { return %categories; }
 1454:     if (($categories{$id.'_total'} eq '') && ($total=~/\d/)) {
 1455:         $totaltype='typein';
 1456:     }
 1457:     $categories{$id.'_totaltype'}=$totaltype;
 1458:     if ($totaltype eq 'default') {
 1459:         $categories{$id.'_total'}='';
 1460:     } else {
 1461:         $total=~s/\D//gs;
 1462:         unless ($total) { $total=0; }
 1463:         $categories{$id.'_total'}=$total;
 1464:     }
 1465:     return %categories;
 1466: }
 1467: 
 1468: sub set_category_weight {
 1469:     my ($cangrade,$id,$weight,%categories)=@_;
 1470:     unless ($cangrade) { return %categories; }
 1471:     $weight=~s/\D//gs;
 1472:     unless ($weight) { $weight=0; }
 1473:     $categories{$id.'_weight'}=$weight;
 1474:     return %categories;
 1475: }
 1476: 
 1477: sub set_category_displayachieved {
 1478:     my ($cangrade,$id,$value,%categories)=@_;
 1479:     unless ($cangrade) { return %categories; }
 1480:     unless (($value eq 'percent') || ($value eq 'points')) { $value='percent'; }
 1481:     $categories{$id.'_displayachieved'}=$value;
 1482:     return %categories;
 1483: }
 1484: 
 1485: 
 1486: #
 1487: # === end category-related
 1488: #
 1489: #
 1490: # Pass this two refs to arrays for the start and end color, and a number
 1491: # from 0 to 1 for how much of the latter you want to mix in. It will
 1492: # return a string ready to show ("#FFC309");
 1493: 
 1494: sub mixColors {
 1495:     my $start = shift;
 1496:     my $end = shift;
 1497:     my $ratio = shift;
 1498:     
 1499:     my ($a,$b);
 1500:     my $final = "";
 1501:     $a = $start->[0]; $b = $end->[0];
 1502:     my $mix1 = POSIX::floor((1-$ratio)*$a + $ratio*$b);
 1503:     $a = $start->[1]; $b = $end->[1];
 1504:     my $mix2 = POSIX::floor((1-$ratio)*$a + $ratio*$b);
 1505:     $a = $start->[2]; $b = $end->[2];
 1506:     my $mix3 = POSIX::floor((1-$ratio)*$a + $ratio*$b);
 1507: 
 1508:     $final = sprintf "%02x%02x%02x", $mix1, $mix2, $mix3;
 1509:     return "#" . $final;
 1510: }
 1511: 
 1512: 1;

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