Annotation of loncom/interface/spreadsheet/assesscalc.pm, revision 1.52

1.1       matthew     1: #
1.52    ! raeburn     2: # $Id: assesscalc.pm,v 1.51 2005/10/12 21:29:49 albertel Exp $
1.1       matthew     3: #
                      4: # Copyright Michigan State University Board of Trustees
                      5: #
                      6: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      7: #
                      8: # LON-CAPA is free software; you can redistribute it and/or modify
                      9: # it under the terms of the GNU General Public License as published by
                     10: # the Free Software Foundation; either version 2 of the License, or
                     11: # (at your option) any later version.
                     12: #
                     13: # LON-CAPA is distributed in the hope that it will be useful,
                     14: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     15: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     16: # GNU General Public License for more details.
                     17: #
                     18: # You should have received a copy of the GNU General Public License
                     19: # along with LON-CAPA; if not, write to the Free Software
                     20: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     21: #
                     22: # /home/httpd/html/adm/gpl.txt
                     23: #
                     24: # http://www.lon-capa.org/
                     25: #
                     26: # The LearningOnline Network with CAPA
                     27: # Spreadsheet/Grades Display Handler
                     28: #
                     29: # POD required stuff:
                     30: 
                     31: =head1 NAME
                     32: 
                     33: assesscalc
                     34: 
                     35: =head1 SYNOPSIS
                     36: 
                     37: =head1 DESCRIPTION
                     38: 
                     39: =cut
                     40: 
                     41: ###################################################
                     42: ###                 AssessSheet                 ###
                     43: ###################################################
                     44: package Apache::assesscalc;
                     45: 
                     46: use strict;
1.18      matthew    47: use warnings FATAL=>'all';
                     48: no warnings 'uninitialized';
1.1       matthew    49: use Apache::Constants qw(:common :http);
                     50: use Apache::lonnet;
1.2       matthew    51: use Apache::loncommon;
1.1       matthew    52: use Apache::Spreadsheet;
1.25      matthew    53: use Apache::loncoursedata();
1.1       matthew    54: use HTML::Entities();
                     55: use Spreadsheet::WriteExcel;
                     56: use GDBM_File;
                     57: use Time::HiRes;
1.26      www        58: use Apache::lonlocal;
1.1       matthew    59: 
                     60: @Apache::assesscalc::ISA = ('Apache::Spreadsheet');
                     61: 
                     62: ########################################################
                     63: ########################################################
                     64: 
                     65: =pod
                     66: 
                     67: =head2 Package Variables
                     68: 
                     69: =over 4
                     70: 
                     71: =item %Exportrows
                     72: 
                     73: =item $current_name
                     74: 
                     75: =item $current_domain
                     76: 
                     77: =item $current_course
                     78: 
                     79: =item %parmhash
                     80: 
                     81: =item %nice_parameter_name
                     82: 
                     83: =item %useropt
                     84: 
                     85: =item %courseopt
                     86: 
                     87: =back 
                     88: 
                     89: =cut
                     90: 
                     91: ########################################################
                     92: ########################################################
                     93: 
                     94: my %Exportrows;
1.22      matthew    95: my %newExportrows;
1.1       matthew    96: 
                     97: my $current_name;
                     98: my $current_domain;
                     99: my $current_course;
                    100: 
                    101: my %parmhash;
                    102: my %nice_parameter_name;
                    103: 
                    104: my %useropt;
1.22      matthew   105: my %userdata;
1.1       matthew   106: my %courseopt;
1.37      matthew   107: my $navmap;
1.1       matthew   108: 
                    109: ########################################################
                    110: ########################################################
                    111: 
                    112: =pod
                    113: 
                    114: =head2 Package Subroutines
                    115: 
                    116: =item &clear_package()
                    117: 
1.22      matthew   118: Reset all package variables and clean up caches.
1.1       matthew   119: 
                    120: =cut
                    121: 
                    122: ########################################################
                    123: ########################################################
                    124: sub clear_package {
1.22      matthew   125:     if (defined($current_name) &&
                    126:         defined($current_domain) &&
                    127:         defined($current_course) &&
1.39      albertel  128:         $current_course eq $env{'request.course.id'} &&
1.22      matthew   129:         %newExportrows) {
                    130:         &save_cached_export_rows($current_name,$current_domain);
                    131:     }
1.1       matthew   132:     undef(%Exportrows);
1.22      matthew   133:     undef(%newExportrows);
1.1       matthew   134:     undef($current_name);
                    135:     undef($current_domain);
                    136:     undef($current_course);
                    137:     undef(%useropt);
1.22      matthew   138:     undef(%userdata);
1.1       matthew   139:     undef(%courseopt);
1.37      matthew   140:     undef($navmap);
1.1       matthew   141: }
                    142: 
1.22      matthew   143: sub save_cached_export_rows {
                    144:     my ($sname,$sdomain) = @_;
                    145:     my $result = &Apache::lonnet::put
1.39      albertel  146:         ('nohist_calculatedsheets_'.$env{'request.course.id'},
1.22      matthew   147:          $newExportrows{$sname.':'.$sdomain},
                    148:          $sdomain,$sname);
                    149:     delete($newExportrows{$sname.':'.$sdomain});
                    150: }
                    151: 
1.11      matthew   152: sub initialize {
1.37      matthew   153:     my ($in_navmap) = @_;
1.11      matthew   154:     &clear_package();
1.37      matthew   155:     $navmap = $in_navmap;
                    156:     if (! defined($navmap)) {
                    157:         $navmap = Apache::lonnavmaps::navmap->new();
                    158:     }
                    159:     if (!defined($navmap)) {
                    160:         &Apache::lonnet::logthis('assesscalc:Can not open Coursemap');
                    161:     }
1.25      matthew   162:     &Apache::loncoursedata::clear_internal_caches();
1.11      matthew   163: }
                    164: 
1.1       matthew   165: ########################################################
                    166: ########################################################
                    167: 
                    168: =pod
                    169: 
                    170: =item &initialize_package()
                    171: 
                    172: =cut
                    173: 
                    174: ########################################################
                    175: ########################################################
                    176: sub initialize_package {
1.37      matthew   177:     my ($sname,$sdomain,$in_navmap) = @_;
1.1       matthew   178:     $current_name   = $sname;
                    179:     $current_domain = $sdomain;
1.37      matthew   180:     $navmap = $in_navmap;
1.21      matthew   181:     undef(%useropt);
1.22      matthew   182:     undef(%userdata);
1.39      albertel  183:     if ($current_course ne $env{'request.course.id'}) {
                    184:         $current_course = $env{'request.course.id'};
1.13      matthew   185:         undef(%courseopt);
                    186:     }
1.1       matthew   187:     &load_cached_export_rows();
                    188:     &load_parameter_caches();
1.25      matthew   189:     &Apache::loncoursedata::clear_internal_caches();
1.1       matthew   190: }
                    191: 
1.22      matthew   192: 
1.1       matthew   193: ########################################################
                    194: ########################################################
                    195: 
                    196: =pod
                    197: 
                    198: =item &load_parameter_caches()
                    199: 
                    200: =cut
                    201: 
                    202: ########################################################
                    203: ########################################################
                    204: sub load_parameter_caches {
                    205:     my $userprefix = $current_name.':'.$current_domain.'_';
                    206:     $userprefix =~ s/:/_/g;
                    207:     #
                    208:     # Course Parameters Cache
                    209:     if (! %courseopt) {
1.39      albertel  210:         $current_course = $env{'request.course.id'};
1.1       matthew   211:         undef(%courseopt);
                    212:         if (! defined($current_name) || ! defined($current_domain)) {
                    213:             return;
                    214:         }
1.39      albertel  215:         my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    216:         my $id  = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1       matthew   217:         my %Tmp = &Apache::lonnet::dump('resourcedata',$dom,$id);
                    218:         while (my ($name,$value) = each(%Tmp)) {
1.3       matthew   219:             $courseopt{$name}=$value;
1.1       matthew   220:         }
                    221:     }
                    222:     if (! %useropt) {
                    223:         my %Tmp = &Apache::lonnet::dump('resourcedata',
                    224:                                         $current_domain,$current_name);
                    225:         while (my ($name,$value) = each(%Tmp)) {
                    226:             if ($name =~ /^error: 2/ || $name =~ /no such file/) {
                    227:                 undef(%useropt);
                    228:                 last;
                    229:             }
                    230:             $useropt{$userprefix.$name}=$value;
                    231:         }
1.21      matthew   232:         $useropt{'loadtime'} = time;
1.1       matthew   233:     }
1.22      matthew   234:     if (! %userdata) {
                    235:         %userdata = &Apache::loncoursedata::get_current_state($current_name,
                    236:                                                               $current_domain);
                    237:         $userdata{'loadtime'} = time;
                    238:     }
                    239:     return;
1.1       matthew   240: }
                    241: 
                    242: ########################################################
                    243: ########################################################
                    244: 
                    245: =pod
                    246: 
                    247: =head2 assesscalc object methods
                    248: 
                    249: =cut
                    250: 
                    251: ########################################################
                    252: ########################################################
1.22      matthew   253: sub ensure_current_caches {
1.1       matthew   254:     my $self = shift;
1.19      matthew   255:     ##
                    256:     ## Check for a modified parameters
                    257:     ##
1.1       matthew   258:     if (! defined($current_course) || 
1.39      albertel  259:         $current_course ne $env{'request.course.id'} ) {
                    260:         $current_course = $env{'request.course.id'};
1.1       matthew   261:         undef(%courseopt); 
1.22      matthew   262:         undef(%useropt);
                    263:         undef(%userdata);
1.1       matthew   264:     }
1.19      matthew   265:     ##
                    266:     ## Check for new user
                    267:     ##
1.1       matthew   268:     if (! defined($current_name)   || $current_name ne $self->{'name'} ||
                    269:         ! defined($current_domain) || $current_domain ne $self->{'domain'}) {
                    270:         $current_domain = $self->{'domain'};
                    271:         $current_name   = $self->{'name'};
                    272:         undef(%useropt);
1.22      matthew   273:         undef(%userdata);
1.1       matthew   274:     }
                    275:     &load_parameter_caches();
                    276: }
                    277: 
                    278: ##################################################
                    279: ##################################################
                    280: 
                    281: =pod
                    282: 
                    283: =item &parmval()
                    284: 
                    285: Determine the value of a parameter.
                    286: 
                    287: Inputs: $what, the parameter needed, $symb, $uname, $udom, $csec 
                    288: 
                    289: Returns: The value of a parameter, or '' if none.
                    290: 
                    291: This function cascades through the possible levels searching for a value for
                    292: a parameter.  The levels are checked in the following order:
1.52    ! raeburn   293: user, course (at group, section level and course level), map, and 
        !           294: lonnet::metadata.
1.1       matthew   295: This function uses %parmhash, which must be tied prior to calling it.
                    296: This function also requires %courseopt and %useropt to be initialized for
                    297: this user and course.
                    298: 
                    299: =cut
                    300: 
                    301: ##################################################
                    302: ##################################################
                    303: sub parmval {
                    304:     my $self = shift;
1.52    ! raeburn   305:     my ($what,$symb,$uname,$udom,$csec,$recurse,$mapname,$id,$fn,$cgroup)=@_;
        !           306:     $uname  = $self->{'name'}    if (! defined($uname));
        !           307:     $udom   = $self->{'domain'}  if (! defined($udom));
        !           308:     $csec   = $self->{'section'} if (! defined($csec));
        !           309:     $cgroup = $self->{'group'}   if (! defined($cgroup)); 
        !           310:     $symb   = $self->{'symb'}    if (! defined($symb));
1.1       matthew   311:     #
                    312:     my $result='';
                    313:     #
                    314:     # This should be a 
1.44      albertel  315:     if (!defined($mapname) || !defined($id) || !defined($fn)) {
                    316: 	($mapname,$id,$fn)=&Apache::lonnet::decode_symb($symb);
                    317:     }
1.1       matthew   318:     # Cascading lookup scheme
                    319:     my $rwhat=$what;
                    320:     $what =~ s/^parameter\_//;
                    321:     $what =~ s/\_([^\_]+)$/\.$1/;
                    322:     #
                    323:     my $symbparm = $symb.'.'.$what;
                    324:     my $mapparm  = $mapname.'___(all).'.$what;
1.3       matthew   325:     my $courseprefix = $self->{'cid'};
1.1       matthew   326:     my $usercourseprefix = $uname.'_'.$udom.'_'.$self->{'cid'};
                    327:     #
1.52    ! raeburn   328:     my $grplevel=$courseprefix.'.['.$cgroup.'].'.$what;
        !           329:     my $grplevelr=$courseprefix.'.['.$cgroup.'].'.$symbparm;
        !           330:     my $grplevelm=$courseprefix.'.['.$cgroup.'].'.$mapparm;
        !           331:     #
1.3       matthew   332:     my $seclevel  = $courseprefix.'.['.$csec.'].'.$what;
                    333:     my $seclevelr = $courseprefix.'.['.$csec.'].'.$symbparm;
                    334:     my $seclevelm = $courseprefix.'.['.$csec.'].'.$mapparm;
                    335:     #
                    336:     my $courselevel  = $courseprefix.'.'.$what;
                    337:     my $courselevelr = $courseprefix.'.'.$symbparm;
                    338:     my $courselevelm = $courseprefix.'.'.$mapparm;
                    339:     #
                    340:     my $ucourselevel  = $usercourseprefix.'.'.$what;
                    341:     my $ucourselevelr = $usercourseprefix.'.'.$symbparm;
                    342:     my $ucourselevelm = $usercourseprefix.'.'.$mapparm;
1.52    ! raeburn   343:     # check user
1.1       matthew   344:     if (defined($uname)) {
1.3       matthew   345:         return $useropt{$ucourselevelr} if (defined($useropt{$ucourselevelr}));
                    346:         return $useropt{$ucourselevelm} if (defined($useropt{$ucourselevelm}));
                    347:         return $useropt{$ucourselevel}  if (defined($useropt{$ucourselevel}));
1.1       matthew   348:     }
1.52    ! raeburn   349:     # check group
        !           350:     if (defined($cgroup)) {
        !           351:         return $courseopt{$grplevelr} if (defined($courseopt{$grplevelr}));
        !           352:         return $courseopt{$grplevelm} if (defined($courseopt{$grplevelm}));
        !           353:         return $courseopt{$grplevel}  if (defined($courseopt{$grplevel}));
        !           354:     }
1.1       matthew   355:     # check section
                    356:     if (defined($csec)) {
                    357:         return $courseopt{$seclevelr} if (defined($courseopt{$seclevelr}));
                    358:         return $courseopt{$seclevelm} if (defined($courseopt{$seclevelm}));
                    359:         return $courseopt{$seclevel}  if (defined($courseopt{$seclevel}));
                    360:     }
                    361:     #
                    362:     # check course
                    363:     return $courseopt{$courselevelr} if (defined($courseopt{$courselevelr}));
                    364:     # check map parms
                    365:     my $thisparm = $parmhash{$symbparm};
                    366:     return $thisparm if (defined($thisparm));
                    367:     # check default
                    368:     $thisparm = &Apache::lonnet::metadata($fn,$rwhat.'.default');
                    369:     return $thisparm if (defined($thisparm));
1.36      albertel  370:     # check more course
                    371:     return $courseopt{$courselevelm} if (defined($courseopt{$courselevelm}));
                    372:     return $courseopt{$courselevel}  if (defined($courseopt{$courselevel}));
                    373: 
1.1       matthew   374:     # Cascade Up
                    375:     my $space=$what;
1.35      albertel  376:     $space=~s/\.[^._]+$//;
1.1       matthew   377:     if ($space ne '0') {
                    378: 	my @parts=split(/_/,$space);
                    379: 	my $id=pop(@parts);
                    380: 	my $part=join('_',@parts);
                    381: 	if ($part eq '') { $part='0'; }
                    382: 	my $newwhat=$rwhat;
                    383: 	$newwhat=~s/\Q$space\E/$part/;
1.44      albertel  384: 	my $partgeneral=$self->parmval($newwhat,$symb,$uname,$udom,$csec,1,
                    385: 				       $mapname,$id,$fn);
1.1       matthew   386: 	if (defined($partgeneral)) { return $partgeneral; }
                    387:     }
1.17      albertel  388:     if ($recurse) { return undef; }
                    389:     my $pack_def=&Apache::lonnet::packages_tab_default($fn,'resource.'.$what);
                    390:     if (defined($pack_def)) { return $pack_def; }
1.1       matthew   391:     #nothing defined
                    392:     return '';
                    393: }
                    394: 
1.8       matthew   395: sub get_html_title {
                    396:     my $self = shift;
1.29      matthew   397:     my ($assess_title,$name,$time) = $self->get_full_title();
1.8       matthew   398:     my $title = '<h1>'.$assess_title.'</h1>'.
                    399:         '<h2>'.$name.', '.
                    400:         &Apache::loncommon::aboutmewrapper
                    401:                          ($self->{'name'}.'@'.$self->{'domain'},
                    402:                           $self->{'name'},$self->{'domain'});
                    403:     $title .= '<h3>'.$time.'</h3>';
                    404:     return $title;
                    405: }
                    406: 
1.1       matthew   407: sub get_title {
                    408:     my $self = shift;
1.16      matthew   409:     if (($self->{'symb'} eq '_feedback') ||
                    410:         ($self->{'symb'} eq '_evaluation') ||
                    411:         ($self->{'symb'} eq '_discussion') ||
                    412:         ($self->{'symb'} eq '_tutoring')) {
                    413:         my $assess_title = ucfirst($self->{'symb'});
1.8       matthew   414:         $assess_title =~ s/^_//;
1.29      matthew   415:         return $assess_title;
1.1       matthew   416:     } else {
1.29      matthew   417:         return &Apache::lonnet::gettitle($self->{'symb'});
1.1       matthew   418:     }
1.29      matthew   419: }
                    420: 
                    421: sub get_full_title {
                    422:     my $self = shift;
                    423:     my @title = ($self->get_title());
1.2       matthew   424:     # Look up the users identifying information
                    425:     # Get the users information
1.34      albertel  426:     my $name = &Apache::loncommon::plainname($self->{'name'},
                    427: 					     $self->{'domain'});
1.8       matthew   428:     push (@title,$name);
1.26      www       429:     push (@title,&Apache::lonlocal::locallocaltime(time));
1.8       matthew   430:     return @title;
1.1       matthew   431: }
                    432: 
                    433: sub parent_link {
                    434:     my $self = shift;
                    435:     my $link .= '<p><a href="/adm/studentcalc?'.
                    436:         'sname='.$self->{'name'}.
                    437:             '&sdomain='.$self->{'domain'}.'">'.
1.26      www       438:                 &mt('Student level sheet').'</a></p>'."\n";
1.1       matthew   439:     return $link;
                    440: }
                    441: 
                    442: sub outsheet_html {
                    443:     my $self = shift;
                    444:     my ($r) = @_;
1.29      matthew   445:     ####################################
                    446:     # Report any calculation errors    #
                    447:     ####################################
                    448:     $r->print($self->html_report_error());
1.1       matthew   449:     ###################################
                    450:     # Determine table structure
                    451:     ###################################
1.14      matthew   452:     my $importcolor = '#FFFFFF';
1.15      matthew   453:     my $exportcolor = '#FFFFAA';
1.1       matthew   454:     my $num_uneditable = 1;
                    455:     my $num_left = 52-$num_uneditable;
1.26      www       456:     my %lt=&Apache::lonlocal::texthash(
                    457: 				       'as' => 'Assessment',
                    458: 				       'ca' => 'Calculations',
                    459: 				       );
1.1       matthew   460:     my $tableheader =<<"END";
                    461: <table border="2">
                    462: <tr>
1.26      www       463:   <th colspan="2" rowspan="2"><font size="+2">$lt{'as'}</font></th>
1.14      matthew   464:   <td bgcolor="$importcolor" colspan="$num_uneditable">&nbsp;</td>
1.1       matthew   465:   <td colspan="$num_left">
1.26      www       466:       <b><font size="+1">$lt{'ca'}</font></b></td>
1.1       matthew   467: </tr><tr>
                    468: END
                    469:     my $label_num = 0;
                    470:     foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
                    471:         if ($label_num<$num_uneditable) { 
1.14      matthew   472:             $tableheader .= '<td bgcolor="'.$importcolor.'">';
1.1       matthew   473:         } else {
                    474:             $tableheader .= '<td>';
                    475:         }
                    476:         $tableheader .= "<b><font size=+1>$_</font></b></td>";
                    477:         $label_num++;
                    478:     }
                    479:     $tableheader.="</tr>\n";
                    480:     #
                    481:     $r->print($tableheader);
                    482:     #
                    483:     # Print out template row
                    484:     $r->print('<tr><td>Template</td><td>&nbsp;</td>'.
1.14      matthew   485: 	      $self->html_template_row($num_uneditable,$importcolor).
                    486:               "</tr>\n");
1.1       matthew   487:     #
                    488:     # Print out summary/export row
                    489:     $r->print('<tr><td>Export</td><td>0</td>'.
1.14      matthew   490: 	      $self->html_export_row($exportcolor)."</tr>\n");
1.1       matthew   491:     #
                    492:     # Prepare to output rows
                    493:     $tableheader =<<"END";
                    494: <table border="2">
                    495: <tr><th>row</th><th>Item</th>
                    496: END
                    497:     foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
                    498: 	if ($label_num<$num_uneditable) { 
1.14      matthew   499:             $tableheader.='<th bgcolor="'.$importcolor.'">';
1.1       matthew   500:         } else {
                    501:             $tableheader.='<th>';
                    502:         }
                    503:         $tableheader.="<b><font size=+1>$_</font></b></th>";
                    504:     }
                    505:     #
                    506:     my $num_output = 0;
1.8       matthew   507:     foreach my $rownum (sort {$a <=> $b} ($self->rows())) {
1.28      matthew   508:         if (! $self->parameter_part_is_valid(
                    509:                                              $self->{'formulas'}->{'A'.$rownum}
                    510:                                              )) {
                    511:             next;
                    512:         }
1.1       matthew   513: 	if ($num_output++ % 50 == 0) {
                    514: 	    $r->print("</table>\n".$tableheader);
                    515: 	}
                    516: 	$r->print('<tr><td>'.$rownum.'</td>'.
1.14      matthew   517:                   $self->assess_html_row($rownum,$importcolor)."</tr>\n");
1.1       matthew   518:     }
                    519:     $r->print("</table>\n");
                    520:     return;
                    521: }
                    522: 
                    523: sub assess_html_row {
                    524:     my $self = shift();
1.14      matthew   525:     my ($row,$importcolor) = @_;
1.1       matthew   526:     my $parameter_name = $self->{'formulas'}->{'A'.$row};
                    527:     my @rowdata = $self->get_row($row);
                    528:     my $num_cols_output = 0;
                    529:     my $row_html;
1.48      albertel  530:     my $name=$self->get_parm_name($parameter_name);
                    531:     if ($name ne '') {
1.1       matthew   532:         $name =~ s/ /\&nbsp;/g;
                    533:         $row_html .= '<td>'.$name.'<br />'.$parameter_name.'</td>';
                    534:     } else {
                    535:         $row_html .= '<td>'.$parameter_name.'</td>';
                    536:     }
                    537:     foreach my $cell (@rowdata) {
1.10      matthew   538:         if ($num_cols_output < 1) {
1.14      matthew   539:             $row_html .= '<td bgcolor="'.$importcolor.'">';
1.10      matthew   540:             $row_html .= &Apache::Spreadsheet::html_uneditable_cell($cell,
                    541:                                                                     '#FFDDDD');
                    542:         } else {
                    543:             $row_html .= '<td bgcolor="#EOFFDD">';
                    544:             $row_html .= &Apache::Spreadsheet::html_editable_cell($cell,
                    545:                                                                   '#E0FFDD',1);
                    546:         }
1.1       matthew   547: 	$row_html .= '</td>';
1.10      matthew   548:         $num_cols_output++;
1.1       matthew   549:     }
                    550:     return $row_html;
                    551: }
                    552: 
1.9       matthew   553: sub csv_rows {
                    554:     # writes the meat of the spreadsheet to an excel worksheet.  Called
                    555:     # by Spreadsheet::outsheet_excel;
1.1       matthew   556:     my $self = shift;
1.30      matthew   557:     my ($connection,$filehandle) = @_;
1.9       matthew   558:     #
                    559:     # Write a header row
                    560:     $self->csv_output_row($filehandle,undef,
1.26      www       561:                           (&mt('Parameter'),&mt('Description'),&mt('Value')));
1.9       matthew   562:     #
                    563:     # Write each row
                    564:     foreach my $rownum (sort {$a <=> $b} ($self->rows())) {
                    565:         my $parameter_name = $self->{'formulas'}->{'A'.$rownum};
1.48      albertel  566:         my $description = $self->get_parm_name($parameter_name);
1.9       matthew   567:         $self->csv_output_row($filehandle,$rownum,
                    568:                               $parameter_name,$description);
                    569:     }
                    570:     return;
1.1       matthew   571: }
                    572: 
1.8       matthew   573: sub excel_rows {
                    574:     # writes the meat of the spreadsheet to an excel worksheet.  Called
                    575:     # by Spreadsheet::outsheet_excel;
1.1       matthew   576:     my $self = shift;
1.38      matthew   577:     my ($connection,$worksheet,$cols_output,$rows_output,$format) = @_;
1.30      matthew   578:     return if (! ref($worksheet));
1.8       matthew   579:     #
                    580:     # Write a header row
                    581:     $cols_output = 0;
                    582:     foreach my $value ('Parameter','Description','Value') {
1.38      matthew   583:         $worksheet->write($rows_output,$cols_output++,$value,$format->{'h4'});
1.8       matthew   584:     }
1.38      matthew   585:     $rows_output++;
1.8       matthew   586:     #
                    587:     # Write each row
                    588:     foreach my $rownum (sort {$a <=> $b} ($self->rows())) {
                    589:         my $parameter_name = $self->{'formulas'}->{'A'.$rownum};
1.48      albertel  590:         my $description = $self->get_parm_name($parameter_name);
1.8       matthew   591:         $self->excel_output_row($worksheet,$rownum,$rows_output++,
                    592:                                 $parameter_name,$description);
                    593:     }
                    594:     return;
1.1       matthew   595: }
                    596: 
1.21      matthew   597: ##
                    598: ## Routines to support assesscalc::compute
                    599: ##
1.48      albertel  600: sub get_parm {
1.21      matthew   601:     my $self = shift;
                    602:     my @Mandatory_parameters = @_;
1.48      albertel  603:     my %parameters;
1.21      matthew   604:     #
1.23      albertel  605:     my ($symap,$syid,$srcf) = &Apache::lonnet::decode_symb($self->{'symb'});
1.21      matthew   606:     my @Metadata = split(/\,/,&Apache::lonnet::metadata($srcf,'keys'));
                    607:     foreach my $parm (@Mandatory_parameters,@Metadata) {
                    608:         next if ($parm !~ /^(resource\.|stores|parameter)_/);
                    609:         my $cleaned_name = $parm;
                    610:         $cleaned_name =~ s/^resource\./stores_/;
                    611:         $cleaned_name =~ s/\./_/g;
1.48      albertel  612:         $parameters{$cleaned_name}=1;
                    613:     }
                    614:     return (keys(%parameters));
                    615: }
                    616: 
                    617: sub get_parm_name {
                    618:     my $self = shift;
                    619:     my $parm = shift;
                    620:     my ($symap,$syid,$srcf) = &Apache::lonnet::decode_symb($self->{'symb'});
                    621:     my $display = &Apache::lonnet::metadata($srcf,$parm.'.display');
                    622:     if (! $display) {
                    623: 	$display .= &Apache::lonnet::metadata($srcf,$parm.'.name');
1.21      matthew   624:     }
1.48      albertel  625:     return $display;
1.21      matthew   626: }
                    627: 
                    628: sub get_parameter_values {
                    629:     my $self = shift();
                    630:     my @Parameters;
                    631:     my ($parameters) = @_;
                    632:     if (!ref($parameters)) {
                    633:         @Parameters = @_;
                    634:     } elsif (ref($parameters) eq 'ARRAY') {
                    635:         @Parameters = @$parameters;
                    636:     } elsif (ref($parameters) eq 'HASH') {
                    637:         @Parameters = keys(%$parameters);
                    638:     }
                    639:     #
                    640:     my %parameters;
                    641:     #
                    642:     my $filename = $self->{'coursefilename'}.'_parms.db';
                    643:     if (tie(%parmhash,'GDBM_File',
                    644:             $self->{'coursefilename'}.'_parms.db',&GDBM_READER(),0640)) {
1.44      albertel  645: 	my ($mapname,$id,$fn)=&Apache::lonnet::decode_symb($self->{'symb'});
1.21      matthew   646:         foreach my $parmname (@Parameters) {
1.47      albertel  647:             my $value = $self->parmval($parmname,$self->{'symb'},
                    648: 				       $self->{'name'},$self->{'domain'},
                    649: 				       $self->{'section'},undef,
                    650: 				       $mapname,$id,$fn);
1.21      matthew   651:             $parameters{$parmname} =$value;
                    652:         }
                    653:         untie(%parmhash);
                    654:     } else {
                    655:         $self->logthis('unable to tie '.$filename);
                    656:     }
                    657:     return %parameters;
                    658: }
                    659: 
                    660: sub deal_with_export_row {
                    661:     my $self = shift();
                    662:     my @exportarray = @_;
                    663:     $Exportrows{$self->{'symb'}}->{'time'} = time;
                    664:     $Exportrows{$self->{'symb'}}->{$self->{'filename'}} = \@exportarray;
                    665:     #
                    666:     # Save the export data
                    667:     $self->save_export_data();
                    668:     return;
                    669: }
                    670: 
1.22      matthew   671: sub get_problem_state {
                    672:     my $self = shift;
                    673:     my %student_parameters;
                    674:     if (exists($userdata{$self->{'symb'}}) && 
                    675:         ref($userdata{$self->{'symb'}}) eq 'HASH') {
                    676:         %student_parameters = %{$userdata{$self->{'symb'}}};
                    677:     }
                    678:     return %student_parameters;
                    679: }
1.21      matthew   680: 
1.28      matthew   681: sub determine_parts {
                    682:     my $self = shift;
1.41      albertel  683:     my $check_hidden = shift;
1.28      matthew   684:     if (exists($self->{'Parts'}) && ref($self->{'Parts'}) eq 'HASH') {
                    685:         return;
                    686:     }
                    687:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($self->{'symb'});
                    688:     my $src = &Apache::lonnet::clutter($url);
                    689:     return if (! defined($src));
                    690:     my %Parts;
                    691:     my $metadata = &Apache::lonnet::metadata($src,'packages');
                    692:     foreach (split(',',$metadata)) {
                    693:         my ($part) = (/^part_(.*)$/);
1.41      albertel  694:         if (!defined($part)) { next; }
                    695:         if (!$check_hidden) { $Parts{$part}++; next; }
                    696:         if (!&Apache::loncommon::check_if_partid_hidden
                    697: 	    ($part,$self->{'symb'},$self->{'name'},$self->{'domain'})
1.28      matthew   698:             ) {
                    699:             $Parts{$part}++;
                    700:         }
                    701:     }
                    702:     # Make sure part 0 is defined.
                    703:     $Parts{'0'}++;
                    704:     $self->{'Parts'} = \%Parts;
                    705:     return;
                    706: }
                    707: 
                    708: sub parameter_part_is_valid {
                    709:     my $self = shift;
                    710:     my ($parameter) = @_;
                    711:     return 1 if ($parameter eq 'timestamp');
                    712:     if (! defined($self->{'Parts'}) || 
                    713:         ! ref ($self->{'Parts'})    ||
                    714:         ref($self->{'Parts'}) ne 'HASH') {
                    715:         return 1;
                    716:     }
                    717:     #
1.51      albertel  718:     my ($start,@pieces)=split('_',$parameter);
                    719:     if ( $start !~ m/^(resource|stores|parameter)$/) { return 0; }
                    720:     while (@pieces) {
                    721:         pop(@pieces);
                    722:         my $testpart=join('_',@pieces);
                    723: 	if (exists($self->{'Parts'}->{$testpart}) &&
                    724: 	    $self->{'Parts'}->{$testpart} ) {
                    725: 	    return 1;
                    726: 	}
1.28      matthew   727:     }
1.51      albertel  728:     return 0;
1.28      matthew   729: }
                    730: 
1.1       matthew   731: sub compute {
                    732:     my $self = shift;
1.19      matthew   733:     my ($r) = @_;
1.1       matthew   734:     $self->initialize_safe_space();
1.11      matthew   735:     #########################################
                    736:     #########################################
                    737:     ###                                   ###
                    738:     ###  Retrieve the problem parameters  ###
                    739:     ###                                   ###
                    740:     #########################################
                    741:     #########################################
                    742:     my @Mandatory_parameters = ("stores_0_solved",
                    743:                                 "stores_0_awarddetail",
                    744:                                 "stores_0_awarded",
                    745:                                 "timestamp",
                    746:                                 "stores_0_tries",
                    747:                                 "stores_0_award");
1.1       matthew   748:     #
                    749:     # Definitions
                    750:     undef(%nice_parameter_name);
                    751:     my %parameters;   # holds underscored parameters by name
                    752:     #
                    753:     # Get the metadata fields and determine their proper names
1.48      albertel  754:     my @parameters=$self->get_parm(@Mandatory_parameters);
1.1       matthew   755:     #
                    756:     # Get the values of the metadata fields
1.22      matthew   757:     $self->ensure_current_caches();
1.48      albertel  758:     %parameters = $self->get_parameter_values(@parameters);
1.1       matthew   759:     #
                    760:     # Clean out unnecessary parameters
                    761:     foreach (keys(%parameters)) {
                    762:         delete($parameters{$_}) if (! /(resource\.|stores_|parameter_)/);
                    763:     }
                    764:     #
                    765:     # Get the students performance data
1.43      albertel  766:     $self->determine_parts(($parameters{'parameter_0_hiddenparts'} ne ''));
1.22      matthew   767:     my %student_parameters = $self->get_problem_state();
1.1       matthew   768:     while (my ($parm,$value) = each(%student_parameters)) {
                    769:         $parm =~ s/^resource\./stores_/;
                    770:         $parm =~ s/\./_/g;
1.41      albertel  771: 	# Clean out any bad parameters
                    772: 	next if (! $self->parameter_part_is_valid($parm));
                    773: 	$parameters{$parm} = $value;
1.1       matthew   774:     }
                    775:     #
                    776:     # Set up the formulas and parameter values
                    777:     my %f=$self->formulas();
                    778:     my %c;
                    779:     #
1.5       matthew   780:     # Check for blackout requirements
1.39      albertel  781:     if ((!exists($env{'request.role.adv'}) || !$env{'request.role.adv'})) {
1.5       matthew   782:         while (my ($parm,$value) = each(%parameters)) {
                    783:             last if ($self->blackout());
                    784:             next if ($parm !~ /^(parameter_.*)_problemstatus$/);
1.24      matthew   785:             if ($parameters{$1.'_answerdate'} ne '' &&
1.21      matthew   786:                 $parameters{$1.'_answerdate'} < time) {
                    787:                 next;
                    788:             }
1.5       matthew   789:             if (lc($value) eq 'no') {
                    790:                 # We must blackout this sheet
                    791:                 $self->blackout(1);
                    792:             }
                    793:         }
                    794:     }
                    795:     #
                    796:     # Move the parameters into the spreadsheet
1.1       matthew   797:     while (my ($parm,$value) = each(%parameters)) {
                    798:         my $cell = 'A'.$self->get_row_number_from_key($parm);
                    799:         $f{$cell} = $parm;
1.31      matthew   800:         if ($parm =~ /_submission$/ && $value =~ /(\{|\})/) {
                    801:             $value = 'witheld';
                    802:         }
1.49      albertel  803:         $value = 'q{'.$value.'}' if ($value =~/([^\d\.]|\.\.)/);
1.6       matthew   804:         $c{$parm} = $value;
1.1       matthew   805:     }
1.50      albertel  806:     foreach my $cell (grep(/^A/,keys(%f))) {
                    807:         # Clean out any bad formulas
                    808: 	next if (exists($c{$f{$cell}}));
                    809: 	next if ($cell eq 'A0');
                    810: 	delete($f{$cell});
                    811:     }
1.6       matthew   812:     $self->formulas(\%f);
                    813:     $self->constants(\%c);
1.1       matthew   814:     $self->calcsheet();
                    815:     #
                    816:     # Store export row in cache
                    817:     my @exportarray = $self->exportrow();
1.21      matthew   818:     $self->deal_with_export_row(@exportarray);
1.12      matthew   819:     $self->save() if ($self->need_to_save());
1.1       matthew   820:     return;
                    821: }
                    822: 
                    823: ##
                    824: ## sett overrides Spreadsheet::sett
                    825: ##
                    826: sub sett {
                    827:     my $self = shift;
                    828:     my %t=();
1.40      albertel  829:     undef(%Apache::Spreadsheet::sheet_values);
1.1       matthew   830:     #
                    831:     # Deal with the template row by copying the template formulas into each
                    832:     # row.
                    833:     foreach my $col ($self->template_cells()) {
                    834:         next if ($col=~/^A/);
                    835:         foreach my $row ($self->rows()) {
                    836:             # Get the name of this cell
                    837:             my $cell=$col.$row;
                    838:             # Grab the template declaration
                    839:             $t{$cell}=$self->formula('template_'.$col);
                    840:             # Replace '#' with the row number
                    841:             $t{$cell}=~s/\#/$row/g;
                    842:             # Replace '....' with ','
                    843:             $t{$cell}=~s/\.\.+/\,/g;
                    844:             # Replace 'A0' with the value from 'A0'
                    845:             $t{$cell}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
                    846:             # Replace parameters
                    847:             $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
                    848:         }
                    849:     }
                    850:     #
                    851:     # Deal with the cells which have formulas
                    852:     while (my ($cell,$formula) = each(%{$self->{'formulas'}})) {
                    853: 	next if ($cell =~ /template_/);
                    854:         if ($cell =~ /^A/ && $cell ne 'A0') {
1.45      albertel  855: 	    if ($formula !~ /^\!/ 
                    856: 		&& exists($self->{'constants'}->{$formula}) 
                    857: 		&& $self->{'constants'}->{$formula} ne ''
                    858: 		) {
1.40      albertel  859: 		$Apache::Spreadsheet::sheet_values{$cell}=
1.49      albertel  860: 		    eval($self->{'constants'}->{$formula});
1.1       matthew   861:             }
                    862:         } else {
                    863:             $t{$cell}=$formula;
                    864:             $t{$cell}=~s/\.\.+/\,/g;
                    865:             $t{$cell}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
                    866:             $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
                    867:         }
                    868:     }
                    869:     # Put %t into the safe space
                    870:     %{$self->{'safe'}->varglob('t')}=%t;
                    871: }
                    872: 
                    873: 
                    874: ########################################################
                    875: ########################################################
                    876: 
                    877: =pod
                    878: 
                    879: =item &load_cached_export_rows()
                    880: 
                    881: Retrieves and parsers the export rows of the assessment spreadsheets.
                    882: These rows are saved in the students directory in the format:
                    883: 
                    884:  sname:sdom:assesscalc:symb.time => time
                    885: 
                    886:  sname:sdom:assesscalc:symb => filename___=___Adata___;___Bdata___;___ ...
                    887: 
                    888: =cut
                    889: 
                    890: ########################################################
                    891: ########################################################
                    892: sub load_cached_export_rows {
1.18      matthew   893:     undef(%Exportrows);
1.1       matthew   894:     my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets_'.
1.39      albertel  895:                                     $env{'request.course.id'},
1.1       matthew   896:                                     $current_domain,$current_name,undef);
                    897:     if ($tmp[0]!~/^error/) {
                    898:         my %tmp = @tmp;
1.39      albertel  899:         my $default_filename =  $env{'course.'.$env{'request.course.id'}.
1.1       matthew   900:                                          '.spreadsheet_default_assesscalc'};
                    901:         # We only got one key, so we will access it directly.
                    902:         while (my ($key,$sheetdata) = each(%tmp)) {
                    903:             my ($sname,$sdom,$sheettype,$symb) = split(':',$key);
1.33      matthew   904:             if (! defined($sname) || $sname eq '' ||
                    905:                 ! defined($sdom)  || $sdom eq '' ) {
                    906:                 next;
                    907:             }
1.1       matthew   908:             if ($symb =~ /\.time$/) {
                    909:                 $symb =~ s/\.time$//;
                    910:                 $Exportrows{$symb}->{'time'} = $sheetdata;
                    911:             } else {
                    912:                 $sheetdata =~ s/^(.*)___=___//;
                    913:                 my $filename = $1;
                    914:                 $filename = $default_filename if (! defined($filename));
                    915:                 my @Data = split('___;___',$sheetdata);
                    916:                 $Exportrows{$symb}->{$filename} = \@Data;
                    917:             }
                    918:         }
                    919:     }
                    920: }
                    921: 
                    922: #############################################
                    923: #############################################
                    924: 
                    925: =pod
                    926: 
                    927: =item &export_data
                    928: 
                    929: Returns the export data associated with the spreadsheet.  Computes the
                    930: spreadsheet only if necessary.
                    931: 
                    932: =cut
                    933: 
                    934: #############################################
                    935: #############################################
                    936: sub export_data {
                    937:     my $self = shift;
1.19      matthew   938:     my ($r) = @_;
1.1       matthew   939:     my $symb = $self->{'symb'};
1.39      albertel  940:     if (! exists($env{'request.role.adv'}) || ! $env{'request.role.adv'} ||
1.5       matthew   941:         ! exists($Exportrows{$symb}) || ! defined($Exportrows{$symb})  ||
1.1       matthew   942:         ! $self->check_expiration_time($Exportrows{$symb}->{'time'}) ||
                    943:         ! exists($Exportrows{$symb}->{$self->{'filename'}}) ||
1.18      matthew   944:         ! defined($Exportrows{$symb}->{$self->{'filename'}}) ||
                    945:         ! ref($Exportrows{$symb}->{$self->{'filename'}}) 
                    946:         ) {
1.19      matthew   947:         $self->compute($r);
1.1       matthew   948:     }
1.29      matthew   949:     my @Data;
                    950:     if ($self->badcalc()) {
                    951:         @Data = ();
                    952:     } else {
                    953:         @Data = @{$Exportrows{$symb}->{$self->{'filename'}}};
                    954:         if ($Data[0] =~ /^(.*)___=___/) {
                    955:             $self->{'sheetname'} = $1;
                    956:             $Data[0] =~ s/^(.*)___=___//;
                    957:         }
                    958:         for (my $i=0;$i<$#Data;$i++) {
                    959:             if ($Data[$i]=~/\D/ && defined($Data[$i])) {
                    960:                 $Data[$i]="'".$Data[$i]."'";
                    961:             }
                    962:         }
1.1       matthew   963:     }
                    964:     return @Data;
                    965: }
                    966: 
                    967: #############################################
                    968: #############################################
                    969: 
                    970: =pod
                    971: 
                    972: =item &save_export_data()
                    973: 
                    974: Writes the export data for this spreadsheet to the students cache.
                    975: 
                    976: =cut
                    977: 
                    978: #############################################
                    979: #############################################
                    980: sub save_export_data {
                    981:     my $self = shift;
1.7       matthew   982:     return if ($self->temporary());
1.1       matthew   983:     my $student = $self->{'name'}.':'.$self->{'domain'};
                    984:     my $symb    = $self->{'symb'};
1.29      matthew   985:     if ($self->badcalc()){
                    986:         # do not save data away when calculations have not been done properly.
                    987:         delete($Exportrows{$symb});
                    988:         return;
                    989:     }
1.1       matthew   990:     if (! exists($Exportrows{$symb}) || 
                    991:         ! exists($Exportrows{$symb}->{$self->{'filename'}})) {
                    992:         return;
                    993:     }
                    994:     my $key = join(':',($self->{'name'},$self->{'domain'},'assesscalc',$symb));
                    995:     my $timekey = $key.'.time';
1.22      matthew   996:     my $newstore= join('___;___',
                    997:                        map {s/[^[:print:]]//g;$_;} # strip out unprintable
                    998:                                 @{$Exportrows{$symb}->{$self->{'filename'}}});
1.1       matthew   999:     $newstore = $self->{'filename'}.'___=___'.$newstore;
1.22      matthew  1000:     $newExportrows{$student}->{$key} = $newstore;
                   1001:     $newExportrows{$student}->{$timekey} = $Exportrows{$symb}->{'time'};
1.1       matthew  1002:     return;
                   1003: }
                   1004: 
                   1005: 1;
                   1006: 
                   1007: __END__

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