File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.101: download - view: text, annotated - select for diffs
Sat Jun 4 19:49:28 2011 UTC (12 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Interface to download category grading

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

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