File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.106: download - view: text, annotated - select for diffs
Fri Mar 13 22:34:00 2015 UTC (9 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Student's display of grades will check if it has been more than 10 minutes
  since last check for content change in course.
  - If so, loncommon::needs_coursereinit() will be called to check if
    course was changed after "Big Hash" was last tied for the user's session.
  - Course will be re-initialized (or Switch Server link displayed), as needed.
- No check made for critical messages for privileged users ('mgr' priv).

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

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