File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.98: download - view: text, annotated - select for diffs
Thu Jun 2 01:34:34 2011 UTC (12 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Another 30% time savings

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

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