File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.100: download - view: text, annotated - select for diffs
Fri Jun 3 01:07:22 2011 UTC (12 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Work on getting data for complete class list

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

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