File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.127: download - view: text, annotated - select for diffs
Fri Jan 5 19:10:30 2024 UTC (4 months, 1 week ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- It's $env{'request.course.sec'} not %env{'request.user.section'} and
  apparently $uname and $udom are only set when user has mgr priv.

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

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