File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.97: download - view: text, annotated - select for diffs
Wed Jun 1 21:32:50 2011 UTC (12 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Slight optimization (10%)

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

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