File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.108: download - view: text, annotated - select for diffs
Sun Jan 31 21:25:38 2016 UTC (8 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Score upload form supports identification of a user based on clicker ID,
  for Course Coordinators who prefer not to use LON-CAPA's in-built
  "Process Clicker" utility.
- clickers.db file on a library server contains key = value pairs, where key
  is (escaped) clicker ID, and value is (escaped) comma-separated list of
  usernames who registered that particular clicker ID.
- bi-nightly run of searchcat.pl will update clickers.db file.

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

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