File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.102: download - view: text, annotated - select for diffs
Sat Jun 25 20:12:56 2011 UTC (12 years, 10 months ago) by www
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
Starting on Excel output

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

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