File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.99: download - view: text, annotated - select for diffs
Fri Jun 3 00:04:47 2011 UTC (12 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Work on category calculation for spreadsheets

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

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