File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.115: download - view: text, annotated - select for diffs
Wed May 20 16:55:52 2020 UTC (4 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Support section-specific roles which have vgr or mgr privs.

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

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