File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.93: download - view: text, annotated - select for diffs
Thu May 26 18:02:22 2011 UTC (12 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Drop score calculation completed

    1: # The LearningOnline Network with CAPA
    2: # Quick Student Grades Display
    3: #
    4: # $Id: lonquickgrades.pm,v 1.93 2011/05/26 18:02:22 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::lonquickgrades;
   30: 
   31: use strict;
   32: use Apache::Constants qw(:common :http);
   33: use POSIX;
   34: use Apache::loncommon;
   35: use Apache::lonlocal;
   36: use Apache::lonnet;
   37: use Apache::grades;
   38: 
   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: 		
  248:                 if ($completionStatus == $curRes->EXCUSED()) {
  249:                     next;
  250:                 }
  251: 		if ($showPoints) {
  252: 		    my $score = 0;
  253: 		    # If we're not telling status and the answer date isn't passed yet, 
  254: 		    # it's an "attempted" point
  255: 		    if ((($curRes->problemstatus($part) eq 'no') ||
  256:                         ($curRes->problemstatus($part) eq 'no_feedback_ever')) &&
  257: 			($dateStatus != $curRes->ANSWER_OPEN)) {
  258: 			my $status = $curRes->simpleStatus($part);
  259: 			if ($status == $curRes->ATTEMPTED) {
  260: 			    $partsAttempted += $curRes->weight($part);
  261: 			    $totalAttempted += $partsAttempted;
  262: 			}
  263: 		    } else {
  264: 			$score = &Apache::grades::compute_points($curRes->weight($part), $curRes->awarded($part));
  265: 		    }
  266: 		    $partsRight += $score;
  267: 		    $totalRight += $score;
  268: 		    $partsCount += $curRes->weight($part);
  269: 
  270:                     $curRes->{DATA}->{PROB_SCORE}  += $score;
  271:                     $curRes->{DATA}->{PROB_WEIGHT} += $curRes->weight($part);
  272: 
  273: 		    if ($curRes->opendate($part) < $now) {
  274: 			$totalPossible += $curRes->weight($part);
  275:                         $curRes->{DATA}->{PROB_POSSIBLE} += $curRes->weight($part);
  276: 		    }
  277: 		    $totalParts += $curRes->weight($part);
  278: 		} else {
  279: 		    my $status = $curRes->simpleStatus($part);
  280: 		    my $thisright = 0;
  281: 		    $partsCount++;
  282: 		    if ($status == $curRes->CORRECT ||
  283: 			$status == $curRes->PARTIALLY_CORRECT ) {
  284: 			$partsRight++;
  285: 			$totalRight++;
  286: 			$thisright = 1;
  287: 		    }
  288: 
  289: 		    if ($status == $curRes->ATTEMPTED) {
  290: 			$partsAttempted++;
  291: 			$totalAttempted++;
  292: 		    }
  293: 		    
  294: 		    my $dateStatus = $curRes->getDateStatus($part);
  295: 		    $totalParts++;
  296: 		    if ($curRes->opendate($part) < $now) {
  297: 			$totalPossible++;
  298: 		    }
  299: 		}
  300:             }
  301: 
  302:             if ($depth == 1) { # in top-level only
  303: 		$topLevelParts += $partsCount;
  304: 		$topLevelRight += $partsRight;
  305: 		$topLevelAttempted += $partsAttempted;
  306: 	    }
  307: 
  308:             # Crawl down stack and record parts correct and total
  309:             for my $res (@{$stack}) {
  310:                 if (ref($res) && $res->is_map()) {
  311:                     if (!defined($res->{DATA}->{CHILD_PARTS})) {
  312:                         $res->{DATA}->{CHILD_PARTS} = 0;
  313:                         $res->{DATA}->{CHILD_CORRECT} = 0;
  314: 			$res->{DATA}->{CHILD_ATTEMPTED} = 0;
  315:                     }
  316:                     
  317:                     $res->{DATA}->{CHILD_PARTS} += $partsCount;
  318:                     $res->{DATA}->{CHILD_CORRECT} += $partsRight;
  319: 		    $res->{DATA}->{CHILD_ATTEMPTED} += $partsAttempted;
  320:                 }
  321:             }
  322:         }
  323:         $curRes = $iterator->next();
  324:     }
  325:     return ($navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted);
  326: }
  327: 
  328: #
  329: # Outputting everything.
  330: #
  331: 
  332: sub outputTable {
  333: 
  334:     my ($r,$showPoints,$notshowTotals,
  335:            $navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted)=@_;
  336: 
  337:     my @start = (255, 255, 192);
  338:     my @end   = (0, 192, 0);
  339: 
  340:     my $indentString = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  341: 
  342:     # Second pass: Print the maps.
  343:     $r->print(&Apache::loncommon::start_data_table()
  344:              .&Apache::loncommon::start_data_table_header_row()
  345:              .'<th>'.&mt('Folder').'</th>');
  346:     my $title = &mt($showPoints ? "Points Scored" : "Done");
  347:     if ($totalAttempted) {
  348:         $title .= " / " . &mt("Attempted");
  349:     }
  350:     $r->print("<th>$title".($notshowTotals?'':" / ".&mt('Total')).'</th>'
  351:              .&Apache::loncommon::end_data_table_header_row());
  352: #
  353: # Output of folder scores
  354: #
  355: 
  356:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  357:     my $depth = 1;
  358:     $iterator->next(); # ignore first BEGIN_MAP
  359:     my $curRes = $iterator->next();
  360: 
  361:     while ($depth > 0) {
  362:         if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
  363:         if ($curRes == $iterator->END_MAP()) { $depth--; }
  364: 
  365:         if (ref($curRes) && $curRes->is_map()) {
  366:             my $title = $curRes->compTitle();
  367:             
  368:             my $correct = $curRes->{DATA}->{CHILD_CORRECT};
  369:             my $total = $curRes->{DATA}->{CHILD_PARTS};
  370: 	    my $attempted = $curRes->{DATA}->{CHILD_ATTEMPTED};
  371: 
  372:             if ($total > 0) {
  373:                 my $ratio;
  374:                 $ratio = $correct / $total;
  375:                 my $color = &mixColors(\@start, \@end, $ratio);
  376:                 $r->print(&Apache::loncommon::start_data_table_row()
  377:                          .'<td style="background-color:'.$color.';">');
  378:                 
  379: 		my $thisIndent = '';
  380:                 for (my $i = 1; $i < $depth; $i++) { $thisIndent .= $indentString; }
  381:                 
  382:                 $r->print("$thisIndent$title</td>");
  383: 		if ($totalAttempted) {
  384: 		    $r->print('<td valign="top">'
  385:                              .$thisIndent
  386:                              .'<span class="LC_nobreak">'
  387:                              .$correct.' / '.$attempted.($notshowTotals?'':' / '.$total)
  388:                              .'</span></td>'
  389:                              .&Apache::loncommon::end_data_table_row()
  390:                     );
  391: 		} else {
  392: 		    $r->print('<td valign="top">'
  393:                              .$thisIndent
  394:                              .'<span class="LC_nobreak">'
  395:                              .$correct.($notshowTotals?'':' / '.$total)
  396:                              .'</span></td>'
  397:                              .&Apache::loncommon::end_data_table_row());
  398: 		}
  399:             }
  400:         }
  401: 
  402:         $curRes = $iterator->next();
  403:     }
  404: 
  405:     # If there were any problems at the top level, print an extra "catchall"
  406:     if ($topLevelParts > 0) {
  407:         my $ratio = $topLevelRight / $topLevelParts;
  408:         my $color = &mixColors(\@start, \@end, $ratio);
  409:         $r->print(&Apache::loncommon::start_data_table_row()
  410:                  .'<td style="background-color:'.$color.';">');
  411:         $r->print(&mt("Problems Not Contained In A Folder")."</td><td>");
  412:         $r->print("$topLevelRight / $topLevelParts</td>"
  413:                  .&Apache::loncommon::end_data_table_row());
  414:     }
  415: 
  416: #
  417: # show totals (if applicable), close table
  418: #
  419:     if ($showPoints) {
  420:         my $maxHelpLink = &Apache::loncommon::help_open_topic("Quick_Grades_Possibly_Correct");
  421: 
  422:         $title = $showPoints ? "Points" : "Parts Done";
  423:         my $totaltitle = $showPoints ? &mt("Awarded Total Points") : &mt("Total Parts Done");
  424:         $r->print(&Apache::loncommon::start_data_table_row()
  425:                  .'<td colspan="2" align="right">'.$totaltitle.': <b>'.$totalRight.'</b><br />');
  426:         $r->print(&mt('Max Possible To Date')." $maxHelpLink: <b>$totalPossible</b><br />");
  427:         $title = $showPoints ? "Points" : "Parts";
  428:         $r->print(&mt("Total $title In Course").': <b>'.$totalParts.'</b></td>'
  429:                  .&Apache::loncommon::end_data_table_row());
  430:     }
  431: 
  432:     $r->print(&Apache::loncommon::end_data_table());
  433: }
  434: 
  435: #
  436: # === Outputting category-based grades.
  437: #
  438: # $category{'order'}: output order of categories by id
  439: # $category{'all'}: complete list of all categories 
  440: # $category{$id.'_name'}: display-name of category
  441: #
  442: 
  443: sub outputCategories {
  444: 
  445:     my ($r,$showPoints,$notshowTotals,
  446:            $navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted)=@_;
  447: # Take care of storing and retrieving categories
  448: 
  449:     my $cangrade=&Apache::lonnet::allowed('mgr');
  450: 
  451:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  452:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  453:     my %categories=();
  454: # Loading old categories
  455:     %categories=&Apache::lonnet::dump('grading_categories',$cdom,$cnum);
  456: # Storing
  457:     if (($cangrade) && (($env{'form.storechanges'}) || ($env{'form.storemove'} ne '') || ($env{'form.cmd'} ne ''))) {
  458: # Process the changes
  459:         %categories=&process_category_edits($r,$cangrade,%categories);
  460: # Actually store
  461:         &Apache::lonnet::put('grading_categories',\%categories,$cdom,$cnum);
  462:     }
  463: # new categories loaded now
  464:     &output_category_table($r,$cangrade,$navmap,%categories);
  465: #
  466:     if ($cangrade) {
  467:         $r->print(&Apache::loncommon::resourcebrowser_javascript().
  468:                   '<input type="hidden" name="storemove" value="" />'.
  469:                   '<input type="hidden" name="cmd" value="" />'.
  470:                   '<input type="hidden" name="resourcesymb" value="" />'.
  471:                   '<input type="submit" name="storechanges" value="'.&mt("Save changes to grading categories").'" />'.
  472:                   '<script>function storecmd (cmd) { document.quickform.cmd.value=cmd; document.quickform.submit(); }</script>');
  473:     }
  474: #
  475: # Debug
  476: #
  477: #    my %data=&dumpdata($navmap);
  478: #    foreach (keys(%data)) {
  479: #        $r->print("\n<br />".$_.'='.$data{$_});
  480: #    }
  481: #   my @debugarray=('5:1','4:3','1:1','5:5','6:7');
  482: #   $r->print("Array: ".join(',',@debugarray).'<br />');
  483: #   $r->print("0,0,0: ".join(',',&drop(0,0,0,@debugarray)).'<br />');
  484: #   $r->print("1,0,0: ".join(',',&drop(1,0,0,@debugarray)).'<br />');
  485: #   $r->print("0,1,0: ".join(',',&drop(0,1,0,@debugarray)).'<br />');
  486: #   $r->print("1,1,0: ".join(',',&drop(1,1,0,@debugarray)).'<br />');
  487: #
  488: #   $r->print("0,0,2: ".join(',',&drop(0,0,2,@debugarray)).'<br />');
  489: #   $r->print("1,0,2: ".join(',',&drop(1,0,2,@debugarray)).'<br />');
  490: #   $r->print("0,1,2: ".join(',',&drop(0,1,2,@debugarray)).'<br />');
  491: #   $r->print("1,1,2: ".join(',',&drop(1,1,2,@debugarray)).'<br />');
  492: #
  493: #   $r->print("0,0,4: ".join(',',&drop(0,0,4,@debugarray)).'<br />');
  494: #   $r->print("1,0,4: ".join(',',&drop(1,0,4,@debugarray)).'<br />');
  495: #   $r->print("0,1,4: ".join(',',&drop(0,1,4,@debugarray)).'<br />');
  496: #   $r->print("1,1,4: ".join(',',&drop(1,1,4,@debugarray)).'<br />');
  497: #
  498: #   $r->print("0,0,5: ".join(',',&drop(0,0,5,@debugarray)).'<br />');
  499: #   $r->print("1,0,5: ".join(',',&drop(1,0,5,@debugarray)).'<br />');
  500: #   $r->print("0,1,5: ".join(',',&drop(0,1,5,@debugarray)).'<br />');
  501: #   $r->print("1,1,5: ".join(',',&drop(1,1,5,@debugarray)).'<br />');
  502: #
  503: #   $r->print("0,0,7: ".join(',',&drop(0,0,7,@debugarray)).'<br />');
  504: #   $r->print("1,0,7: ".join(',',&drop(1,0,7,@debugarray)).'<br />');
  505: #   $r->print("0,1,7: ".join(',',&drop(0,1,7,@debugarray)).'<br />');
  506: #   $r->print("1,1,7: ".join(',',&drop(1,1,7,@debugarray)).'<br />');
  507: 
  508: }
  509: 
  510: #
  511: # Get data for all symbs
  512: #
  513: 
  514: sub dumpdata {
  515:     my ($navmap)=@_;
  516:     my %returndata=();
  517: 
  518: # Run through the map and get all data
  519: 
  520:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  521:     my $depth = 1;
  522:     $iterator->next(); # ignore first BEGIN_MAP
  523:     my $curRes = $iterator->next();
  524: 
  525:     while ($depth > 0) {
  526:         if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
  527:         if ($curRes == $iterator->END_MAP()) { $depth--; }
  528:         if (ref($curRes)) {
  529:             if ($curRes->is_map()) {
  530:                 $returndata{$curRes->symb()}='folder:'.$curRes->{DATA}->{CHILD_PARTS}.':'.$curRes->{DATA}->{CHILD_ATTEMPTED}.':'.$curRes->{DATA}->{CHILD_CORRECT};
  531:             } else {
  532:                 $returndata{$curRes->symb()}='res:'.$curRes->{DATA}->{PROB_WEIGHT}.':'.$curRes->{DATA}->{PROB_POSSIBLE}.':'.$curRes->{DATA}->{PROB_SCORE};
  533:             } 
  534:         }
  535:         $curRes = $iterator->next();
  536:     }
  537:     return %returndata;
  538: }
  539: 
  540: #
  541: # Process editing commands, update category hash
  542: #
  543: 
  544: sub process_category_edits {
  545:     my ($r,$cangrade,%categories)=@_;
  546:     unless ($cangrade) { return %categories; }
  547: # First store everything
  548:     foreach my $id (split(/\,/,$categories{'order'})) {
  549: # Set names, types, and weight (there is only one of each per category)
  550:         %categories=&set_category_name($cangrade,$id,$env{'form.name_'.$id},%categories);
  551:         %categories=&set_category_total($cangrade,$id,$env{'form.totaltype_'.$id},$env{'form.total_'.$id},%categories);
  552:         %categories=&set_category_weight($cangrade,$id,$env{'form.weight_'.$id},%categories);
  553:         %categories=&set_category_displayachieved($cangrade,$id,$env{'form.displayachieved_'.$id},%categories);
  554: # Set values for category rules (before names may change)
  555:         %categories=&set_category_rules($cangrade,$id,%categories);
  556:     }
  557: 
  558: # Now deal with commands
  559:     my $cmd=$env{'form.cmd'};
  560:     if ($cmd eq 'createnewcat') {
  561:         %categories=&make_new_category($r,$cangrade,undef,%categories);
  562:     } elsif ($cmd=~/^up\_(.+)$/) {
  563:         %categories=&move_up_category($1,$cangrade,%categories);
  564:     } elsif ($cmd=~/^down\_(.+)$/) {
  565:         %categories=&move_down_category($1,$cangrade,%categories);
  566:     } elsif ($cmd=~/^delcat\_(.+)$/) {
  567:         %categories=&del_category($1,$cangrade,%categories);
  568:     } elsif ($cmd=~/^addcont\_(.+)$/) {
  569:         %categories=&add_category_content($1,$cangrade,$env{'form.resourcesymb'},%categories);
  570:     } elsif ($cmd=~/^delcont\_(.+)\_\_\_\_\_\_(.+)$/) {
  571:         %categories=&del_category_content($1,$cangrade,$2,%categories);
  572:     } elsif ($cmd=~/^newrule\_(.+)$/) {
  573:         %categories=&add_calculation_rule($1,$cangrade,':',%categories);
  574:     } elsif ($cmd=~/^delrule\_(.+)\_\_\_\_\_\_(.*)$/) {
  575:         %categories=&del_calculation_rule($1,$cangrade,$2,%categories);
  576:     }
  577: # Move to a new position
  578:     my $moveid=$env{'form.storemove'};
  579:     if ($moveid) {
  580:         %categories=&move_category($moveid,$cangrade,$env{'form.newpos_'.$moveid},%categories);
  581:     } 
  582:     return %categories;
  583: }
  584: 
  585: #
  586: # Output the table
  587: #
  588: 
  589: sub output_category_table {
  590:     my ($r,$cangrade,$navmaps,%categories)=@_;
  591:     my $sum=0;
  592:     my $total=0;
  593:     $r->print(&Apache::loncommon::start_data_table());
  594: #
  595:     &output_category_table_header($r,$cangrade);
  596: #
  597:     my @order=split(/\,/,$categories{'order'});
  598: #
  599:     my %performance=&dumpdata($navmaps);
  600:     my $maxpos=$#order;
  601:     for (my $i=0;$i<=$maxpos;$i++) {
  602:         my ($value,$weight)=&output_and_calc_category($r,$cangrade,$navmaps,$order[$i],$i,$maxpos,\%performance,1,%categories);
  603:         $sum+=$value*$weight;
  604:         $total+=$weight;
  605:     }
  606: #
  607:     &bottom_line_category($r,$cangrade,$sum,$total);
  608: #
  609:     $r->print(&Apache::loncommon::end_data_table());
  610:     return $sum;
  611: }
  612: 
  613: sub output_category_table_header {
  614:     my ($r,$cangrade)=@_;
  615:     $r->print(&Apache::loncommon::start_data_table_header_row());
  616:     if ($cangrade) {
  617:         $r->print('<th colspan="2">'.&mt("Move").'</th><th>'.&mt('Action').'</th>');
  618:     }
  619:     $r->print('<th>'.&mt('Category').'</th>'.
  620:               '<th>'.&mt('Contents').'</th>'.
  621:               '<th>'.&mt('Total Points').'</th>'.
  622:               '<th>'.&mt('Calculation').'</th>'.
  623:               '<th>'.&mt('Relative Weight').'</th>'.
  624:               '<th>'.&mt('Achieved').'</th>');
  625:     $r->print(&Apache::loncommon::end_data_table_header_row());
  626: }
  627: 
  628: 
  629: #
  630: # Output one category to table
  631: #
  632: 
  633: sub output_and_calc_category {
  634:     my ($r,$cangrade,$navmaps,$id,$currentpos,$maxpos,$performance,$output,%categories)=@_;
  635:     my $value=0;
  636:     my $weight=0;
  637:     my $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
  638:     my %lt=&Apache::lonlocal::texthash(
  639:            'up' => 'Move Up',
  640:            'dw' => 'Move Down');
  641:     if ($output) { $r->print("\n".&Apache::loncommon::start_data_table_row()); }
  642: 
  643:     if ($output && $cangrade) {
  644:         $r->print(<<ENDMOVE);
  645: <td>
  646: <div class="LC_docs_entry_move">
  647:   <a href='javascript:storecmd("up_$id");'>
  648:     <img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" />
  649:   </a>
  650: </div>
  651: <div class="LC_docs_entry_move">
  652:   <a href='javascript:storecmd("down_$id");'>
  653:     <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" />
  654:   </a>
  655: </div>
  656: </td>
  657: ENDMOVE
  658:         $r->print("\n<td>\n<select name='newpos_$id' onchange='this.form.storemove.value=\"$id\";this.form.submit()'>");
  659:         for (my $i=0;$i<=$maxpos;$i++) {
  660:             if ($i==$currentpos) {
  661:                 $r->print('<option value="" selected="selected">('.$i.')</option>');
  662:             } else {
  663:                 $r->print('<option value="'.$i.'">'.$i.'</option>');
  664:             }
  665:         }
  666:         $r->print("\n</select>\n</td>\n");
  667:         $r->print('<td><a href="javascript:storecmd(\'delcat_'.$id.'\');">'.&mt('Delete').'</a></td>');
  668:         $r->print('<td><input type="text" name="name_'.$id.
  669:                   '" value="'.&Apache::lonhtmlcommon::entity_encode($categories{$id.'_name'}).'" /></td>');
  670:     } elsif ($output) {
  671:         $r->print('<td>'.$categories{$id.'_name'}.'</td>');
  672:     }
  673: # Content display and summing up of points
  674:     my $totalpossible=0;
  675:     my $totalcorrect=0;
  676:     my @individual=();
  677:     if ($output) { $r->print('<td><ul>'); }
  678:     foreach my $contentid (split(/\,/,$categories{$id.'_content'})) {
  679:         my ($type,$possible,$attempted,$correct)=split(/\:/,$$performance{$contentid});
  680:         $totalpossible+=$possible;
  681:         $totalcorrect+=$correct;
  682:         if ($possible>0) { push(@individual,"$possible:$correct"); }
  683:         if ($output) {
  684:            $r->print('<li>');
  685:            $r->print(&Apache::lonnet::gettitle($contentid).' ('.$correct.'/'.$possible.')');
  686:            if ($cangrade) {
  687:               $r->print(' <a href="javascript:storecmd(\'delcont_'.$id.'______'.$contentid.'\');">'.&mt('Delete').'</a>');
  688:            }
  689:            $r->print('</li>');
  690:         }
  691:     }
  692:     if ($output) {
  693:        $r->print('</ul>');
  694:        if ($cangrade) {
  695:            $r->print('<br />'.&Apache::loncommon::selectresource_link('quickform','addcont_'.$id,&mt('Add Problem or Folder')).'<br />');
  696:        }
  697:        $r->print('<p>'.&mt('Total raw points: [_1]/[_2]',$totalcorrect,$totalpossible).'</p>');
  698:        $r->print('</td>'); 
  699:     }
  700: # Total
  701:     if ($output) { $r->print('<td>'); }
  702:     if ($cangrade) {
  703:        if ($output) { 
  704:           $r->print(
  705:                   '<select name="totaltype_'.$id.'">'.
  706:                   '<option value="default"'.($categories{$id.'_totaltype'} eq 'default'?' selected="selected"':'').'>'.&mt('default').'</option>'.
  707:                   '<option value="typein"'.($categories{$id.'_totaltype'} eq 'typein'?' selected="selected"':'').'>'.&mt('Type-in value').'</option>'.
  708:                   '</select>'.
  709:                   '<input type="text" size="4" name="total_'.$id.
  710:                   '" value="'.&Apache::lonhtmlcommon::entity_encode($categories{$id.'_total'}).'" />'); 
  711:        }
  712:     } else {
  713:        if ($output) {
  714:           $r->print('<td>'.($categories{$id.'_totaltype'} eq 'default'?&mt('default'):$categories{$id.'_total'}));
  715:        }
  716:     }
  717: # Adjust total points
  718:     if ($categories{$id.'_totaltype'} eq 'typein') {
  719:        $totalpossible=1.*$categories{$id.'_total'};
  720:     }
  721:     if ($output) {
  722:        $r->print('<p>'.&mt('Adjusted raw points: [_1]/[_2]',$totalcorrect,$totalpossible).'</p>');
  723:     }
  724: 
  725: 
  726: # Calculation
  727:     if ($output) { $r->print('<td><ul>'); }
  728:     foreach my $calcrule (split(/\,/,$categories{$id.'_calculations'})) {
  729:         if ($output) { $r->print('<li>'); }
  730:         my ($code,$value)=split(/\:/,$calcrule);
  731:         if ($output) { $r->print(&pretty_prt_rule($cangrade,$id,$code,$value)); }
  732:         if ($cangrade) {
  733:            if ($output) { $r->print(' <a href="javascript:storecmd(\'delrule_'.$id.'______'.$code.'\');">'.&mt('Delete').'</a>'); }
  734:         }
  735:         if ($code eq 'capabove') {
  736:             if ($totalpossible>0) {
  737:                 if ($totalcorrect/$totalpossible>$value/100.) {
  738:                     $totalcorrect=$totalpossible*$value/100.;
  739:                 }
  740:             }
  741:         } elsif ($code eq 'capbelow') {
  742:             if ($totalpossible>0) {
  743:                 if ($totalcorrect/$totalpossible<$value/100.) {
  744:                     $totalcorrect=$totalpossible*$value/100.;
  745:                 }
  746:             }
  747:         } elsif ($code eq 'droplow') {
  748:             ($totalcorrect,@individual)=&drop(0,0,$value,@individual);
  749:         } elsif ($code eq 'drophigh') {
  750:             ($totalcorrect,@individual)=&drop(1,0,$value,@individual);
  751:         } elsif ($code eq 'droplowperc') {
  752:             ($totalcorrect,@individual)=&drop(0,1,$value,@individual);
  753:         } elsif ($code eq 'drophighperc') {
  754:             ($totalcorrect,@individual)=&drop(1,1,$value,@individual);
  755:         }
  756:         if ($output) { $r->print('</li>'); }
  757:     }
  758:     if ($output) { 
  759:         $r->print('</ul>'); 
  760:         if ($cangrade) { $r->print('<br />'.&new_calc_rule_form($id)); }
  761:         $r->print('<p>'.&mt('Calculated points: [_1]/[_2]',$totalcorrect,$totalpossible).'</p>');
  762:         $r->print('</td>'); 
  763:     }
  764: 
  765: # Weight
  766:     if ($cangrade) {
  767:        if ($output) { 
  768:           $r->print('<td>'.
  769:                   '<input type="text" size="4" name="weight_'.$id.
  770:                   '" value="'.&Apache::lonhtmlcommon::entity_encode($categories{$id.'_weight'}).'" /></td>');
  771:        }
  772:     } else {
  773:        if ($output) {
  774:           $r->print('<td>'.$categories{$id.'_weight'}.'</td>');
  775:        }
  776:     }
  777: # Achieved
  778:     if ($output) { $r->print('<td>'); }
  779:     if ($cangrade) {
  780:         if ($output) {
  781:            $r->print('<select name="displayachieved_'.$id.'">'.
  782:                   '<option value="percent"'.($categories{$id.'_displayachieved'} eq 'percent'?' selected="selected"':'').'>'.&mt('percent').'</option>'.
  783:                   '<option value="points"'.($categories{$id.'_displayachieved'} eq 'points'?' selected="selected"':'').'>'.&mt('points').'</option>'.
  784:                   '</select>');
  785:         }
  786:     } else {
  787:         if ($output) {
  788:             if ($categories{$id.'_displayachieved'} eq 'percent') {
  789:                 $r->print(&mt('percent'));
  790:             } else {
  791:                 $r->print(&mt('points'));
  792:             }
  793:         }
  794:     }
  795:     if ($output) { $r->print('</td>'); }
  796: 
  797:     return ($value,$weight);
  798: }
  799: 
  800: #
  801: # Drop folders and problems
  802: #
  803: 
  804: sub drop {
  805:     my ($high,$percent,$n,@individual)=@_;
  806:     my @newindividual=sort {
  807:         my ($pa,$ca)=split(/\:/,$a);
  808:         my ($pb,$cb)=split(/\:/,$b);
  809:         if ($percent) {
  810:             my $perca=0;
  811:             if ($pa>0) { $perca=$ca/$pa; }
  812:             my $percb=0;
  813:             if ($pb>0) { $percb=$cb/$pb; }
  814:             $perca<=>$percb;
  815:         } else {
  816:             $ca<=>$cb;
  817:         }
  818:     } @individual;
  819:     if ($#newindividual>=$n) {
  820:         if ($high) {
  821:            splice(@newindividual,$#newindividual+1-$n,$n);
  822:         } else {
  823:            splice(@newindividual,0,$n);
  824:         }
  825:     } else {
  826:         @newindividual=();
  827:     }
  828:     my $newcorrect=0;
  829:     for my $score (@newindividual) {
  830:         $newcorrect+=(split(/\:/,$score))[1];
  831:     }
  832:     return ($newcorrect,@newindividual);
  833: } 
  834: #
  835: # Bottom line with grades
  836: #
  837: 
  838: sub bottom_line_category {
  839:     my ($r,$cangrade,$sum,$total)=@_;
  840:     $r->print(&Apache::loncommon::start_data_table_row());
  841:     if ($cangrade) {
  842:         $r->print('<td colspan="3"><a href="javascript:storecmd(\'createnewcat\');">'.&mt('Create New Category').'</a></td>');
  843:     }
  844:     $r->print('<td colspan="6">'.&mt('Current:').$sum.'<br />'.&mt('Total:').$total.'<br /></td>');
  845: }
  846: 
  847: #
  848: # Make one new category
  849: #
  850: 
  851: sub make_new_category {
  852:     my ($r,$cangrade,$ordernum,%categories)=@_;
  853:     unless ($cangrade) { return %categories; }
  854: # Generate new ID
  855:     my $id=time.'_'.$$.'_'.rand(10000);
  856: # Add new ID to list of all IDs ever created in this course
  857:     $categories{'all'}.=','.$id;
  858:     $categories{'all'}=~s/^\,//;
  859: # Add new ID to ordered list of displayed and evaluated categories
  860:     $categories{'order'}.=','.$id;
  861:     $categories{'order'}=~s/^\,//;
  862: # Move it into desired space
  863:     if (defined($ordernum)) {
  864:         %categories=&move_category($id,$cangrade,$ordernum,%categories);
  865:     }
  866:     $categories{$id.'_weight'}=0;
  867:     $categories{$id.'_totaltype'}='default';
  868:     $categories{$id.'_displayachieved'}='percent';
  869:     return %categories;
  870: }
  871: 
  872: 
  873: # === Calculation Rule Editing
  874: 
  875: sub category_rule_codes {
  876:     return &Apache::lonlocal::texthash(
  877:                 'droplowperc'  => 'Drop N lowest grade percentage problems/folders',
  878:                 'drophighperc' => 'Drop N highest grade percentage problems/folderss',
  879:                 'droplow'  => 'Drop N lowest point problems/folders',
  880:                 'drophigh' => 'Drop N highest point problems/folders',
  881:                 'capabove' => 'Cap percentage above N percent',
  882:                 'capbelow' => 'Cap percentage below N percent');
  883: }
  884: 
  885: sub pretty_prt_rule {
  886:     my ($cangrade,$id,$code,$value)=@_;
  887:     my $cid=$id.'_'.$code;
  888:     my %lt=&category_rule_codes();
  889:     my $ret='<span class="LC_nobreak">';
  890:     if ($cangrade) {
  891:         $ret.='<select name="sel_'.$cid.'">';
  892:         foreach my $calc (''=>'',sort(keys(%lt))) {
  893:             $ret.='<option value="'.$calc.'"'.($calc eq $code?' selected="selected"':'').' />'.$lt{$calc}.'</input>';
  894:         }
  895:         $ret.='</select> N=<input type="text" size="5" name="val_'.$cid.'" value="'.$value.'" /></span>';
  896:     } else {
  897:         $ret.=$lt{$code}.'; N='.$value;
  898:     }
  899:     $ret.='</span>';
  900:     return $ret;
  901: }
  902: 
  903: sub new_calc_rule_form {
  904:     my ($id)=@_;
  905:     return '<a href="javascript:storecmd(\'newrule_'.$id.'\');">'.&mt('New Calculation Rule').'</a>';
  906: }
  907: 
  908: #
  909: # Add a calculation rule
  910: #
  911: 
  912: sub add_calculation_rule {
  913:     my ($id,$cangrade,$newcontent,%categories)=@_;
  914:     unless ($cangrade) { return %categories; }
  915:     my %newcontent=($newcontent => 1);
  916:     foreach my $current (split(/\,/,$categories{$id.'_calculations'})) {
  917:         $newcontent{$current}=1;
  918:     }
  919:     $categories{$id.'_calculations'}=join(',',sort(keys(%newcontent)));
  920:     return %categories;
  921: }
  922: 
  923: #
  924: # Delete a calculation rule
  925: #
  926: 
  927: sub del_calculation_rule {
  928:     my ($id,$cangrade,$delcontent,%categories)=@_;
  929:     unless ($cangrade) { return %categories; }
  930:     my @newcontent=();
  931:     foreach my $current (split(/\,/,$categories{$id.'_calculations'})) {
  932:         unless ($current=~/^\Q$delcontent\E\:/) {
  933:             push(@newcontent,$current);
  934:         }
  935:     }
  936:     $categories{$id.'_calculations'}=join(',',@newcontent);
  937:     return %categories;
  938: }
  939: 
  940: sub set_category_rules {
  941:     my ($cangrade,$id,%categories)=@_;
  942:     unless ($cangrade) { return %categories; }
  943:     my %lt=&category_rule_codes();
  944:     my @newrules=();
  945:     foreach my $code ('',(keys(%lt))) {
  946:         if ($env{'form.sel_'.$id.'_'.$code}) {
  947:             push(@newrules,$env{'form.sel_'.$id.'_'.$code}.':'.$env{'form.val_'.$id.'_'.$code});
  948:         }
  949:     }
  950:     $categories{$id.'_calculations'}=join(',',sort(@newrules));
  951:     return %categories;
  952: }
  953: 
  954: 
  955: # === Category Editing
  956: 
  957: #
  958: # Add to category content
  959: #
  960: 
  961: sub add_category_content {
  962:     my ($id,$cangrade,$newcontent,%categories)=@_;
  963:     unless ($cangrade) { return %categories; }
  964:     &Apache::lonnet::logthis("In here $newcontent");
  965:     my %newcontent=($newcontent => 1);
  966:     foreach my $current (split(/\,/,$categories{$id.'_content'})) {
  967:         $newcontent{$current}=1;
  968:     }
  969:     $categories{$id.'_content'}=join(',',sort(keys(%newcontent)));
  970:     return %categories;
  971: }
  972: 
  973: #
  974: # Delete from category content
  975: #
  976: 
  977: sub del_category_content {
  978:     my ($id,$cangrade,$delcontent,%categories)=@_;
  979:     unless ($cangrade) { return %categories; }
  980:     my @newcontent=();
  981:     foreach my $current (split(/\,/,$categories{$id.'_content'})) {
  982:         unless ($current eq $delcontent) {
  983:             push(@newcontent,$current);
  984:         }
  985:     }
  986:     $categories{$id.'_content'}=join(',',@newcontent);
  987:     return %categories;
  988: }
  989: 
  990: #
  991: # Delete category
  992: #
  993: 
  994: sub del_category {
  995:     my ($id,$cangrade,%categories)=@_;
  996:     unless ($cangrade) { return %categories; }
  997:     my @neworder=();
  998:     foreach my $currentid (split(/\,/,$categories{'order'})) {
  999:         unless ($currentid eq $id) {
 1000:             push(@neworder,$currentid);
 1001:         }
 1002:     }
 1003:     $categories{'order'}=join(',',@neworder);
 1004:     return %categories;
 1005: }
 1006: 
 1007: #
 1008: # Move category up
 1009: #
 1010: 
 1011: sub move_up_category {
 1012:     my ($id,$cangrade,%categories)=@_;
 1013:     my $currentpos=&current_pos_category($id,%categories);
 1014:     if ($currentpos<1) { return %categories; }
 1015:     return &move_category($id,$cangrade,$currentpos-1,%categories);
 1016: }
 1017: 
 1018: #
 1019: # Move category down
 1020: #
 1021: 
 1022: sub move_down_category {
 1023:     my ($id,$cangrade,%categories)=@_;
 1024:     my $currentpos=&current_pos_category($id,%categories);
 1025:     my @order=split(/\,/,$categories{'order'});
 1026:     if ($currentpos>=$#order) { return %categories; }
 1027:     return &move_category($id,$cangrade,$currentpos+1,%categories);
 1028: }
 1029: 
 1030: #
 1031: # Move a category to a desired position n the display order
 1032: #
 1033: 
 1034: sub move_category {
 1035:     my ($id,$cangrade,$ordernum,%categories)=@_;
 1036:     unless ($cangrade) { return %categories; }
 1037:     my @order=split(/\,/,$categories{'order'});
 1038: # Where is the index currently?
 1039:     my $currentpos=&current_pos_category($id,%categories);
 1040:     if (defined($currentpos)) {
 1041:         if ($currentpos<$ordernum) {
 1042: # This is moving to a higher index
 1043: # ....X1234....
 1044: # ....1234X....
 1045:             for (my $i=$currentpos;$i<$ordernum;$i++) {
 1046:                 $order[$i]=$order[$i+1];
 1047:             }
 1048:             $order[$ordernum]=$id;
 1049:         }
 1050:         if ($currentpos>$ordernum) {
 1051: # This is moving to a lower index
 1052: # ....1234X....
 1053: # ....X1234....
 1054:             for (my $i=$currentpos;$i>$ordernum;$i--) {
 1055:                 $order[$i]=$order[$i-1];
 1056:             }
 1057:             $order[$ordernum]=$id;
 1058:         }
 1059:     }
 1060:     $categories{'order'}=join(',',@order);
 1061:     return %categories;
 1062: }
 1063: 
 1064: #
 1065: #  Find current postion of a category in the order
 1066: #
 1067: 
 1068: sub current_pos_category {
 1069:     my ($id,%categories)=@_;
 1070:     my @order=split(/\,/,$categories{'order'});
 1071:     for (my $i=0;$i<=$#order;$i++) {
 1072:         if ($order[$i] eq $id) { return $i; }
 1073:     }
 1074: # not found
 1075:     return undef;
 1076: }
 1077: 
 1078: #
 1079: # Set name of a category
 1080: #
 1081: sub set_category_name {
 1082:     my ($cangrade,$id,$name,%categories)=@_;
 1083:     unless ($cangrade) { return %categories; }
 1084:     $categories{$id.'_name'}=$name;
 1085:     return %categories;
 1086: }
 1087: 
 1088: #
 1089: # Set total of a category
 1090: #
 1091: sub set_category_total {
 1092:     my ($cangrade,$id,$totaltype,$total,%categories)=@_;
 1093:     unless ($cangrade) { return %categories; }
 1094:     if (($categories{$id.'_total'} eq '') && ($total=~/\d/)) {
 1095:         $totaltype='typein';
 1096:     }
 1097:     $categories{$id.'_totaltype'}=$totaltype;
 1098:     if ($totaltype eq 'default') {
 1099:         $categories{$id.'_total'}='';
 1100:     } else {
 1101:         $total=~s/\D//gs;
 1102:         unless ($total) { $total=0; }
 1103:         $categories{$id.'_total'}=$total;
 1104:     }
 1105:     return %categories;
 1106: }
 1107: 
 1108: sub set_category_weight {
 1109:     my ($cangrade,$id,$weight,%categories)=@_;
 1110:     unless ($cangrade) { return %categories; }
 1111:     $weight=~s/\D//gs;
 1112:     unless ($weight) { $weight=0; }
 1113:     $categories{$id.'_weight'}=$weight;
 1114:     return %categories;
 1115: }
 1116: 
 1117: sub set_category_displayachieved {
 1118:     my ($cangrade,$id,$value,%categories)=@_;
 1119:     unless ($cangrade) { return %categories; }
 1120:     unless (($value eq 'percent') || ($value eq 'points')) { $value='percent'; }
 1121:     $categories{$id.'_displayachieved'}=$value;
 1122:     return %categories;
 1123: }
 1124: 
 1125: 
 1126: #
 1127: # === end category-related
 1128: #
 1129: #
 1130: # Pass this two refs to arrays for the start and end color, and a number
 1131: # from 0 to 1 for how much of the latter you want to mix in. It will
 1132: # return a string ready to show ("#FFC309");
 1133: 
 1134: sub mixColors {
 1135:     my $start = shift;
 1136:     my $end = shift;
 1137:     my $ratio = shift;
 1138:     
 1139:     my ($a,$b);
 1140:     my $final = "";
 1141:     $a = $start->[0]; $b = $end->[0];
 1142:     my $mix1 = POSIX::floor((1-$ratio)*$a + $ratio*$b);
 1143:     $a = $start->[1]; $b = $end->[1];
 1144:     my $mix2 = POSIX::floor((1-$ratio)*$a + $ratio*$b);
 1145:     $a = $start->[2]; $b = $end->[2];
 1146:     my $mix3 = POSIX::floor((1-$ratio)*$a + $ratio*$b);
 1147: 
 1148:     $final = sprintf "%02x%02x%02x", $mix1, $mix2, $mix3;
 1149:     return "#" . $final;
 1150: }
 1151: 
 1152: 1;

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