File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.125: download - view: text, annotated - select for diffs
Sat Oct 29 18:13:28 2022 UTC (18 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6975
  - &get_supplemental() routine moved from lonnet.pm to loncommon.pm
  - use LONCAPA::map() moved out of conditional block in loncommon.pm
  - $keeporder arg for update_content_constraints() no longer needed

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

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