File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.122: download - view: text, annotated - select for diffs
Tue Nov 30 15:55:37 2021 UTC (2 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6955 IP-based blocking. Pass user'sIP address as third arg to
  loncommon::blockcheck() and second to loncommon::blocking_status().

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

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