File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.114: download - view: text, annotated - select for diffs
Tue Nov 13 03:59:00 2018 UTC (5 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6400
  - deeplink parameter determines whether deep-linked items are listed in
    and/or linked to in Course Contents and student's view of Grades

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

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