File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.109: download - view: text, annotated - select for diffs
Sat Apr 2 04:30:21 2016 UTC (8 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6808. New course container -- "Placement" for Placement Tests.
  Work in progress.

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

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