File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.177: download - view: text, annotated - select for diffs
Tue Mar 11 15:00:47 2003 UTC (21 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- silly typo

    1: #
    2: # $Id: lonspreadsheet.pm,v 1.177 2003/03/11 15:00:47 albertel Exp $
    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: lonspreadsheet
   34: 
   35: =head1 SYNOPSIS
   36: 
   37: Spreadsheet interface to internal LON-CAPA data
   38: 
   39: =head1 DESCRIPTION
   40: 
   41: Lonspreadsheet provides course coordinators the ability to manage their
   42: students grades online.  The students are able to view their own grades, but
   43: not the grades of their peers.  The spreadsheet is highly customizable,
   44: offering the ability to use Perl code to manipulate data, as well as many
   45: built-in functions.
   46: 
   47: =head2 Functions available to user of lonspreadsheet
   48: 
   49: =over 4
   50: 
   51: =cut
   52: 
   53: 
   54: package Apache::lonspreadsheet;
   55:             
   56: use strict;
   57: use Apache::Constants qw(:common :http);
   58: use Apache::lonnet;
   59: use Apache::lonhtmlcommon;
   60: use HTML::Entities();
   61: 
   62: # --------------------------------------------------------- Various form fields
   63: 
   64: sub textfield {
   65:     my ($title,$name,$value)=@_;
   66:     return "\n<p><b>$title:</b><br>".
   67:         '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
   68: }
   69: 
   70: sub hiddenfield {
   71:     my ($name,$value)=@_;
   72:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
   73: }
   74: 
   75: sub selectbox {
   76:     my ($title,$name,$value,%options)=@_;
   77:     my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
   78:     foreach (sort keys(%options)) {
   79:         $selout.='<option value="'.$_.'"';
   80:         if ($_ eq $value) { $selout.=' selected'; }
   81:         $selout.='>'.$options{$_}.'</option>';
   82:     }
   83:     return $selout.'</select>';
   84: }
   85: 
   86: my %oldsheets;
   87: my %loadedcaches;
   88: 
   89: # ================================================================ Main handler
   90: #
   91: # Interactive call to screen
   92: #
   93: #
   94: sub handler {
   95:     my $r=shift;
   96: 
   97:     my ($sheettype) = ($r->uri=~/\/(\w+)$/);
   98: 
   99:     if (! exists($ENV{'form.Status'})) {
  100:         $ENV{'form.Status'} = 'Active';
  101:     }
  102:     if ( ! exists($ENV{'form.output'}) || 
  103:              ($sheettype ne 'classcalc' && 
  104:               lc($ENV{'form.output'}) eq 'recursive excel')) {
  105:         $ENV{'form.output'} = 'HTML';
  106:     }
  107:     #
  108:     # Overload checking
  109:     #
  110:     # Check this server
  111:     my $loaderror=&Apache::lonnet::overloaderror($r);
  112:     if ($loaderror) { return $loaderror; }
  113:     # Check the course homeserver
  114:     $loaderror= &Apache::lonnet::overloaderror($r,
  115:                       $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
  116:     if ($loaderror) { return $loaderror; } 
  117:     #
  118:     # HTML Header
  119:     #
  120:     if ($r->header_only) {
  121:         $r->content_type('text/html');
  122:         $r->send_http_header;
  123:         return OK;
  124:     }
  125:     #
  126:     # Roles Checking
  127:     #
  128:     # Needs to be in a course
  129:     if (! $ENV{'request.course.fn'}) { 
  130:         # Not in a course, or not allowed to modify parms
  131:         $ENV{'user.error.msg'}=
  132:             $r->uri.":opa:0:0:Cannot modify spreadsheet";
  133:         return HTTP_NOT_ACCEPTABLE; 
  134:     }
  135:     #
  136:     # Get query string for limited number of parameters
  137:     #
  138:     &Apache::loncommon::get_unprocessed_cgi
  139:         ($ENV{'QUERY_STRING'},['uname','udom','usymb','ufn','mapid','resid']);
  140:     #
  141:     # Deal with restricted student permissions 
  142:     #
  143:     if ($ENV{'request.role'} =~ /^st\./) {
  144:         delete $ENV{'form.unewfield'}   if (exists($ENV{'form.unewfield'}));
  145:         delete $ENV{'form.unewformula'} if (exists($ENV{'form.unewformula'}));
  146:     }
  147:     #
  148:     # Look for special assessment spreadsheets - '_feedback', etc.
  149:     #
  150:     if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'} || 
  151:                                              $ENV{'form.ufn'} eq '' || 
  152:                                              $ENV{'form.ufn'} eq 'default')) {
  153:         $ENV{'form.ufn'}='default_'.$1;
  154:     }
  155:     if (!$ENV{'form.ufn'} || $ENV{'form.ufn'} eq 'default') {
  156:         $ENV{'form.ufn'}='course_default_'.$sheettype;
  157:     }
  158:     #
  159:     # Interactive loading of specific sheet?
  160:     #
  161:     if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
  162:         $ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
  163:     }
  164:     #
  165:     # Determine the user name and domain for the sheet.
  166:     my $aname;
  167:     my $adom;
  168:     unless ($ENV{'form.uname'}) {
  169:         $aname=$ENV{'user.name'};
  170:         $adom=$ENV{'user.domain'};
  171:     } else {
  172:         $aname=$ENV{'form.uname'};
  173:         $adom=$ENV{'form.udom'};
  174:     }
  175:     #
  176:     # Open page, try to prevent browser cache.
  177:     #
  178:     $r->content_type('text/html');
  179:     $r->header_out('Cache-control','no-cache');
  180:     $r->header_out('Pragma','no-cache');
  181:     $r->send_http_header;
  182:     #
  183:     # Header....
  184:     #
  185:     $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
  186:     my $nothing = &Apache::lonhtmlcommon::javascript_nothing();
  187: 
  188:     if ($ENV{'request.role'} !~ /^st\./) {
  189:         $r->print(<<ENDSCRIPT);
  190: <script language="JavaScript">
  191: 
  192:     var editwin;
  193: 
  194:     function celledit(cellname,cellformula) {
  195:         var edit_text = '';
  196:         // cellformula may contain less-than and greater-than symbols, so
  197:         // we need to escape them?  
  198:         edit_text +='<html><head><title>Cell Edit Window</title></head><body>';
  199:         edit_text += '<form name="editwinform">';
  200:         edit_text += '<center><h3>Cell '+cellname+'</h3>';
  201:         edit_text += '<textarea name="newformula" cols="40" rows="6"';
  202:         edit_text += ' wrap="off" >'+cellformula+'</textarea>';
  203:         edit_text += '</br>';
  204:         edit_text += '<input type="button" name="accept" value="Accept"';
  205:         edit_text += ' onClick=\\\'javascript:';
  206:         edit_text += 'opener.document.sheet.unewfield.value=';
  207:         edit_text +=     '"'+cellname+'";';
  208:         edit_text += 'opener.document.sheet.unewformula.value=';
  209:         edit_text +=     'document.editwinform.newformula.value;';
  210:         edit_text += 'opener.document.sheet.submit();';
  211:         edit_text += 'self.close()\\\' />';
  212:         edit_text += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  213:         edit_text += '<input type="button" name="abort" ';
  214:         edit_text +=     'value="Discard Changes"';
  215:         edit_text += ' onClick="javascript:self.close()" />';
  216:         edit_text += '</center></body></html>';
  217: 
  218:         if (editwin != null && !(editwin.closed) ) {
  219:             editwin.close();
  220:         }
  221: 
  222:         editwin = window.open($nothing,'CellEditWin','height=200,width=350,scrollbars=no,resizeable=yes,alwaysRaised=yes,dependent=yes',true);
  223:         editwin.document.write(edit_text);
  224:     }
  225: 
  226:     function changesheet(cn) {
  227: 	document.sheet.unewfield.value=cn;
  228:         document.sheet.unewformula.value='changesheet';
  229:         document.sheet.submit();
  230:     }
  231: 
  232:     function insertrow(cn) {
  233: 	document.sheet.unewfield.value='insertrow';
  234:         document.sheet.unewformula.value=cn;
  235:         document.sheet.submit();
  236:     }
  237: 
  238: </script>
  239: ENDSCRIPT
  240:     }
  241:     $r->print('</head>'.&Apache::loncommon::bodytag('Grades Spreadsheet').
  242:               '<form action="'.$r->uri.'" name="sheet" method="post">');
  243:     $r->print(&hiddenfield('uname',$ENV{'form.uname'}).
  244:               &hiddenfield('udom',$ENV{'form.udom'}).
  245:               &hiddenfield('usymb',$ENV{'form.usymb'}).
  246:               &hiddenfield('unewfield','').
  247:               &hiddenfield('unewformula',''));
  248:     $r->rflush();
  249:     #
  250:     # Full recalc?
  251:     #
  252:     # Read new sheet or modified worksheet
  253:     my $sheet=Apache::lonspreadsheet::Spreadsheet->new($aname,$adom,$sheettype,$ENV{'form.usymb'});
  254:     if ($ENV{'form.forcerecalc'}) {
  255:         $r->print('<h4>Completely Recalculating Sheet ...</h4>');
  256:         $sheet->complete_recalc();
  257:     }
  258:     #
  259:     # Global directory configs
  260:     #
  261:     $sheet->includedir($r->dir_config('lonIncludes'));
  262:     #
  263:     # Check user permissions
  264:     if (($sheet->{'type'}  eq 'classcalc'       ) || 
  265:         ($sheet->{'uname'} ne $ENV{'user.name'} ) ||
  266:         ($sheet->{'udom'}  ne $ENV{'user.domain'})) {
  267:         unless (&Apache::lonnet::allowed('vgr',$sheet->{'cid'})) {
  268:             $r->print('<h1>Access Permission Denied</h1>'.
  269:                       '</form></body></html>');
  270:             return OK;
  271:         }
  272:     }
  273:     # Print out user information
  274:     $r->print('<h2>'.$sheet->{'coursedesc'}.'</h2>');
  275:     if ($sheet->{'type'} ne 'classcalc') {
  276:         $r->print('<h2>'.$sheet->gettitle().'</h2><p>');
  277:     }
  278:     if ($sheet->{'type'} eq 'assesscalc') {
  279:         $r->print('<b>User:</b> '.$sheet->{'uname'}.
  280:                   '<br /><b>Domain:</b> '.$sheet->{'udom'}.'<br />');
  281:     }
  282:     if ($sheet->{'type'} eq 'studentcalc' || 
  283:         $sheet->{'type'} eq 'assesscalc') {
  284:         $r->print('<b>Section/Group:</b>'.$sheet->{'csec'}.'</p>');
  285:     } 
  286:     #
  287:     # If a new formula had been entered, go from work copy
  288:     if ($ENV{'form.unewfield'}) {
  289:         $r->print('<h2>Modified Workcopy</h2>');
  290:         #$ENV{'form.unewformula'}=~s/\'/\"/g;
  291:         $r->print('<p>Cell '.$ENV{'form.unewfield'}.' = <pre>');
  292:         $r->print(&HTML::Entities::encode($ENV{'form.unewformula'}).
  293:                   '</pre></p>');
  294:         $sheet->{'filename'} = $ENV{'form.ufn'};
  295:         $sheet->tmpread($ENV{'form.unewfield'},$ENV{'form.unewformula'});
  296:     } elsif ($ENV{'form.saveas'}) {
  297:         $sheet->{'filename'} = $ENV{'form.ufn'};
  298:         $sheet->tmpread();
  299:     } else {
  300:         $sheet->readsheet($ENV{'form.ufn'});
  301:     }
  302:     # Additional options
  303:     if ($sheet->{'type'} eq 'assesscalc') {
  304:         $r->print('<p><font size=+2>'.
  305:                   '<a href="/adm/studentcalc?'.
  306:                   'uname='.$sheet->{'uname'}.
  307:                   '&udom='.$sheet->{'udom'}.'">'.
  308:                   'Level up: Student Sheet</a></font></p>');
  309:     }
  310:     if (($sheet->{'type'} eq 'studentcalc') && 
  311:         (&Apache::lonnet::allowed('vgr',$sheet->{'cid'}))) {
  312:         $r->print ('<p><font size=+2><a href="/adm/classcalc">'.
  313:                    'Level up: Course Sheet</a></font></p>');
  314:     }
  315:     # Recalc button
  316:     $r->print('<br />'.
  317:               '<input type="submit" name="forcerecalc" '.
  318:               'value="Completely Recalculate Sheet"></p>');
  319:     # Save dialog
  320:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
  321:         my $fname=$ENV{'form.ufn'};
  322:         $fname=~s/\_[^\_]+$//;
  323:         if ($fname eq 'default') { $fname='course_default'; }
  324:         $r->print('<input type=submit name=saveas value="Save as ...">'.
  325:                   '<input type=text size=20 name=newfn value="'.$fname.'">'.
  326:                   'make default: <input type=checkbox name="makedefufn"><p>');
  327:     }
  328:     $r->print(&hiddenfield('ufn',$sheet->{'filename'}));
  329:     # Load dialog
  330:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
  331:         $r->print('<p><input type=submit name=load value="Load ...">'.
  332:                   '<select name="loadthissheet">'.
  333:                   '<option name="default">Default</option>');
  334:         foreach ($sheet->othersheets()) {
  335:             $r->print('<option name="'.$_.'"');
  336:             if ($ENV{'form.ufn'} eq $_) {
  337:                 $r->print(' selected');
  338:             }
  339:             $r->print('>'.$_.'</option>');
  340:         } 
  341:         $r->print('</select><p>');
  342:         if ($sheet->{'type'} eq 'studentcalc') {
  343:             $sheet->setothersheets($sheet->othersheets('assesscalc'));
  344:         }
  345:     }
  346:     #
  347:     # Set up caching mechanisms
  348:     #
  349:     &Apache::lonspreadsheet::Spreadsheet::load_spreadsheet_expirationdates();
  350:     # Clear out old caches if we have not seen this class before.
  351:     if (exists($oldsheets{'course'}) &&
  352:         $oldsheets{'course'} ne $sheet->{'cid'}) {
  353:         undef %oldsheets;
  354:         undef %loadedcaches;
  355:     }
  356:     $oldsheets{'course'} = $sheet->{'cid'};
  357:     #
  358:     if ($sheet->{'type'} eq 'classcalc') {
  359:         $r->print("Loading previously calculated student sheets ...\n");
  360:         $r->rflush();
  361:         &Apache::lonspreadsheet::Spreadsheet::cachedcsheets();
  362:     } elsif ($sheet->{'type'} eq 'studentcalc') {
  363:         $r->print("Loading previously calculated assessment sheets ...\n");
  364:         $r->rflush();
  365:         $sheet->cachedssheets();
  366:     }
  367:     # Update sheet, load rows
  368:     $r->print("Loaded sheet(s), updating rows ...<br>\n");
  369:     $r->rflush();
  370:     #
  371:     $sheet->updatesheet();
  372:     $r->print("Updated rows, loading row data ...\n");
  373:     $r->rflush();
  374:     #
  375:     $sheet->loadrows($r);
  376:     $r->print("Loaded row data, calculating sheet ...<br>\n");
  377:     $r->rflush();
  378:     #
  379:     my $calcoutput=$sheet->calcsheet();
  380:     $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
  381:     # See if something to save
  382:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
  383:         my $fname='';
  384:         if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
  385:             $fname=~s/\W/\_/g;
  386:             if ($fname eq 'default') { $fname='course_default'; }
  387:             $fname.='_'.$sheet->{'type'};
  388:             $sheet->{'filename'} = $fname;
  389:             $ENV{'form.ufn'}=$fname;
  390:             $r->print('<p>Saving spreadsheet: '.
  391:                       $sheet->writesheet($ENV{'form.makedefufn'}).
  392:                       '<p>');
  393:         }
  394:     }
  395:     #
  396:     # Write the modified worksheet
  397:     $r->print('<b>Current sheet:</b> '.$sheet->{'filename'}.'</p>');
  398:     $sheet->tmpwrite();
  399:     if ($sheet->{'type'} eq 'assesscalc') {
  400:         $r->print('<p>Show rows with empty A column: ');
  401:     } else {
  402:         $r->print('<p>Show empty rows: ');
  403:     }
  404:     #
  405:     $r->print(&hiddenfield('userselhidden','true').
  406:               '<input type="checkbox" name="showall" onClick="submit()"');
  407:     #
  408:     if ($ENV{'form.showall'}) { 
  409:         $r->print(' checked'); 
  410:     } else {
  411:         unless ($ENV{'form.userselhidden'}) {
  412:             unless 
  413:                 ($ENV{'course.'.$sheet->{'cid'}.'.hideemptyrows'} eq 'yes') {
  414:                     $r->print(' checked');
  415:                     $ENV{'form.showall'}=1;
  416:                 }
  417:         }
  418:     }
  419:     $r->print('>');
  420:     #
  421:     # output format select box 
  422:     $r->print(' Output as <select name="output" size="1" onChange="submit()">'.
  423:               "\n");
  424:     foreach my $mode (qw/HTML CSV Excel/) {
  425:         $r->print('<option value="'.$mode.'"');
  426:         if ($ENV{'form.output'} eq $mode) {
  427:             $r->print(' selected ');
  428:         } 
  429:         $r->print('>'.$mode.'</option>'."\n");
  430:     }
  431: #
  432: #    Mulit-sheet excel takes too long and does not work at all for large
  433: #    classes.  Future inclusion of this option may be possible with the
  434: #    Spreadsheet::WriteExcel::Big and speed improvements.
  435: #
  436: #    if ($sheet->{'type'} eq 'classcalc') {
  437: #        $r->print('<option value="recursive excel"');
  438: #        if ($ENV{'form.output'} eq 'recursive excel') {
  439: #            $r->print(' selected ');
  440: #        } 
  441: #        $r->print(">Multi-Sheet Excel</option>\n");
  442: #    }
  443:     $r->print("</select>\n");
  444:     #
  445:     if ($sheet->{'type'} eq 'classcalc') {
  446:         $r->print('&nbsp;Student Status: '.
  447:                   &Apache::lonhtmlcommon::StatusOptions
  448:                   ($ENV{'form.Status'},'sheet'));
  449:     }
  450:     #
  451:     # Buttons to insert rows
  452: #    $r->print(<<ENDINSERTBUTTONS);
  453: #<br>
  454: #<input type='button' onClick='insertrow("top");' 
  455: #value='Insert Row Top'>
  456: #<input type='button' onClick='insertrow("bottom");' 
  457: #value='Insert Row Bottom'><br>
  458: #ENDINSERTBUTTONS
  459:     # Print out sheet
  460:     $sheet->outsheet($r);
  461:     $r->print('</form></body></html>');
  462:     #  Done
  463:     return OK;
  464: }
  465: 
  466: 1;
  467: 
  468: #############################################################
  469: #############################################################
  470: #############################################################
  471: 
  472: package Apache::lonspreadsheet::Spreadsheet;
  473:             
  474: use strict;
  475: use Apache::Constants qw(:common :http);
  476: use Apache::lonnet;
  477: use Apache::loncoursedata;
  478: use Apache::File();
  479: use Safe;
  480: use Safe::Hole;
  481: use Opcode;
  482: use GDBM_File;
  483: use HTML::Entities();
  484: use HTML::TokeParser;
  485: use Spreadsheet::WriteExcel;
  486: use Time::HiRes;
  487: 
  488: #
  489: # These global hashes are dependent on user, course and resource, 
  490: # and need to be initialized every time when a sheet is calculated
  491: #
  492: my %courseopt;
  493: my %useropt;
  494: my %parmhash;
  495: 
  496: #
  497: # Caches for coursewide information 
  498: #
  499: my %Section;
  500: 
  501: #
  502: # Caches for previously calculated spreadsheets
  503: #
  504: my %expiredates;
  505: 
  506: #
  507: # Cache for stores of an individual user
  508: #
  509: my $cachedassess;
  510: my %cachedstores;
  511: 
  512: #
  513: # Some hashes for stats on timing and performance
  514: #
  515: my %starttimes;
  516: my %usedtimes;
  517: my %numbertimes;
  518: 
  519: #
  520: # Directories
  521: #
  522: my $includedir;
  523: 
  524: sub includedir {
  525:     my $self = shift;
  526:     $includedir = shift;
  527: }
  528: 
  529: my %spreadsheets;
  530: #my %loadedcaches;
  531: my %courserdatas;
  532: my %userrdatas;
  533: my %defaultsheets;
  534: my %rowlabel_cache;
  535: #my %oldsheets;
  536: 
  537: sub complete_recalc {
  538:     my $self = shift;
  539:     undef %spreadsheets;
  540:     undef %courserdatas;
  541:     undef %userrdatas;
  542:     undef %defaultsheets;
  543:     undef %rowlabel_cache;
  544: }
  545: 
  546: sub get_sheet {
  547:     my $self = shift;
  548:     my $sheet_id = shift;
  549:     my $formulas;
  550:     # if we already have the file loaded and parsed, return the formulas
  551:     if (exists($self->{'sheets'}->{$sheet_id})) {
  552:         $formulas = $self->{'sheets'}->{$sheet_id};
  553:         $self->debug('retrieved '.$sheet_id);
  554:     } else {
  555:         # load the file
  556:         #     set $error and return undef if there is an error loading
  557:         # parse it
  558:         #     set $error and return undef if there is an error parsing
  559:     }
  560:     return $formulas;
  561: }
  562: 
  563: #
  564: # Load previously cached student spreadsheets for this course
  565: #
  566: sub load_spreadsheet_expirationdates {
  567:     undef %expiredates;
  568:     my $cid=$ENV{'request.course.id'};
  569:     my @tmp = &Apache::lonnet::dump('nohist_expirationdates',
  570:                                     $ENV{'course.'.$cid.'.domain'},
  571:                                     $ENV{'course.'.$cid.'.num'});
  572:     if (lc($tmp[0]) !~ /^error/){
  573:         %expiredates = @tmp;
  574:     }
  575: }
  576: 
  577: # ===================================================== Calculated sheets cache
  578: #
  579: # Load previously cached student spreadsheets for this course
  580: #
  581: sub cachedcsheets {
  582:     my $cid=$ENV{'request.course.id'};
  583:     my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets',
  584:                                     $ENV{'course.'.$cid.'.domain'},
  585:                                     $ENV{'course.'.$cid.'.num'});
  586:     if ($tmp[0] !~ /^error/) {
  587:         my %StupidTempHash = @tmp;
  588:         while (my ($key,$value) = each %StupidTempHash) {
  589:             $Apache::lonspreadsheet::oldsheets{$key} = $value;
  590:         }
  591:     }
  592: }
  593: 
  594: #
  595: # Load previously cached assessment spreadsheets for this student
  596: #
  597: sub cachedssheets {
  598:     my $self = shift;
  599:     my ($uname,$udom) = @_;
  600:     $uname = $uname || $self->{'uname'};
  601:     $udom  = $udom  || $self->{'udom'};
  602:     if (! exists($Apache::lonspreadsheet::loadedcaches{$uname.'_'.$udom})) {
  603:         my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets_'.
  604:                                         $ENV{'request.course.id'},
  605:                                         $self->{'udom'},
  606:                                         $self->{'uname'});
  607:         if ($tmp[0] !~ /^error/) {
  608:             my %TempHash = @tmp;
  609:             my $count = 0;
  610:             while (my ($key,$value) = each %TempHash) {
  611:                 $Apache::lonspreadsheet::oldsheets{$key} = $value;
  612:                 $count++;
  613:             }
  614:             $Apache::lonspreadsheet::loadedcaches{$self->{'uname'}.'_'.$self->{'udom'}}=1;
  615:         }
  616:     }    
  617: }
  618: 
  619: # ======================================================= Forced recalculation?
  620: sub checkthis {
  621:     my ($keyname,$time)=@_;
  622:     if (! exists($expiredates{$keyname})) {
  623:         return 0;
  624:     } else {
  625:         return ($time<$expiredates{$keyname});
  626:     }
  627: }
  628: 
  629: sub forcedrecalc {
  630:     my ($uname,$udom,$stype,$usymb)=@_;
  631:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
  632:     my $time=$Apache::lonspreadsheet::oldsheets{$key.'.time'};
  633:     if ($ENV{'form.forcerecalc'}) { return 1; }
  634:     unless ($time) { return 1; }
  635:     if ($stype eq 'assesscalc') {
  636:         my $map=(split(/___/,$usymb))[0];
  637:         if (&checkthis('::assesscalc:',$time) ||
  638:             &checkthis('::assesscalc:'.$map,$time) ||
  639:             &checkthis('::assesscalc:'.$usymb,$time) ||
  640:             &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
  641:             &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
  642:             &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
  643:             return 1;
  644:         }
  645:     } else {
  646:         if (&checkthis('::studentcalc:',$time) || 
  647:             &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
  648: 	    return 1;
  649:         }
  650:     }
  651:     return 0; 
  652: }
  653: 
  654: 
  655: ##################################################
  656: ##################################################
  657: 
  658: =pod
  659: 
  660: =item &parmval()
  661: 
  662: Determine the value of a parameter.
  663: 
  664: Inputs: $what, the parameter needed, $symb, $uname, $udom, $csec 
  665: 
  666: Returns: The value of a parameter, or '' if none.
  667: 
  668: This function cascades through the possible levels searching for a value for
  669: a parameter.  The levels are checked in the following order:
  670: user, course (at section level and course level), map, and lonnet::metadata.
  671: This function uses %parmhash, which must be tied prior to calling it.
  672: This function also requires %courseopt and %useropt to be initialized for
  673: this user and course.
  674: 
  675: =cut
  676: 
  677: ##################################################
  678: ##################################################
  679: sub parmval {
  680:     my ($what,$symb,$uname,$udom,$csec)=@_;
  681:     return '' if (!$symb);
  682:     #
  683:     my $cid   = $ENV{'request.course.id'};
  684:     my $result='';
  685:     #
  686:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
  687:     # Cascading lookup scheme
  688:     my $rwhat=$what;
  689:     $what =~ s/^parameter\_//;
  690:     $what =~ s/\_([^\_]+)$/\.$1/;
  691:     #
  692:     my $symbparm = $symb.'.'.$what;
  693:     my $mapparm  = $mapname.'___(all).'.$what;
  694:     my $usercourseprefix = $uname.'_'.$udom.'_'.$cid;
  695:     #
  696:     my $seclevel  = $usercourseprefix.'.['.$csec.'].'.$what;
  697:     my $seclevelr = $usercourseprefix.'.['.$csec.'].'.$symbparm;
  698:     my $seclevelm = $usercourseprefix.'.['.$csec.'].'.$mapparm;
  699:     #
  700:     my $courselevel  = $usercourseprefix.'.'.$what;
  701:     my $courselevelr = $usercourseprefix.'.'.$symbparm;
  702:     my $courselevelm = $usercourseprefix.'.'.$mapparm;
  703:     # fourth, check user
  704:     if (defined($uname)) {
  705:         return $useropt{$courselevelr} if (defined($useropt{$courselevelr}));
  706:         return $useropt{$courselevelm} if (defined($useropt{$courselevelm}));
  707:         return $useropt{$courselevel}  if (defined($useropt{$courselevel}));
  708:     }
  709:     # third, check course
  710:     if (defined($csec)) {
  711:         return $courseopt{$seclevelr} if (defined($courseopt{$seclevelr}));
  712:         return $courseopt{$seclevelm} if (defined($courseopt{$seclevelm}));
  713:         return $courseopt{$seclevel}  if (defined($courseopt{$seclevel}));
  714:     }
  715:     #
  716:     return $courseopt{$courselevelr} if (defined($courseopt{$courselevelr}));
  717:     return $courseopt{$courselevelm} if (defined($courseopt{$courselevelm}));
  718:     return $courseopt{$courselevel}  if (defined($courseopt{$courselevel}));
  719:     # second, check map parms
  720:     my $thisparm = $parmhash{$symbparm};
  721:     return $thisparm if (defined($thisparm));
  722: 
  723:     # first, check default
  724:     $thisparm = &Apache::lonnet::metadata($fn,$rwhat.'.default');
  725:     return $thisparm if (defined($thisparm));
  726: 
  727:     #Cascade Up
  728:     my $space=$what;
  729:     $space=~s/\.\w+$//;
  730:     if ($space ne '0') {
  731: 	my @parts=split(/_/,$space);
  732: 	my $id=pop(@parts);
  733: 	my $part=join('_',@parts);
  734: 	if ($part eq '') { $part='0'; }
  735: 	my $newwhat=$rwhat;
  736: 	$newwhat=~s/\Q$space\E/$part/;
  737: 	my $partgeneral=&parmval($newwhat,$symb,$uname,$udom,$csec);
  738: 	if (defined($partgeneral)) { return $partgeneral; }
  739:     }
  740: 
  741:     #nothing defined
  742:     return '';
  743: }
  744: 
  745: #
  746: # new: Make a new spreadsheet
  747: #
  748: sub new {
  749:     my $this = shift;
  750:     my $class = ref($this) || $this;
  751:     #
  752:     my ($uname,$udom,$stype,$usymb)=@_;
  753:     #
  754:     my $self = {
  755:         uname => $uname,
  756:         udom  => $udom,
  757:         type  => $stype,
  758:         usymb => $usymb,
  759:         errorlog => '',
  760:         maxrow   => '',
  761:         mapid => $ENV{'form.mapid'},
  762:         resid => $ENV{'form.resid'},
  763:         cid   => $ENV{'request.course.id'},
  764:         csec  => $Section{$uname.':'.$udom},
  765:         cnum  => $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
  766:         cdom  => $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  767:         chome => $ENV{'course.'.$ENV{'request.course.id'}.'.home'},
  768:         coursefilename => $ENV{'request.course.fn'},
  769:         coursedesc => $ENV{'course.'.$ENV{'request.course.id'}.'.description'},
  770:         rows       => [],
  771:         template_cells => [],
  772:         };
  773:     $self->{'uhome'} = &Apache::lonnet::homeserver($uname,$udom);
  774:     #
  775:     #
  776:     $self->{'formulas'} = {};
  777:     $self->{'constants'} = {};
  778:     $self->{'othersheets'} = [];
  779:     $self->{'rowlabel'} = {};
  780:     #
  781:     #
  782:     $self->{'safe'} = &initsheet($self->{'type'});
  783:     $self->{'root'} = $self->{'safe'}->root();
  784:     #
  785:     # Place some of the %$self  items into the safe space except the safe space
  786:     # itself
  787:     my $initstring = '';
  788:     foreach (qw/uname udom type usymb cid csec coursefilename
  789:              cnum cdom chome uhome/) {
  790:         $initstring.= qq{\$$_="$self->{$_}";};
  791:     }
  792:     $self->{'safe'}->reval($initstring);
  793:     bless($self,$class);
  794:     return $self;
  795: }
  796: 
  797: ##
  798: ## mask - used to reside in the safe space.  
  799: ##
  800: {
  801: 
  802: my %memoizer;
  803: 
  804: sub mask {
  805:     my ($lower,$upper)=@_;
  806:     my $key = $lower.'_'.$upper;
  807:     if (exists($memoizer{$key})) {
  808:         return $memoizer{$key};
  809:     }
  810:     $upper = $lower if (! defined($upper));
  811:     #
  812:     my ($la,$ld) = ($lower=~/([A-Za-z]|\*)(\d+|\*)/);
  813:     my ($ua,$ud) = ($upper=~/([A-Za-z]|\*)(\d+|\*)/);
  814:     #
  815:     my $alpha='';
  816:     my $num='';
  817:     #
  818:     if (($la eq '*') || ($ua eq '*')) {
  819:         $alpha='[A-Za-z]';
  820:     } else {
  821:        if (($la=~/[A-Z]/) && ($ua=~/[A-Z]/) ||
  822:            ($la=~/[a-z]/) && ($ua=~/[a-z]/)) {
  823:           $alpha='['.$la.'-'.$ua.']';
  824:        } else {
  825:           $alpha='['.$la.'-Za-'.$ua.']';
  826:        }
  827:     }   
  828:     if (($ld eq '*') || ($ud eq '*')) {
  829: 	$num='\d+';
  830:     } else {
  831:         if (length($ld)!=length($ud)) {
  832:            $num.='(';
  833: 	   foreach ($ld=~m/\d/g) {
  834:               $num.='['.$_.'-9]';
  835: 	   }
  836:            if (length($ud)-length($ld)>1) {
  837:               $num.='|\d{'.(length($ld)+1).','.(length($ud)-1).'}';
  838: 	   }
  839:            $num.='|';
  840:            foreach ($ud=~m/\d/g) {
  841:                $num.='[0-'.$_.']';
  842:            }
  843:            $num.=')';
  844:        } else {
  845:            my @lda=($ld=~m/\d/g);
  846:            my @uda=($ud=~m/\d/g);
  847:            my $i; 
  848:            my $j=0; 
  849:            my $notdone=1;
  850:            for ($i=0;($i<=$#lda)&&($notdone);$i++) {
  851:                if ($lda[$i]==$uda[$i]) {
  852: 		   $num.=$lda[$i];
  853:                    $j=$i;
  854:                } else {
  855:                    $notdone=0;
  856:                }
  857:            }
  858:            if ($j<$#lda-1) {
  859: 	       $num.='('.$lda[$j+1];
  860:                for ($i=$j+2;$i<=$#lda;$i++) {
  861:                    $num.='['.$lda[$i].'-9]';
  862:                }
  863:                if ($uda[$j+1]-$lda[$j+1]>1) {
  864: 		   $num.='|['.($lda[$j+1]+1).'-'.($uda[$j+1]-1).']\d{'.
  865:                    ($#lda-$j-1).'}';
  866:                }
  867: 	       $num.='|'.$uda[$j+1];
  868:                for ($i=$j+2;$i<=$#uda;$i++) {
  869:                    $num.='[0-'.$uda[$i].']';
  870:                }
  871:                $num.=')';
  872:            } else {
  873:                if ($lda[-1]!=$uda[-1]) {
  874:                   $num.='['.$lda[-1].'-'.$uda[-1].']';
  875: 	       }
  876:            }
  877:        }
  878:     }
  879:     my $expression ='^'.$alpha.$num."\$";
  880:     $memoizer{$key} = $expression;
  881:     return $expression;
  882: }
  883: 
  884: }
  885: 
  886: sub add_hash_to_safe {
  887:     my $self = shift;
  888:     my $code = <<'END';
  889: #-------------------------------------------------------
  890: 
  891: =item UWCALC(hashname,modules,units,date) 
  892: 
  893: returns the proportion of the module 
  894: weights not previously completed by the student.
  895: 
  896: =over 4
  897: 
  898: =item hashname 
  899: 
  900: name of the hash the module dates have been inserted into
  901: 
  902: =item modules 
  903: 
  904: reference to a cell which contains a comma deliminated list of modules 
  905: covered by the assignment.
  906: 
  907: =item units 
  908: 
  909: reference to a cell which contains a comma deliminated list of module 
  910: weights with respect to the assignment
  911: 
  912: =item date 
  913: 
  914: reference to a cell which contains the date the assignment was completed.
  915: 
  916: =back 
  917: 
  918: =cut
  919: 
  920: #-------------------------------------------------------
  921: sub UWCALC {
  922:     my ($hashname,$modules,$units,$date) = @_;
  923:     my @Modules = split(/,/,$modules);
  924:     my @Units   = split(/,/,$units);
  925:     my $total_weight;
  926:     foreach (@Units) {
  927: 	$total_weight += $_;
  928:     }
  929:     my $usum=0;
  930:     for (my $i=0; $i<=$#Modules; $i++) {
  931: 	if (&HASH($hashname,$Modules[$i]) eq $date) {
  932: 	    $usum += $Units[$i];
  933: 	}
  934:     }
  935:     return $usum/$total_weight;
  936: }
  937: 
  938: #-------------------------------------------------------
  939: 
  940: =item CDLSUM(list) 
  941: 
  942: returns the sum of the elements in a cell which contains
  943: a Comma Deliminate List of numerical values.
  944: 'list' is a reference to a cell which contains a comma deliminated list.
  945: 
  946: =cut
  947: 
  948: #-------------------------------------------------------
  949: sub CDLSUM {
  950:     my ($list)=@_;
  951:     my $sum;
  952:     foreach (split/,/,$list) {
  953: 	$sum += $_;
  954:     }
  955:     return $sum;
  956: }
  957: 
  958: #-------------------------------------------------------
  959: 
  960: =item CDLITEM(list,index) 
  961: 
  962: returns the item at 'index' in a Comma Deliminated List.
  963: 
  964: =over 4
  965: 
  966: =item list
  967: 
  968: reference to a cell which contains a comma deliminated list.
  969: 
  970: =item index 
  971: 
  972: the Perl index of the item requested (first element in list has
  973: an index of 0) 
  974: 
  975: =back
  976: 
  977: =cut
  978: 
  979: #-------------------------------------------------------
  980: sub CDLITEM {
  981:     my ($list,$index)=@_;
  982:     my @Temp = split/,/,$list;
  983:     return $Temp[$index];
  984: }
  985: 
  986: #-------------------------------------------------------
  987: 
  988: =item CDLHASH(name,key,value) 
  989: 
  990: loads a comma deliminated list of keys into
  991: the hash 'name', all with a value of 'value'.
  992: 
  993: =over 4
  994: 
  995: =item name  
  996: 
  997: name of the hash.
  998: 
  999: =item key
 1000: 
 1001: (a pointer to) a comma deliminated list of keys.
 1002: 
 1003: =item value
 1004: 
 1005: a single value to be entered for each key.
 1006: 
 1007: =back
 1008: 
 1009: =cut
 1010: 
 1011: #-------------------------------------------------------
 1012: sub CDLHASH {
 1013:     my ($name,$key,$value)=@_;
 1014:     my @Keys;
 1015:     my @Values;
 1016:     # Check to see if we have multiple $key values
 1017:     if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
 1018: 	my $keymask = &mask($key);
 1019: 	# Assume the keys are addresses
 1020: 	my @Temp = grep /$keymask/,keys(%sheet_values);
 1021: 	@Keys = $sheet_values{@Temp};
 1022:     } else {
 1023: 	$Keys[0]= $key;
 1024:     }
 1025:     my @Temp;
 1026:     foreach $key (@Keys) {
 1027: 	@Temp = (@Temp, split/,/,$key);
 1028:     }
 1029:     @Keys = @Temp;
 1030:     if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
 1031: 	my $valmask = &mask($value);
 1032: 	my @Temp = grep /$valmask/,keys(%sheet_values);
 1033: 	@Values =$sheet_values{@Temp};
 1034:     } else {
 1035: 	$Values[0]= $value;
 1036:     }
 1037:     $value = $Values[0];
 1038:     # Add values to hash
 1039:     for (my $i = 0; $i<=$#Keys; $i++) {
 1040: 	my $key   = $Keys[$i];
 1041: 	if (! exists ($hashes{$name}->{$key})) {
 1042: 	    $hashes{$name}->{$key}->[0]=$value;
 1043: 	} else {
 1044: 	    my @Temp = sort(@{$hashes{$name}->{$key}},$value);
 1045: 	    $hashes{$name}->{$key} = \@Temp;
 1046: 	}
 1047:     }
 1048:     return "hash '$name' updated";
 1049: }
 1050: 
 1051: #-------------------------------------------------------
 1052: 
 1053: =item GETHASH(name,key,index) 
 1054: 
 1055: returns the element in hash 'name' 
 1056: reference by the key 'key', at index 'index' in the values list.
 1057: 
 1058: =cut
 1059: 
 1060: #-------------------------------------------------------
 1061: sub GETHASH {
 1062:     my ($name,$key,$index)=@_;
 1063:     if (! defined($index)) {
 1064: 	$index = 0;
 1065:     }
 1066:     if ($key =~ /^[A-z]\d+$/) {
 1067: 	$key = $sheet_values{$key};
 1068:     }
 1069:     return $hashes{$name}->{$key}->[$index];
 1070: }
 1071: 
 1072: #-------------------------------------------------------
 1073: 
 1074: =item CLEARHASH(name) 
 1075: 
 1076: clears all the values from the hash 'name'
 1077: 
 1078: =item CLEARHASH(name,key) 
 1079: 
 1080: clears all the values from the hash 'name' associated with the given key.
 1081: 
 1082: =cut
 1083: 
 1084: #-------------------------------------------------------
 1085: sub CLEARHASH {
 1086:     my ($name,$key)=@_;
 1087:     if (defined($key)) {
 1088: 	if (exists($hashes{$name}->{$key})) {
 1089: 	    $hashes{$name}->{$key}=undef;
 1090: 	    return "hash '$name' key '$key' cleared";
 1091: 	}
 1092:     } else {
 1093: 	if (exists($hashes{$name})) {
 1094: 	    $hashes{$name}=undef;
 1095: 	    return "hash '$name' cleared";
 1096: 	}
 1097:     }
 1098:     return "Error in clearing hash";
 1099: }
 1100: 
 1101: #-------------------------------------------------------
 1102: 
 1103: =item HASH(name,key,value) 
 1104: 
 1105: loads values into an internal hash.  If a key 
 1106: already has a value associated with it, the values are sorted numerically.  
 1107: 
 1108: =item HASH(name,key) 
 1109: 
 1110: returns the 0th value in the hash 'name' associated with 'key'.
 1111: 
 1112: =cut
 1113: 
 1114: #-------------------------------------------------------
 1115: sub HASH {
 1116:     my ($name,$key,$value)=@_;
 1117:     my @Keys;
 1118:     undef @Keys;
 1119:     my @Values;
 1120:     # Check to see if we have multiple $key values
 1121:     if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
 1122: 	my $keymask = &mask($key);
 1123: 	# Assume the keys are addresses
 1124: 	my @Temp = grep /$keymask/,keys(%sheet_values);
 1125: 	@Keys = $sheet_values{@Temp};
 1126:     } else {
 1127: 	$Keys[0]= $key;
 1128:     }
 1129:     # If $value is empty, return the first value associated 
 1130:     # with the first key.
 1131:     if (! $value) {
 1132: 	return $hashes{$name}->{$Keys[0]}->[0];
 1133:     }
 1134:     # Check to see if we have multiple $value(s) 
 1135:     if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
 1136: 	my $valmask = &mask($value);
 1137: 	my @Temp = grep /$valmask/,keys(%sheet_values);
 1138: 	@Values =$sheet_values{@Temp};
 1139:     } else {
 1140: 	$Values[0]= $value;
 1141:     }
 1142:     # Add values to hash
 1143:     for (my $i = 0; $i<=$#Keys; $i++) {
 1144: 	my $key   = $Keys[$i];
 1145: 	my $value = ($i<=$#Values ? $Values[$i] : $Values[0]);
 1146: 	if (! exists ($hashes{$name}->{$key})) {
 1147: 	    $hashes{$name}->{$key}->[0]=$value;
 1148: 	} else {
 1149: 	    my @Temp = sort(@{$hashes{$name}->{$key}},$value);
 1150: 	    $hashes{$name}->{$key} = \@Temp;
 1151: 	}
 1152:     }
 1153:     return $Values[-1];
 1154: }
 1155: END
 1156:     $self->{'safe'}->reval($code);
 1157:     return;
 1158: }
 1159: 
 1160: sub initsheet {
 1161:     my $safeeval = new Safe(shift);
 1162:     my $safehole = new Safe::Hole;
 1163:     $safeeval->permit("entereval");
 1164:     $safeeval->permit(":base_math");
 1165:     $safeeval->permit("sort");
 1166:     $safeeval->deny(":base_io");
 1167:     $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
 1168:     $safehole->wrap(\&mask,$safeeval,'&mask');
 1169:     $safeeval->share('$@');
 1170:     my $code=<<'ENDDEFS';
 1171: # ---------------------------------------------------- Inside of the safe space
 1172: #
 1173: # f: formulas
 1174: # t: intermediate format (variable references expanded)
 1175: # v: output values
 1176: # c: preloaded constants (A-column)
 1177: # rl: row label
 1178: # os: other spreadsheets (for student spreadsheet only)
 1179: 
 1180: undef %sheet_values;   # Holds the (computed, final) values for the sheet
 1181:     # This is only written to by &calc, the spreadsheet computation routine.
 1182:     # It is read by many functions
 1183: undef %t; # Holds the values of the spreadsheet temporarily. Set in &sett, 
 1184:     # which does the translation of strings like C5 into the value in C5.
 1185:     # Used in &calc - %t holds the values that are actually eval'd.
 1186: undef %f;    # Holds the formulas for each cell.  This is the users
 1187:     # (spreadsheet authors) data for each cell.
 1188: undef %c; # Holds the constants for a sheet.  In the assessment
 1189:     # sheets, this is the A column.  Used in &MINPARM, &MAXPARM, &expandnamed,
 1190:     # &sett, and &constants.  There is no &getconstants.
 1191:     # &constants is called by &loadstudent, &loadcourse, &load assessment,
 1192: undef @os;  # Holds the names of other spreadsheets - this is used to specify
 1193:     # the spreadsheets that are available for the assessment sheet.
 1194:     # Set by &setothersheets.  &setothersheets is called by &handler.  A
 1195:     # related subroutine is &othersheets.
 1196: $errorlog = '';
 1197: 
 1198: $maxrow = 0;
 1199: $type = '';
 1200: 
 1201: # filename/reference of the sheet
 1202: $filename = '';
 1203: 
 1204: # user data
 1205: $uname = '';
 1206: $uhome = '';
 1207: $udom  = '';
 1208: 
 1209: # course data
 1210: 
 1211: $csec = '';
 1212: $chome= '';
 1213: $cnum = '';
 1214: $cdom = '';
 1215: $cid  = '';
 1216: $coursefilename  = '';
 1217: 
 1218: # symb
 1219: 
 1220: $usymb = '';
 1221: 
 1222: # error messages
 1223: $errormsg = '';
 1224: 
 1225: #-------------------------------------------------------
 1226: 
 1227: =item NUM(range)
 1228: 
 1229: returns the number of items in the range.
 1230: 
 1231: =cut
 1232: 
 1233: #-------------------------------------------------------
 1234: sub NUM {
 1235:     my $mask=&mask(@_);
 1236:     my $num= $#{@{grep(/$mask/,keys(%sheet_values))}}+1;
 1237:     return $num;   
 1238: }
 1239: 
 1240: sub BIN {
 1241:     my ($low,$high,$lower,$upper)=@_;
 1242:     my $mask=&mask($lower,$upper);
 1243:     my $num=0;
 1244:     foreach (grep /$mask/,keys(%sheet_values)) {
 1245:         if (($sheet_values{$_}>=$low) && ($sheet_values{$_}<=$high)) {
 1246:             $num++;
 1247:         }
 1248:     }
 1249:     return $num;   
 1250: }
 1251: 
 1252: 
 1253: #-------------------------------------------------------
 1254: 
 1255: =item SUM(range)
 1256: 
 1257: returns the sum of items in the range.
 1258: 
 1259: =cut
 1260: 
 1261: #-------------------------------------------------------
 1262: sub SUM {
 1263:     my $mask=&mask(@_);
 1264:     my $sum=0;
 1265:     foreach (grep /$mask/,keys(%sheet_values)) {
 1266:         $sum+=$sheet_values{$_};
 1267:     }
 1268:     return $sum;   
 1269: }
 1270: 
 1271: #-------------------------------------------------------
 1272: 
 1273: =item MEAN(range)
 1274: 
 1275: compute the average of the items in the range.
 1276: 
 1277: =cut
 1278: 
 1279: #-------------------------------------------------------
 1280: sub MEAN {
 1281:     my $mask=&mask(@_);
 1282: #    $errorlog.='(mask = '.$mask.' )';
 1283:     my $sum=0; 
 1284:     my $num=0;
 1285:     foreach (grep /$mask/,keys(%sheet_values)) {
 1286:         $sum+=$sheet_values{$_};
 1287:         $num++;
 1288:     }
 1289:     if ($num) {
 1290:        return $sum/$num;
 1291:     } else {
 1292:        return undef;
 1293:     }   
 1294: }
 1295: 
 1296: #-------------------------------------------------------
 1297: 
 1298: =item STDDEV(range)
 1299: 
 1300: compute the standard deviation of the items in the range.
 1301: 
 1302: =cut
 1303: 
 1304: #-------------------------------------------------------
 1305: sub STDDEV {
 1306:     my $mask=&mask(@_);
 1307: #    $errorlog.='(mask = '.$mask.' )';
 1308:     my $sum=0; my $num=0;
 1309:     foreach (grep /$mask/,keys(%sheet_values)) {
 1310:         $sum+=$sheet_values{$_};
 1311:         $num++;
 1312:     }
 1313:     unless ($num>1) { return undef; }
 1314:     my $mean=$sum/$num;
 1315:     $sum=0;
 1316:     foreach (grep /$mask/,keys(%sheet_values)) {
 1317:         $sum+=($sheet_values{$_}-$mean)**2;
 1318:     }
 1319:     return sqrt($sum/($num-1));    
 1320: }
 1321: 
 1322: #-------------------------------------------------------
 1323: 
 1324: =item PROD(range)
 1325: 
 1326: compute the product of the items in the range.
 1327: 
 1328: =cut
 1329: 
 1330: #-------------------------------------------------------
 1331: sub PROD {
 1332:     my $mask=&mask(@_);
 1333:     my $prod=1;
 1334:     foreach (grep /$mask/,keys(%sheet_values)) {
 1335:         $prod*=$sheet_values{$_};
 1336:     }
 1337:     return $prod;   
 1338: }
 1339: 
 1340: #-------------------------------------------------------
 1341: 
 1342: =item MAX(range)
 1343: 
 1344: compute the maximum of the items in the range.
 1345: 
 1346: =cut
 1347: 
 1348: #-------------------------------------------------------
 1349: sub MAX {
 1350:     my $mask=&mask(@_);
 1351:     my $max='-';
 1352:     foreach (grep /$mask/,keys(%sheet_values)) {
 1353:         unless ($max) { $max=$sheet_values{$_}; }
 1354:         if (($sheet_values{$_}>$max) || ($max eq '-')) { $max=$sheet_values{$_}; }
 1355:     } 
 1356:     return $max;   
 1357: }
 1358: 
 1359: #-------------------------------------------------------
 1360: 
 1361: =item MIN(range)
 1362: 
 1363: compute the minimum of the items in the range.
 1364: 
 1365: =cut
 1366: 
 1367: #-------------------------------------------------------
 1368: sub MIN {
 1369:     my $mask=&mask(@_);
 1370:     my $min='-';
 1371:     foreach (grep /$mask/,keys(%sheet_values)) {
 1372:         unless ($max) { $max=$sheet_values{$_}; }
 1373:         if (($sheet_values{$_}<$min) || ($min eq '-')) { 
 1374:             $min=$sheet_values{$_}; 
 1375:         }
 1376:     }
 1377:     return $min;   
 1378: }
 1379: 
 1380: #-------------------------------------------------------
 1381: 
 1382: =item SUMMAX(num,lower,upper)
 1383: 
 1384: compute the sum of the largest 'num' items in the range from
 1385: 'lower' to 'upper'
 1386: 
 1387: =cut
 1388: 
 1389: #-------------------------------------------------------
 1390: sub SUMMAX {
 1391:     my ($num,$lower,$upper)=@_;
 1392:     my $mask=&mask($lower,$upper);
 1393:     my @inside=();
 1394:     foreach (grep /$mask/,keys(%sheet_values)) {
 1395: 	push (@inside,$sheet_values{$_});
 1396:     }
 1397:     @inside=sort(@inside);
 1398:     my $sum=0; my $i;
 1399:     for ($i=$#inside;(($i>$#inside-$num) && ($i>=0));$i--) { 
 1400:         $sum+=$inside[$i];
 1401:     }
 1402:     return $sum;   
 1403: }
 1404: 
 1405: #-------------------------------------------------------
 1406: 
 1407: =item SUMMIN(num,lower,upper)
 1408: 
 1409: compute the sum of the smallest 'num' items in the range from
 1410: 'lower' to 'upper'
 1411: 
 1412: =cut
 1413: 
 1414: #-------------------------------------------------------
 1415: sub SUMMIN {
 1416:     my ($num,$lower,$upper)=@_;
 1417:     my $mask=&mask($lower,$upper);
 1418:     my @inside=();
 1419:     foreach (grep /$mask/,keys(%sheet_values)) {
 1420: 	$inside[$#inside+1]=$sheet_values{$_};
 1421:     }
 1422:     @inside=sort(@inside);
 1423:     my $sum=0; my $i;
 1424:     for ($i=0;(($i<$num) && ($i<=$#inside));$i++) { 
 1425:         $sum+=$inside[$i];
 1426:     }
 1427:     return $sum;   
 1428: }
 1429: 
 1430: #-------------------------------------------------------
 1431: 
 1432: =item MINPARM(parametername)
 1433: 
 1434: Returns the minimum value of the parameters matching the parametername.
 1435: parametername should be a string such as 'duedate'.
 1436: 
 1437: =cut
 1438: 
 1439: #-------------------------------------------------------
 1440: sub MINPARM {
 1441:     my ($expression) = @_;
 1442:     my $min = undef;
 1443:     study($expression);
 1444:     foreach $parameter (keys(%c)) {
 1445:         next if ($parameter !~ /$expression/);
 1446:         if ((! defined($min)) || ($min > $c{$parameter})) {
 1447:             $min = $c{$parameter} 
 1448:         }
 1449:     }
 1450:     return $min;
 1451: }
 1452: 
 1453: #-------------------------------------------------------
 1454: 
 1455: =item MAXPARM(parametername)
 1456: 
 1457: Returns the maximum value of the parameters matching the input parameter name.
 1458: parametername should be a string such as 'duedate'.
 1459: 
 1460: =cut
 1461: 
 1462: #-------------------------------------------------------
 1463: sub MAXPARM {
 1464:     my ($expression) = @_;
 1465:     my $max = undef;
 1466:     study($expression);
 1467:     foreach $parameter (keys(%c)) {
 1468:         next if ($parameter !~ /$expression/);
 1469:         if ((! defined($min)) || ($max < $c{$parameter})) {
 1470:             $max = $c{$parameter} 
 1471:         }
 1472:     }
 1473:     return $max;
 1474: }
 1475: 
 1476: sub calc {
 1477: #    $errorlog .= "\%t has ".(keys(%t))." keys\n";
 1478:     %sheet_values = %t; # copy %t into %sheet_values.
 1479: #    $errorlog .= "\%sheet_values has ".(keys(%sheet_values))." keys\n";
 1480:     my $notfinished=1;
 1481:     my $lastcalc='';
 1482:     my $depth=0;
 1483:     while ($notfinished) {
 1484: 	$notfinished=0;
 1485:         while (my ($cell,$value) = each(%t)) {
 1486:             my $old=$sheet_values{$cell};
 1487:             $sheet_values{$cell}=eval $value;
 1488: 	    if ($@) {
 1489: 		undef %sheet_values;
 1490:                 return $cell.': '.$@;
 1491:             }
 1492: 	    if ($sheet_values{$cell} ne $old) { 
 1493:                 $notfinished=1; 
 1494:                 $lastcalc=$cell; 
 1495:             }
 1496:         }
 1497:         $depth++;
 1498:         if ($depth>100) {
 1499: 	    undef %sheet_values;
 1500:             return $lastcalc.': Maximum calculation depth exceeded';
 1501:         }
 1502:     }
 1503:     return '';
 1504: }
 1505: 
 1506: # ------------------------------------------- End of "Inside of the safe space"
 1507: ENDDEFS
 1508:     $safeeval->reval($code);
 1509:     return $safeeval;
 1510: }
 1511: 
 1512: 
 1513: #
 1514: # expandnamed used to reside in the safe space
 1515: #
 1516: sub expandnamed {
 1517:     my $self = shift;
 1518:     my $expression=shift;
 1519:     if ($expression=~/^\&/) {
 1520: 	my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/);
 1521: 	my @vars=split(/\W+/,$formula);
 1522:         my %values=();
 1523: 	foreach my $varname ( @vars ) {
 1524:             if ($varname=~/\D/) {
 1525:                $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
 1526:                $varname=~s/$var/\([\\w:\\- ]\+\)/g;
 1527: 	       foreach (keys(%{$self->{'constants'}})) {
 1528: 		  if ($_=~/$varname/) {
 1529: 		      $values{$1}=1;
 1530:                   }
 1531:                }
 1532: 	    }
 1533:         }
 1534:         if ($func eq 'EXPANDSUM') {
 1535:             my $result='';
 1536: 	    foreach (keys(%values)) {
 1537:                 my $thissum=$formula;
 1538:                 $thissum=~s/$var/$_/g;
 1539:                 $result.=$thissum.'+';
 1540:             } 
 1541:             $result=~s/\+$//;
 1542:             return $result;
 1543:         } else {
 1544: 	    return 0;
 1545:         }
 1546:     } else {
 1547:         # it is not a function, so it is a parameter name
 1548:         # We should do the following:
 1549:         #    1. Take the list of parameter names
 1550:         #    2. look through the list for ones that match the parameter we want
 1551:         #    3. If there are no collisions, return the one that matches
 1552:         #    4. If there is a collision, return 'bad parameter name error'
 1553:         my $returnvalue = '';
 1554:         my @matches = ();
 1555:         $#matches = -1;
 1556:         study $expression;
 1557:         my $parameter;
 1558:         foreach $parameter (keys(%{$self->{'constants'}})) {
 1559:             push @matches,$parameter if ($parameter =~ /$expression/);
 1560:         }
 1561:         if (scalar(@matches) == 0) {
 1562:             $returnvalue = 'unmatched parameter: '.$parameter;
 1563:         } elsif (scalar(@matches) == 1) {
 1564:             # why do we not do this lookup here, instead of delaying it?
 1565:             $returnvalue = '$c{\''.$matches[0].'\'}';
 1566:         } elsif (scalar(@matches) > 0) {
 1567:             # more than one match.  Look for a concise one
 1568:             $returnvalue =  "'non-unique parameter name : $expression'";
 1569:             foreach (@matches) {
 1570:                 if (/^$expression$/) {
 1571:                     # why do we not do this lookup here?
 1572:                     $returnvalue = '$c{\''.$_.'\'}';
 1573:                 }
 1574:             }
 1575:         } else {
 1576:             # There was a negative number of matches, which indicates 
 1577:             # something is wrong with reality.  Better warn the user.
 1578:             $returnvalue = 'bizzare parameter: '.$parameter;
 1579:         }
 1580:         return $returnvalue;
 1581:     }
 1582: }
 1583: 
 1584: #
 1585: # sett used to reside in the safe space
 1586: #
 1587: sub sett {
 1588:     my $self = shift;
 1589:     my %t=();
 1590:     my $pattern='';
 1591:     if ($self->{'type'} eq 'assesscalc') {
 1592: 	$pattern='A';
 1593:     } else {
 1594:         $pattern='[A-Z]';
 1595:     }
 1596:     # Deal with the template row
 1597:     foreach my $col ($self->template_cells()) {
 1598:         next if ($col=~/^$pattern/);
 1599:         foreach my $trow ($self->rows()) {
 1600:             # Get the name of this cell
 1601:             my $lb=$col.$trow;
 1602:             # Grab the template declaration
 1603:             $t{$lb}=$self->formula('template_'.$col);
 1604:             # Replace '#' with the row number
 1605:             $t{$lb}=~s/\#/$trow/g;
 1606:             # Replace '....' with ','
 1607:             $t{$lb}=~s/\.\.+/\,/g;
 1608:             # Replace 'A0' with the value from 'A0'
 1609:             $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
 1610:             # Replace parameters
 1611:             $t{$lb}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
 1612:         }
 1613:     }
 1614:     # Deal with the normal cells
 1615:     foreach ($self->formulas_keys()) {
 1616: 	next if ($_=~/template\_/);
 1617:         if  (($_=~/^$pattern(\d+)/) && ($1)) {
 1618:             if ($self->formula($_) !~ /^\!/) {
 1619:                 $t{$_}=$self->{'constants'}->{$_};
 1620:             }
 1621:         } else {
 1622:             $t{$_}=$self->formula($_);
 1623:             $t{$_}=~s/\.\.+/\,/g;
 1624:             $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
 1625:             $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
 1626:         }
 1627:     }
 1628:     # For inserted lines, [B-Z] is also valid
 1629:     if ($self->{'type'} ne 'assesscalc') {
 1630:         foreach ($self->formulas_keys()) {
 1631:             next if ($_ !~ /[B-Z](\d+)/);
 1632:             next if ($self->formula('A'.$1) !~ /^[\~\-]/);
 1633:             $t{$_}=$self->formula($_);
 1634:             $t{$_}=~s/\.\.+/\,/g;
 1635:             $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
 1636:             $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
 1637:         }
 1638:     }
 1639:     # For some reason 'A0' gets special treatment...  This seems superfluous
 1640:     # but I imagine it is here for a reason.
 1641:     $t{'A0'}=$self->formula('A0');
 1642:     $t{'A0'}=~s/\.\.+/\,/g;
 1643:     $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
 1644:     $t{'A0'}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
 1645:     # Put %t into the safe space
 1646:     %{$self->{'safe'}->varglob('t')}=%t;
 1647: }
 1648: 
 1649: 
 1650: ###########################################
 1651: ###          Row output routines        ###
 1652: ###########################################
 1653: #
 1654: # get_row: Produce output row n from sheet by calling the appropriate routine
 1655: #
 1656: sub get_row {
 1657:     my $self = shift;
 1658:     my ($n) = @_;
 1659:     my ($rowlabel,@rowdata);
 1660:     if ($n eq '-') { 
 1661:         ($rowlabel,@rowdata) = $self->templaterow();
 1662:     } elsif ($self->{'type'} eq 'studentcalc') {
 1663:         ($rowlabel,@rowdata) = $self->outrowassess($n);
 1664:     } else {
 1665:         ($rowlabel,@rowdata) = $self->outrow($n);
 1666:     }
 1667:     return ($rowlabel,@rowdata);
 1668: }
 1669: 
 1670: sub templaterow {
 1671:     my $self = shift;
 1672:     my @cols=();
 1673:     my $rowlabel = 'Template</td><td>&nbsp;';
 1674:     foreach my $n ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1675:                    'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 1676:                    'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1677:                    'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1678:         push(@cols,{ name    => 'template_'.$_,
 1679:                      formula => $self->formula('template_'.$n),
 1680:                      value   => $self->value('template_'.$n) });
 1681:     }
 1682:     return ($rowlabel,@cols);
 1683: }
 1684: 
 1685: sub outrowassess {
 1686:     my $self = shift;
 1687:     # $n is the current row number
 1688:     my ($n) = @_;
 1689:     my @cols=();
 1690:     my $rowlabel='';
 1691:     if ($n) {
 1692:         my ($usy,$ufn)=split(/__&&&\__/,$self->formula('A'.$n));
 1693:         if (exists($self->{'rowlabel'}->{$usy})) {
 1694:             # This is dumb, but we need the information when we output
 1695:             # the html version of the studentcalc spreadsheet for the
 1696:             # links to the assesscalc sheets.
 1697:             $rowlabel = $self->{'rowlabel'}->{$usy}.':'.
 1698:                 &Apache::lonnet::escape($ufn);
 1699:         } else { 
 1700:             $rowlabel = '';
 1701:         }
 1702:     } elsif ($ENV{'request.role'} =~ /^st\./) {
 1703:         $rowlabel = 'Summary</td><td>0';
 1704:     } else {
 1705:         $rowlabel = 'Export</td><td>0';
 1706:     }
 1707:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1708: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 1709: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1710: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1711:         push(@cols,{ name    => $_.$n,
 1712:                      formula => $self->formula($_.$n),
 1713:                      value   => $self->value($_.$n)});
 1714:     }
 1715:     return ($rowlabel,@cols);
 1716: }
 1717: 
 1718: sub outrow {
 1719:     my $self = shift;
 1720:     my ($n)=@_;
 1721:     my @cols=();
 1722:     my $rowlabel;
 1723:     if ($n) {
 1724:         $rowlabel = $self->{'rowlabel'}->{$self->formula('A'.$n)};
 1725:     } else {
 1726:         if ($self->{'type'} eq 'classcalc') {
 1727:             $rowlabel = 'Summary</td><td>0';
 1728:         } else {
 1729:             $rowlabel = 'Export</td><td>0';
 1730:         }
 1731:     }
 1732:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1733: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 1734: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1735: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1736:         push(@cols,{ name    => $_.$n,
 1737:                      formula => $self->formula($_.$n),
 1738:                      value   => $self->value($_.$n)});
 1739:     }
 1740:     return ($rowlabel,@cols);
 1741: }
 1742: 
 1743: ########################################################
 1744: ####         Spreadsheet calculation methods       #####
 1745: ########################################################
 1746: #
 1747: # calcsheet: makes all the calls to compute the spreadsheet.
 1748: #
 1749: sub calcsheet {
 1750:     my $self = shift;
 1751:     $self->sync_safe_space();
 1752:     $self->clear_errorlog();
 1753:     $self->sett();
 1754:     my $result =  $self->{'safe'}->reval('&calc();');
 1755:     %{$self->{'values'}} = %{$self->{'safe'}->varglob('sheet_values')};
 1756: #    $self->logthis($self->get_errorlog());
 1757:     return $result;
 1758: }
 1759: 
 1760: ##
 1761: ## sync_safe_space:  Called by calcsheet to make sure all the data we 
 1762: #  need to calculate is placed into the safe space
 1763: ##
 1764: sub sync_safe_space {
 1765:     my $self = shift;
 1766:     # Inside the safe space 'formulas' has a diabolical alter-ego named 'f'.
 1767:     %{$self->{'safe'}->varglob('f')}=%{$self->{'formulas'}};
 1768:     # 'constants' leads a peaceful hidden life of 'c'.
 1769:     %{$self->{'safe'}->varglob('c')}=%{$self->{'constants'}};
 1770:     # 'othersheets' hides as 'os', a disguise few can penetrate.
 1771:     @{$self->{'safe'}->varglob('os')}=@{$self->{'othersheets'}};
 1772: }
 1773: 
 1774: ##
 1775: ## Retrieve the error log from the safe space (used for debugging)
 1776: ##
 1777: sub get_errorlog {
 1778:     my $self = shift;
 1779:     $self->{'errorlog'} = ${$self->{'safe'}->varglob('errorlog')};
 1780:     return $self->{'errorlog'};
 1781: }
 1782: 
 1783: ##
 1784: ## Clear the error log inside the safe space
 1785: ##
 1786: sub clear_errorlog {
 1787:     my $self = shift;
 1788:     ${$self->{'safe'}->varglob('errorlog')} = '';
 1789:     $self->{'errorlog'} = '';
 1790: }
 1791: 
 1792: 
 1793: ########################################################
 1794: #### Spreadsheet content retrieval/setting methods #####
 1795: ########################################################
 1796: ##
 1797: ## constants:  either set or get the constants
 1798: ##
 1799: ##
 1800: sub constants {
 1801:     my $self=shift;
 1802:     my ($constants) = @_;
 1803:     if (defined($constants)) {
 1804:         if (! ref($constants)) {
 1805:             my %tmp = @_;
 1806:             $constants = \%tmp;
 1807:         }
 1808:         $self->{'constants'} = $constants;
 1809:         return;
 1810:     } else {
 1811:         return %{$self->{'constants'}};
 1812:     }
 1813: }
 1814:     
 1815: ##
 1816: ## formulas: either set or get the formulas
 1817: ##
 1818: sub formulas {
 1819:     my $self=shift;
 1820:     my ($formulas) = @_;
 1821:     if (defined($formulas)) {
 1822:         if (! ref($formulas)) {
 1823:             my %tmp = @_;
 1824:             $formulas = \%tmp;
 1825:         }
 1826:         $self->{'formulas'} = $formulas;
 1827:         $self->{'rows'} = [];
 1828:         $self->{'template_cells'} = [];
 1829:         return;
 1830:     } else {
 1831:         return %{$self->{'formulas'}};
 1832:     }
 1833: }
 1834: 
 1835: ##
 1836: ## formulas_keys:  Return the keys to the formulas hash.
 1837: ##
 1838: sub formulas_keys {
 1839:     my $self = shift;
 1840:     my @keys = keys(%{$self->{'formulas'}});
 1841:     return keys(%{$self->{'formulas'}});
 1842: }
 1843: 
 1844: ##
 1845: ## formula:  Return the formula for a given cell in the spreadsheet
 1846: ## returns '' if the cell does not have a formula or does not exist
 1847: ##
 1848: sub formula {
 1849:     my $self = shift;
 1850:     my $cell = shift;
 1851:     if (defined($cell) && exists($self->{'formulas'}->{$cell})) {
 1852:         return $self->{'formulas'}->{$cell};
 1853:     }
 1854:     return '';
 1855: }
 1856: 
 1857: ##
 1858: ## logthis: write the input to lonnet.log
 1859: ##
 1860: sub logthis {
 1861:     my $self = shift;
 1862:     my $message = shift;
 1863:     &Apache::lonnet::logthis($self->{'type'}.':'.
 1864:                              $self->{'uname'}.':'.$self->{'udom'}.':'.
 1865:                              $message);
 1866:     return;
 1867: }
 1868: 
 1869: ##
 1870: ## dump_formulas_to_log: makes lonnet.log huge...
 1871: ##
 1872: sub dump_formulas_to_log {
 1873:     my $self =shift;
 1874:     $self->logthis("Spreadsheet formulas");
 1875:     $self->logthis("--------------------------------------------------------");
 1876:     while (my ($cell, $formula) = each(%{$self->{'formulas'}})) {
 1877:         $self->logthis('    '.$cell.' = '.$formula);
 1878:     }
 1879:     $self->logthis("--------------------------------------------------------");}
 1880: 
 1881: ##
 1882: ## value: returns the computed value of a particular cell
 1883: ##
 1884: sub value {
 1885:     my $self = shift;
 1886:     my $cell = shift;
 1887:     if (defined($cell) && exists($self->{'values'}->{$cell})) {
 1888:         return $self->{'values'}->{$cell};
 1889:     }
 1890:     return '';
 1891: }
 1892: 
 1893: ##
 1894: ## dump_values_to_log: makes lonnet.log huge...
 1895: ##
 1896: sub dump_values_to_log {
 1897:     my $self =shift;
 1898:     $self->logthis("Spreadsheet Values");
 1899:     $self->logthis("--------------------------------------------------------");
 1900:     while (my ($cell, $value) = each(%{$self->{'values'}})) {
 1901:         $self->logthis('    '.$cell.' = '.$value);
 1902:     }
 1903:     $self->logthis("--------------------------------------------------------");}
 1904: 
 1905: ##
 1906: ## Yet another debugging function
 1907: ##
 1908: sub dump_hash_to_log {
 1909:     my $self= shift();
 1910:     my %tmp = @_;
 1911:     if (@_<2) {
 1912:         %tmp = %{$_[0]};
 1913:     }
 1914:     $self->logthis('---------------------------- (entries end with ":"');
 1915:     while (my ($key,$val) = each (%tmp)) {
 1916:         $self->logthis($key.' = '.$val.':');
 1917:     }
 1918:     $self->logthis('---------------------------- (entries end with ":"');
 1919: }
 1920: 
 1921: ################################
 1922: ##      Helper functions      ##
 1923: ################################
 1924: ##
 1925: ## rebuild_stats: rebuilds the rows and template_cells arrays
 1926: ##
 1927: sub rebuild_stats {
 1928:     my $self = shift;
 1929:     $self->{'rows'}=[];
 1930:     $self->{'template_cells'}=[];
 1931:     foreach my $cell($self->formulas_keys()) {
 1932:         push(@{$self->{'rows'}},$1) if ($cell =~ /^A(\d+)/ && $1 != 0);
 1933:         push(@{$self->{'template_cells'}},$1) if ($cell =~ /^template_(\w+)/);
 1934:     }
 1935:     return;
 1936: }
 1937: 
 1938: ##
 1939: ## template_cells returns a list of the cells defined in the template row
 1940: ##
 1941: sub template_cells {
 1942:     my $self = shift;
 1943:     $self->rebuild_stats() if (!@{$self->{'template_cells'}});
 1944:     return @{$self->{'template_cells'}};
 1945: }
 1946: 
 1947: ##
 1948: ## rows returns a list of the names of cells defined in the A column
 1949: ##
 1950: sub rows {
 1951:     my $self = shift;
 1952:     $self->rebuild_stats() if (!@{$self->{'rows'}});
 1953:     return @{$self->{'rows'}};
 1954: }
 1955: 
 1956: ##
 1957: ## Sigh.... 
 1958: ##
 1959: sub setothersheets {
 1960:     my $self = shift;
 1961:     my @othersheets = @_;
 1962:     $self->{'othersheets'} = \@othersheets;
 1963: }
 1964: 
 1965: ##
 1966: ## rowlabels: get or set the rowlabels hash from the spreadsheet.
 1967: ##
 1968: sub rowlabels {
 1969:     my $self = shift;
 1970:     my ($rowlabel) = @_;
 1971:     if (defined($rowlabel)) {
 1972:         if (! ref($rowlabel)) {
 1973:             my %tmp = @_;
 1974:             $rowlabel = \%tmp;
 1975:         }
 1976:         $self->{'rowlabel'}=$rowlabel;
 1977:         return;
 1978:     } else {
 1979:         return %{$self->{'rowlabel'}} if (defined($self->{'rowlabel'}));
 1980:     }
 1981: }
 1982: 
 1983: ##
 1984: ## gettitle: returns a title for the spreadsheet.
 1985: ##
 1986: sub gettitle {
 1987:     my $self = shift;
 1988:     if ($self->{'type'} eq 'classcalc') {
 1989:         return $self->{'coursedesc'};
 1990:     } elsif ($self->{'type'} eq 'studentcalc') {
 1991:         return 'Grades for '.$self->{'uname'}.'@'.$self->{'udom'};
 1992:     } elsif ($self->{'type'} eq 'assesscalc') {
 1993:         if (($self->{'usymb'} eq '_feedback') ||
 1994:             ($self->{'usymb'} eq '_evaluation') ||
 1995:             ($self->{'usymb'} eq '_discussion') ||
 1996:             ($self->{'usymb'} eq '_tutoring')) {
 1997:             my $title = $self->{'usymb'};
 1998:             $title =~ s/^_//;
 1999:             $title = ucfirst($title);
 2000:             return $title;
 2001:         }
 2002:         return if (! defined($self->{'mapid'}) || 
 2003:                    $self->{'mapid'} !~ /^\d+$/);
 2004:         my $mapid = $self->{'mapid'};
 2005:         return if (! defined($self->{'resid'}) || 
 2006:                    $self->{'resid'} !~ /^\d+$/);
 2007:         my $resid = $self->{'resid'};
 2008:         my %course_db;
 2009:         tie(%course_db,'GDBM_File',$self->{'coursefilename'}.'.db',
 2010:             &GDBM_READER(),0640);
 2011:         return if (! tied(%course_db));
 2012:         my $key = 'title_'.$mapid.'.'.$resid;
 2013:         my $title = '';
 2014:         if (exists($course_db{$key})) {
 2015:             $title = $course_db{$key};
 2016:         } else {
 2017:             $title = $self->{'usymb'};
 2018:         }
 2019:         untie (%course_db);
 2020:         return $title;
 2021:     }
 2022: }
 2023: 
 2024: #
 2025: # Export of A-row
 2026: #
 2027: sub exportdata {
 2028:     my $self=shift;
 2029:     my @exportarray=();
 2030:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 2031: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 2032:         push(@exportarray,$self->value($_.'0'));
 2033:     } 
 2034:     return @exportarray;
 2035: }
 2036: 
 2037: ##
 2038: ## update_student_sheet: experimental function
 2039: ##
 2040: sub update_student_sheet{
 2041:     my $self = shift;
 2042:     my ($r,$c) = @_;
 2043:     # Load in the studentcalc sheet
 2044:     $self->readsheet('default_studentcalc');
 2045:     # Determine the structure (contained assessments, etc) of the sheet
 2046:     $self->updatesheet();
 2047:     # Load in the cached sheets for this student
 2048:     $self->cachedssheets();
 2049:     # Load in the (possibly cached) data from the assessment sheets        
 2050:     $self->loadstudent($r,$c);
 2051:     # Compute the sheet
 2052:     $self->calcsheet();
 2053: }
 2054: 
 2055: #
 2056: # sort_indicies: returns an ordered list of the rows of the spreadsheet
 2057: #
 2058: sub sort_indicies {
 2059:     my $self = shift;
 2060:     my @sortidx=();
 2061:     #
 2062:     if ($self->{'type'} eq 'classcalc') {
 2063:         my @sortby=(undef);
 2064:         # Skip row 0
 2065:         for (my $row=1;$row<=$self->{'maxrow'};$row++) {
 2066:             my (undef,$sname,$sdom,$fullname,$section,$id) = 
 2067:                 split(':',$self->{'rowlabel'}->{$self->formula('A'.$row)});
 2068:             push (@sortby, lc($fullname));
 2069:             push (@sortidx, $row);
 2070:         }
 2071:         @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
 2072:     } elsif ($self->{'type'} eq 'studentcalc') {
 2073:         my @sortby1=(undef);
 2074:         my @sortby2=(undef);
 2075:         # Skip row 0
 2076:         for (my $row=1;$row<=$self->{'maxrow'};$row++) {
 2077:             my ($key,undef) = split(/__&&&\__/,$self->formula('A'.$row));
 2078:             my $rowlabel = $self->{'rowlabel'}->{$key};
 2079:             my (undef,$symb,$mapid,$resid,$title,$ufn) = 
 2080:                 split(':',$rowlabel);
 2081:             $ufn   = &Apache::lonnet::unescape($ufn);
 2082:             $symb  = &Apache::lonnet::unescape($symb);
 2083:             $title = &Apache::lonnet::unescape($title);
 2084:             my ($sequence) = ($symb =~ /\/([^\/]*\.sequence)/);
 2085:             if ($sequence eq '') {
 2086:                 $sequence = $symb;
 2087:             }
 2088:             push (@sortby1, $sequence);
 2089:             push (@sortby2, $title);
 2090:             push (@sortidx, $row);
 2091:         }
 2092:         @sortidx = sort { $sortby1[$a] cmp $sortby1[$b] || 
 2093:                               $sortby2[$a] cmp $sortby2[$b] } @sortidx;
 2094:     } else {
 2095:         my @sortby=(undef);
 2096:         # Skip row 0
 2097:         $self->sync_safe_space();
 2098:         for (my $row=1;$row<=$self->{'maxrow'};$row++) {
 2099:             push (@sortby, $self->{'safe'}->reval('$f{"A'.$row.'"}'));
 2100:             push (@sortidx, $row);
 2101:         }
 2102:         @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
 2103:     }
 2104:     return @sortidx;
 2105: }
 2106: 
 2107: #############################################################
 2108: ###                                                       ###
 2109: ###              Spreadsheet Output Routines              ###
 2110: ###                                                       ###
 2111: #############################################################
 2112: 
 2113: ############################################
 2114: ##         HTML output routines           ##
 2115: ############################################
 2116: sub html_editable_cell {
 2117:     my ($cell,$bgcolor) = @_;
 2118:     my $result;
 2119:     my ($name,$formula,$value);
 2120:     if (defined($cell)) {
 2121:         $name    = $cell->{'name'};
 2122:         $formula = $cell->{'formula'};
 2123:         $value   = $cell->{'value'};
 2124:     }
 2125:     $name    = '' if (! defined($name));
 2126:     $formula = '' if (! defined($formula));
 2127:     if (! defined($value)) {
 2128:         $value = '<font color="'.$bgcolor.'">#</font>';
 2129:         if ($formula ne '') {
 2130:             $value = '<i>undefined value</i>';
 2131:         }
 2132:     } elsif ($value =~ /^\s*$/ ) {
 2133:         $value = '<font color="'.$bgcolor.'">#</font>';
 2134:     } else {
 2135:         $value = &HTML::Entities::encode($value) if ($value !~/&nbsp;/);
 2136:     }
 2137:     # Make the formula safe for outputting
 2138:     $formula =~ s/\'/\"/g;
 2139:     # The formula will be parsed by the browser *twice* before being 
 2140:     # displayed to the user for editing.
 2141:     $formula = &HTML::Entities::encode(&HTML::Entities::encode($formula));
 2142:     # Escape newlines so they make it into the edit window
 2143:     $formula =~ s/\n/\\n/gs;
 2144:     # Glue everything together
 2145:     $result .= "<a href=\"javascript:celledit(\'".
 2146:         $name."','".$formula."');\">".$value."</a>";
 2147:     return $result;
 2148: }
 2149: 
 2150: sub html_uneditable_cell {
 2151:     my ($cell,$bgcolor) = @_;
 2152:     my $value = (defined($cell) ? $cell->{'value'} : '');
 2153:     $value = &HTML::Entities::encode($value) if ($value !~/&nbsp;/);
 2154:     return '&nbsp;'.$value.'&nbsp;';
 2155: }
 2156: 
 2157: sub outsheet_html  {
 2158:     my $self = shift;
 2159:     my ($r) = @_;
 2160:     my ($num_uneditable,$realm,$row_type);
 2161:     my $requester_is_student = ($ENV{'request.role'} =~ /^st\./);
 2162:     if ($self->{'type'} eq 'assesscalc') {
 2163:         $num_uneditable = 1;
 2164:         $realm = 'Assessment';
 2165:         $row_type = 'Item';
 2166:     } elsif ($self->{'type'} eq 'studentcalc') {
 2167:         $num_uneditable = 26;
 2168:         $realm = 'User';
 2169:         $row_type = 'Assessment';
 2170:     } elsif ($self->{'type'} eq 'classcalc') {
 2171:         $num_uneditable = 26;
 2172:         $realm = 'Course';
 2173:         $row_type = 'Student';
 2174:     } else {
 2175:         return;  # error
 2176:     }
 2177:     ####################################
 2178:     # Print out header table
 2179:     ####################################
 2180:     my $num_left = 52-$num_uneditable;
 2181:     my $tabledata =<<"END";
 2182: <table border="2">
 2183: <tr>
 2184:   <th colspan="2" rowspan="2"><font size="+2">$realm</font></th>
 2185:   <td bgcolor="#FFDDDD" colspan="$num_uneditable">
 2186:       <b><font size="+1">Import</font></b></td>
 2187:   <td colspan="$num_left">
 2188:       <b><font size="+1">Calculations</font></b></td>
 2189: </tr><tr>
 2190: END
 2191:     my $label_num = 0;
 2192:     foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
 2193:         if ($label_num<$num_uneditable) { 
 2194:             $tabledata.='<td bgcolor="#FFDDDD">';
 2195:         } else {
 2196:             $tabledata.='<td>';
 2197:         }
 2198:         $tabledata.="<b><font size=+1>$_</font></b></td>";
 2199:         $label_num++;
 2200:     }
 2201:     $tabledata.="</tr>\n";
 2202:     $r->print($tabledata);
 2203:     ####################################
 2204:     # Print out template row
 2205:     ####################################
 2206:     my ($num_cols_output,$row_html,$rowlabel,@rowdata);
 2207:     
 2208:     if (! $requester_is_student) {
 2209:         ($rowlabel,@rowdata) = $self->get_row('-');
 2210:         $row_html = '<tr><td>'.$self->format_html_rowlabel($rowlabel).'</td>';
 2211:         $num_cols_output = 0;
 2212:         foreach my $cell (@rowdata) {
 2213:             if ($requester_is_student || 
 2214:                 $num_cols_output++ < $num_uneditable) {
 2215:                 $row_html .= '<td bgcolor="#FFDDDD">';
 2216:                 $row_html .= &html_uneditable_cell($cell,'#FFDDDD');
 2217:             } else {
 2218:                 $row_html .= '<td bgcolor="#EOFFDD">';
 2219:                 $row_html .= &html_editable_cell($cell,'#E0FFDD');
 2220:             }
 2221:             $row_html .= '</td>';
 2222:         }
 2223:         $row_html.= "</tr>\n";
 2224:         $r->print($row_html);
 2225:     }
 2226:     ####################################
 2227:     # Print out summary/export row
 2228:     ####################################
 2229:     ($rowlabel,@rowdata) = $self->get_row('0');
 2230:     $row_html = '<tr><td>'.$self->format_html_rowlabel($rowlabel).'</td>';
 2231:     $num_cols_output = 0;
 2232:     foreach my $cell (@rowdata) {
 2233:         if ($num_cols_output++ < 26 && ! $requester_is_student) {
 2234:             $row_html .= '<td bgcolor="#CCCCFF">';
 2235:             $row_html .= &html_editable_cell($cell,'#CCCCFF');
 2236:         } else {
 2237:             $row_html .= '<td bgcolor="#DDCCFF">';
 2238:             $row_html .= &html_uneditable_cell($cell,'#CCCCFF');
 2239:         }
 2240:         $row_html .= '</td>';
 2241:     }
 2242:     $row_html.= "</tr>\n";
 2243:     $r->print($row_html);
 2244:     $r->print('</table>');
 2245:     ####################################
 2246:     # Prepare to output rows
 2247:     ####################################
 2248:     my @Rows = $self->sort_indicies();
 2249:     #
 2250:     # Loop through the rows and output them one at a time
 2251:     my $rows_output=0;
 2252:     foreach my $rownum (@Rows) {
 2253:         my ($rowlabel,@rowdata) = $self->get_row($rownum);
 2254:         next if ($rowlabel =~ /^\s*$/);
 2255:         next if (($self->{'type'} eq 'assesscalc') && 
 2256:                  (! $ENV{'form.showall'})                &&
 2257:                  ($rowdata[0]->{'value'} =~ /^\s*$/));
 2258:         if (! $ENV{'form.showall'} &&
 2259:             $self->{'type'} =~ /^(studentcalc|classcalc)$/) {
 2260:             my $row_is_empty = 1;
 2261:             foreach my $cell (@rowdata) {
 2262:                 if ($cell->{'value'} !~  /^\s*$/) {
 2263:                     $row_is_empty = 0;
 2264:                     last;
 2265:                 }
 2266:             }
 2267:             next if ($row_is_empty);
 2268:         }
 2269:         #
 2270:         my $defaultbg='#E0FF';
 2271:         #
 2272:         my $row_html ="\n".'<tr><td><b><font size=+1>'.$rownum.
 2273:             '</font></b></td>';
 2274:         #
 2275:         if ($self->{'type'} eq 'classcalc') {
 2276:             $row_html.='<td>'.$self->format_html_rowlabel($rowlabel).'</td>';
 2277:             # Output links for each student?
 2278:             # Nope, that is already done for us in format_html_rowlabel 
 2279:             # (for now)
 2280:         } elsif ($self->{'type'} eq 'studentcalc') {
 2281:             my $ufn = (split(/:/,$rowlabel))[5];
 2282:             $row_html.='<td>'.$self->format_html_rowlabel($rowlabel);
 2283:             $row_html.= '<br>'.
 2284:                 '<select name="sel_'.$rownum.'" '.
 2285:                     'onChange="changesheet('.$rownum.')">'.
 2286:                         '<option name="default">Default</option>';
 2287:             foreach (@{$self->{'othersheets'}}) {
 2288:                 $row_html.='<option name="'.$_.'"';
 2289:                 if ($ufn eq $_) {
 2290:                     $row_html.=' selected';
 2291:                 }
 2292:                 $row_html.='>'.$_.'</option>';
 2293:             }
 2294:             $row_html.='</select></td>';
 2295:         } elsif ($self->{'type'} eq 'assesscalc') {
 2296:             $row_html.='<td>'.$self->format_html_rowlabel($rowlabel).'</td>';
 2297:         }
 2298:         #
 2299:         my $shown_cells = 0;
 2300:         foreach my $cell (@rowdata) {
 2301:             my $value    = $cell->{'value'};
 2302:             my $formula  = $cell->{'formula'};
 2303:             my $cellname = $cell->{'name'};
 2304:             #
 2305:             my $bgcolor;
 2306:             if ($shown_cells && ($shown_cells/5 == int($shown_cells/5))) {
 2307:                 $bgcolor = $defaultbg.'99';
 2308:             } else {
 2309:                 $bgcolor = $defaultbg.'DD';
 2310:             }
 2311:             $bgcolor='#FFDDDD' if ($shown_cells < $num_uneditable);
 2312:             #
 2313:             $row_html.='<td bgcolor='.$bgcolor.'>';
 2314:             if ($requester_is_student || $shown_cells < $num_uneditable) {
 2315:                 $row_html .= &html_uneditable_cell($cell,$bgcolor);
 2316:             } else {
 2317:                 $row_html .= &html_editable_cell($cell,$bgcolor);
 2318:             }
 2319:             $row_html.='</td>';
 2320:             $shown_cells++;
 2321:         }
 2322:         if ($row_html) {
 2323:             if ($rows_output % 25 == 0) {
 2324:                 $r->print("</table>\n<br>\n");
 2325:                 $r->rflush();
 2326:                 $r->print('<table border=2>'.
 2327:                           '<tr><td>&nbsp;<td>'.$row_type.'</td>'.
 2328:                           '<td>'.
 2329:                           join('</td><td>',
 2330:                                (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
 2331:                                       'abcdefghijklmnopqrstuvwxyz'))).
 2332:                           "</td></tr>\n");
 2333:             }
 2334:             $rows_output++;
 2335:             $r->print($row_html);
 2336:         }
 2337:     }
 2338:     #
 2339:     $r->print('</table>');
 2340:     #
 2341:     # Debugging code (be sure to uncomment errorlog code in safe space):
 2342:     #
 2343:     # $r->print("\n<pre>");
 2344:     # $r->print(&geterrorlog($self));
 2345:     # $r->print("\n</pre>");
 2346:     return 1;
 2347: }
 2348: 
 2349: ############################################
 2350: ##         csv output routines            ##
 2351: ############################################
 2352: sub outsheet_csv   {
 2353:     my $self = shift;
 2354:     my ($r) = @_;
 2355:     my $csvdata = '';
 2356:     my @Values;
 2357:     ####################################
 2358:     # Prepare to output rows
 2359:     ####################################
 2360:     my @Rows = $self->sort_indicies();
 2361:     #
 2362:     # Loop through the rows and output them one at a time
 2363:     my $rows_output=0;
 2364:     foreach my $rownum (@Rows) {
 2365:         my ($rowlabel,@rowdata) = $self->get_row($rownum);
 2366:         next if ($rowlabel =~ /^\s*$/);
 2367:         push (@Values,$self->format_csv_rowlabel($rowlabel));
 2368:         foreach my $cell (@rowdata) {
 2369:             push (@Values,'"'.$cell->{'value'}.'"');
 2370:         }
 2371:         $csvdata.= join(',',@Values)."\n";
 2372:         @Values = ();
 2373:     }
 2374:     #
 2375:     # Write the CSV data to a file and serve up a link
 2376:     #
 2377:     my $filename = '/prtspool/'.
 2378:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
 2379:         time.'_'.rand(1000000000).'.csv';
 2380:     my $file;
 2381:     unless ($file = Apache::File->new('>'.'/home/httpd'.$filename)) {
 2382:         $r->log_error("Couldn't open $filename for output $!");
 2383:         $r->print("Problems occured in writing the csv file.  ".
 2384:                   "This error has been logged.  ".
 2385:                   "Please alert your LON-CAPA administrator.");
 2386:         $r->print("<pre>\n".$csvdata."</pre>\n");
 2387:         return 0;
 2388:     }
 2389:     print $file $csvdata;
 2390:     close($file);
 2391:     $r->print('<br /><br />'.
 2392:               '<a href="'.$filename.'">Your CSV spreadsheet.</a>'."\n");
 2393:     #
 2394:     return 1;
 2395: }
 2396: 
 2397: ############################################
 2398: ##        Excel output routines           ##
 2399: ############################################
 2400: sub outsheet_recursive_excel {
 2401:     my $self = shift;
 2402:     my ($r) = @_;
 2403:     my $c = $r->connection;
 2404:     return undef if ($self->{'type'} ne 'classcalc');
 2405:     my ($workbook,$filename) = $self->create_excel_spreadsheet($r);
 2406:     return undef if (! defined($workbook));
 2407:     #
 2408:     # Create main worksheet
 2409:     my $main_worksheet = $workbook->addworksheet('main');
 2410:     #
 2411:     # Figure out who the students are
 2412:     my %f=$self->formulas();
 2413:     my $count = 0;
 2414:     $r->print(<<END);
 2415: <p>
 2416: Compiling Excel Workbook with a worksheet for each student.
 2417: </p><p>
 2418: This operation may take longer than a complete recalculation of the
 2419: spreadsheet. 
 2420: </p><p>
 2421: To abort this operation, hit the stop button on your browser.
 2422: </p><p>
 2423: A link to the spreadsheet will be available at the end of this process.
 2424: </p>
 2425: <p>
 2426: END
 2427:     $r->rflush();
 2428:     my $starttime = time;
 2429:     foreach my $rownum ($self->sort_indicies()) {
 2430:         $count++;
 2431:         my ($sname,$sdom) = split(':',$f{'A'.$rownum});
 2432:         my $student_excel_worksheet=$workbook->addworksheet($sname.'@'.$sdom);
 2433:         # Create a new spreadsheet
 2434:         my $studentsheet = &Apache::lonspreadsheet::Spreadsheet->new
 2435:                                    ($sname,$sdom,'studentcalc',undef);
 2436:         # Read in the spreadsheet definition
 2437:         $studentsheet->update_student_sheet($r,$c);
 2438:         # Stuff the sheet into excel
 2439:         $studentsheet->export_sheet_as_excel($student_excel_worksheet);
 2440:         my $totaltime = int((time - $starttime) / $count * $self->{'maxrow'});
 2441:         my $timeleft = int((time - $starttime) / $count * ($self->{'maxrow'} - $count));
 2442:         if ($count % 5 == 0) {
 2443:             $r->print($count.' students completed.'.
 2444:                       '  Time remaining: '.$timeleft.' sec. '.
 2445:                       '  Estimated total time: '.$totaltime." sec <br />\n");
 2446:             $r->rflush();
 2447:         }
 2448:         if(defined($c) && ($c->aborted())) {
 2449:             last;
 2450:         }
 2451:     }
 2452:     #
 2453:     if(! $c->aborted() ) {
 2454:         $r->print('All students spreadsheets completed!<br />');
 2455:         $r->rflush();
 2456:         #
 2457:         # &export_sheet_as_excel fills $worksheet with the data from $sheet
 2458:         $self->export_sheet_as_excel($main_worksheet);
 2459:         #
 2460:         $workbook->close();
 2461:         # Okay, the spreadsheet is taken care of, so give the user a link.
 2462:         $r->print('<br /><br />'.
 2463:                   '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
 2464:     } else {
 2465:         $workbook->close();  # Not sure how necessary this is.
 2466:         #unlink('/home/httpd'.$filename); # No need to keep this around?
 2467:     }
 2468:     return 1;
 2469: }
 2470: 
 2471: sub outsheet_excel {
 2472:     my $self = shift;
 2473:     my ($r) = @_;
 2474:     my ($workbook,$filename) = $self->create_excel_spreadsheet($r);
 2475:     return undef if (! defined($workbook));
 2476:     my $sheetname;
 2477:     if ($self->{'type'} eq 'classcalc') {
 2478:         $sheetname = 'Main';
 2479:     } elsif ($self->{'type'} eq 'studentcalc') {
 2480:         $sheetname = $self->{'uname'}.'@'.$self->{'udom'};
 2481:     } elsif ($self->{'type'} eq 'assesscalc') {
 2482:         $sheetname = $self->{'uname'}.'@'.$self->{'udom'}.' assessment';
 2483:     }
 2484:     my $worksheet = $workbook->addworksheet($sheetname);
 2485:     #
 2486:     # &export_sheet_as_excel fills $worksheet with the data from $sheet
 2487:     $self->export_sheet_as_excel($worksheet);
 2488:     #
 2489:     $workbook->close();
 2490:     # Okay, the spreadsheet is taken care of, so give the user a link.
 2491:     $r->print('<br /><br />'.
 2492:               '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
 2493:     return 1;
 2494: }
 2495: 
 2496: sub create_excel_spreadsheet {
 2497:     my $self = shift;
 2498:     my ($r) = @_;
 2499:     my $filename = '/prtspool/'.
 2500:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
 2501:         time.'_'.rand(1000000000).'.xls';
 2502:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 2503:     if (! defined($workbook)) {
 2504:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 2505:         $r->print("Problems creating new Excel file.  ".
 2506:                   "This error has been logged.  ".
 2507:                   "Please alert your LON-CAPA administrator");
 2508:         return undef;
 2509:     }
 2510:     #
 2511:     # The excel spreadsheet stores temporary data in files, then put them
 2512:     # together.  If needed we should be able to disable this (memory only).
 2513:     # The temporary directory must be specified before calling 'addworksheet'.
 2514:     # File::Temp is used to determine the temporary directory.
 2515:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 2516:     #
 2517:     # Determine the name to give the worksheet
 2518:     return ($workbook,$filename);
 2519: }
 2520: 
 2521: sub export_sheet_as_excel {
 2522:     my $self = shift;
 2523:     my $worksheet = shift;
 2524:     #
 2525:     my $rows_output = 0;
 2526:     my $cols_output = 0;
 2527:     ####################################
 2528:     #    Write an identifying row      #
 2529:     ####################################
 2530:     my @Headerinfo = ($self->{'coursedesc'});
 2531:     my $title = $self->gettitle();
 2532:     $cols_output = 0;    
 2533:     if (defined($title)) {
 2534:         $worksheet->write($rows_output++,$cols_output++,$title);
 2535:     }
 2536:     ####################################
 2537:     #   Write the summary/export row   #
 2538:     ####################################
 2539:     my ($rowlabel,@rowdata) = &get_row($self,'0');
 2540:     my $label = &format_excel_rowlabel($self,$rowlabel);
 2541:     $cols_output = 0;
 2542:     $worksheet->write($rows_output,$cols_output++,$label);
 2543:     foreach my $cell (@rowdata) {
 2544:         $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
 2545:     }
 2546:     $rows_output+= 2;   # Skip a row, just for fun
 2547:     ####################################
 2548:     # Prepare to output rows
 2549:     ####################################
 2550:     my @Rows = &sort_indicies($self);
 2551:     #
 2552:     # Loop through the rows and output them one at a time
 2553:     foreach my $rownum (@Rows) {
 2554:         my ($rowlabel,@rowdata) = &get_row($self,$rownum);
 2555:         next if ($rowlabel =~ /^[\s]*$/);
 2556:         $cols_output = 0;
 2557:         my $label = &format_excel_rowlabel($self,$rowlabel);
 2558:         if ( ! $ENV{'form.showall'} &&
 2559:              $self->{'type'} =~ /^(studentcalc|classcalc)$/) {
 2560:             my $row_is_empty = 1;
 2561:             foreach my $cell (@rowdata) {
 2562:                 if ($cell->{'value'} !~  /^\s*$/) {
 2563:                     $row_is_empty = 0;
 2564:                     last;
 2565:                 }
 2566:             }
 2567:             next if ($row_is_empty);
 2568:         }
 2569:         $worksheet->write($rows_output,$cols_output++,$rownum);
 2570:         $worksheet->write($rows_output,$cols_output++,$label);
 2571:         if (ref($label)) {
 2572:             $cols_output = (scalar(@$label));
 2573:         }
 2574:         foreach my $cell (@rowdata) {
 2575:             $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
 2576:         }
 2577:         $rows_output++;
 2578:     }
 2579:     return;
 2580: }
 2581: 
 2582: ############################################
 2583: ##          XML output routines           ##
 2584: ############################################
 2585: sub outsheet_xml   {
 2586:     my $self = shift;
 2587:     my ($r) = @_;
 2588:     ## Someday XML
 2589:     ## Will be rendered for the user
 2590:     ## But not on this day
 2591: }
 2592: 
 2593: ##
 2594: ## Outsheet - calls other outsheet_* functions
 2595: ##
 2596: sub outsheet {
 2597:     my $self = shift;
 2598:     my ($r)=@_;
 2599:     if (! exists($ENV{'form.output'})) {
 2600:         $ENV{'form.output'} = 'HTML';
 2601:     }
 2602:     if (lc($ENV{'form.output'}) eq 'csv') {
 2603:         $self->outsheet_csv($r);
 2604:     } elsif (lc($ENV{'form.output'}) eq 'excel') {
 2605:         $self->outsheet_excel($r);
 2606:     } elsif (lc($ENV{'form.output'}) eq 'recursive excel') {
 2607:         $self->outsheet_recursive_excel($r);
 2608: #    } elsif (lc($ENV{'form.output'}) eq 'xml' ) {
 2609: #        $self->outsheet_xml($r);
 2610:     } else {
 2611:         $self->outsheet_html($r);
 2612:     }
 2613: }
 2614: 
 2615: #
 2616: # othersheets: Returns the list of other spreadsheets available 
 2617: #
 2618: sub othersheets {
 2619:     my $self = shift;
 2620:     my ($stype)=@_;
 2621:     $stype = $self->{'type'} if (! defined($stype));
 2622:     #
 2623:     my $cnum  = $self->{'cnum'};
 2624:     my $cdom  = $self->{'cdom'};
 2625:     my $chome = $self->{'chome'};
 2626:     #
 2627:     my @alternatives=();
 2628:     my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
 2629:     my ($tmp) = keys(%results);
 2630:     unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 2631:         @alternatives = sort (keys(%results));
 2632:     }
 2633:     return @alternatives; 
 2634: }
 2635: 
 2636: #
 2637: # Parse a spreadsheet
 2638: # 
 2639: sub parse_sheet {
 2640:     # $sheetxml is a scalar reference or a scalar
 2641:     my ($sheetxml) = @_;
 2642:     if (! ref($sheetxml)) {
 2643:         my $tmp = $sheetxml;
 2644:         $sheetxml = \$tmp;
 2645:     }
 2646:     my %f;
 2647:     my $parser=HTML::TokeParser->new($sheetxml);
 2648:     my $token;
 2649:     while ($token=$parser->get_token) {
 2650:         if ($token->[0] eq 'S') {
 2651:             if ($token->[1] eq 'field') {
 2652:                 $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
 2653:                     $parser->get_text('/field');
 2654:             }
 2655:             if ($token->[1] eq 'template') {
 2656:                 $f{'template_'.$token->[2]->{'col'}}=
 2657:                     $parser->get_text('/template');
 2658:             }
 2659:         }
 2660:     }
 2661:     return \%f;
 2662: }
 2663: 
 2664: sub readsheet {
 2665:     my $self = shift;
 2666:     my ($fn)=@_;
 2667:     #
 2668:     my $stype = $self->{'type'};
 2669:     my $cnum  = $self->{'cnum'};
 2670:     my $cdom  = $self->{'cdom'};
 2671:     my $chome = $self->{'chome'};
 2672:     #
 2673:     if (! defined($fn)) {
 2674:         # There is no filename. Look for defaults in course and global, cache
 2675:         unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
 2676:             my %tmphash = &Apache::lonnet::get('environment',
 2677:                                                ['spreadsheet_default_'.$stype],
 2678:                                                $cdom,$cnum);
 2679:             my ($tmp) = keys(%tmphash);
 2680:             if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 2681:                 $fn = 'default_'.$stype;
 2682:             } else {
 2683:                 $fn = $tmphash{'spreadsheet_default_'.$stype};
 2684:             } 
 2685:             unless (($fn) && ($fn!~/^error\:/)) {
 2686:                 $fn='default_'.$stype;
 2687:             }
 2688:             $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn; 
 2689:         }
 2690:     }
 2691:     # $fn now has a value
 2692:     $self->{'filename'} = $fn;
 2693:     # see if sheet is cached
 2694:     if (exists($spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn})) {
 2695:         
 2696:         my %tmp = split(/___;___/,
 2697:                         $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn});
 2698:         $self->formulas(\%tmp);
 2699:     } else {
 2700:         # Not cached, need to read
 2701:         my %f=();
 2702:         if ($fn=~/^default\_/) {
 2703:             my $sheetxml='';
 2704:             my $fh;
 2705:             my $dfn=$fn;
 2706:             $dfn=~s/\_/\./g;
 2707:             if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
 2708:                 $sheetxml=join('',<$fh>);
 2709:             } else {
 2710:                 # $sheetxml='<field row="0" col="A">"Error"</field>';
 2711:                 $sheetxml='<field row="0" col="A"></field>';
 2712:             }
 2713:             %f=%{&parse_sheet(\$sheetxml)};
 2714:         } elsif($fn=~/\/*\.spreadsheet$/) {
 2715:             my $sheetxml=&Apache::lonnet::getfile
 2716:                 (&Apache::lonnet::filelocation('',$fn));
 2717:             if ($sheetxml == -1) {
 2718:                 $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
 2719:                     .$fn.'"</field>';
 2720:             }
 2721:             %f=%{&parse_sheet(\$sheetxml)};
 2722:         } else {
 2723:             my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
 2724:             my ($tmp) = keys(%tmphash);
 2725:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 2726:                 foreach (keys(%tmphash)) {
 2727:                     $f{$_}=$tmphash{$_};
 2728:                 }
 2729:             } else {
 2730:                 # Unable to grab the specified spreadsheet,
 2731:                 # so we get the default ones instead.
 2732:                 $fn = 'default_'.$stype;
 2733:                 $self->{'filename'} = $fn;
 2734:                 my $dfn = $fn;
 2735:                 $dfn =~ s/\_/\./g;
 2736:                 my $sheetxml;
 2737:                 if (my $fh=Apache::File->new($includedir.'/'.$dfn)) {
 2738:                     $sheetxml = join('',<$fh>);
 2739:                 } else {
 2740:                     $sheetxml='<field row="0" col="A">'.
 2741:                         '"Unable to load spreadsheet"</field>';
 2742:                 }
 2743:                 %f=%{&parse_sheet(\$sheetxml)};
 2744:             }
 2745:         }
 2746:         # Cache and set
 2747:         $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);  
 2748:         $self->formulas(\%f);
 2749:     }
 2750: }
 2751: 
 2752: # ------------------------------------------------------------ Save spreadsheet
 2753: sub writesheet {
 2754:     my $self = shift;
 2755:     my ($makedef)=@_;
 2756:     my $cid=$self->{'cid'};
 2757:     if (&Apache::lonnet::allowed('opa',$cid)) {
 2758:         my %f=$self->formulas();
 2759:         my $stype= $self->{'type'};
 2760:         my $cnum = $self->{'cnum'};
 2761:         my $cdom = $self->{'cdom'};
 2762:         my $chome= $self->{'chome'};
 2763:         my $fn   = $self->{'filename'};
 2764:         # Cache new sheet
 2765:         $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
 2766:         # Write sheet
 2767:         foreach (keys(%f)) {
 2768:             delete($f{$_}) if ($f{$_} eq 'import');
 2769:         }
 2770:         my $reply = &Apache::lonnet::put($fn,\%f,$cdom,$cnum);
 2771:         if ($reply eq 'ok') {
 2772:             $reply = &Apache::lonnet::put($stype.'_spreadsheets',
 2773:                             {$fn => $ENV{'user.name'}.'@'.$ENV{'user.domain'}},
 2774:                                           $cdom,$cnum);
 2775:             if ($reply eq 'ok') {
 2776:                 if ($makedef) { 
 2777:                     $reply = &Apache::lonnet::put('environment',
 2778:                                     {'spreadsheet_default_'.$stype => $fn },
 2779:                                                   $cdom,$cnum);
 2780:                     if ($reply eq 'ok' && 
 2781:                         ($self->{'type'} eq 'studentcalc' ||
 2782:                          $self->{'type'} eq 'assesscalc')) {
 2783:                         # Expire the spreadsheets of the other students.
 2784:                         &Apache::lonnet::expirespread('','','studentcalc','');
 2785:                     }
 2786:                     return $reply;
 2787:                 } 
 2788:                 return $reply;
 2789:             } 
 2790:             return $reply;
 2791:         } 
 2792:         return $reply;
 2793:     }
 2794:     return 'unauthorized';
 2795: }
 2796: 
 2797: # ----------------------------------------------- Make a temp copy of the sheet
 2798: # "Modified workcopy" - interactive only
 2799: #
 2800: sub tmpwrite {
 2801:     my $self = shift;
 2802:     my $fn=$ENV{'user.name'}.'_'.
 2803:         $ENV{'user.domain'}.'_spreadsheet_'.$self->{'usymb'}.'_'.
 2804:            $self->{'filename'};
 2805:     $fn=~s/\W/\_/g;
 2806:     $fn=$Apache::lonnet::tmpdir.$fn.'.tmp';
 2807:     my $fh;
 2808:     if ($fh=Apache::File->new('>'.$fn)) {
 2809:         my %f = $self->formulas();
 2810:         while( my ($cell,$formula) = each(%f)) {
 2811:             print $fh &Apache::lonnet::escape($cell)."=".&Apache::lonnet::escape($formula)."\n";
 2812:         }
 2813:     }
 2814: }
 2815: 
 2816: 
 2817: # ---------------------------------------------------------- Read the temp copy
 2818: sub tmpread {
 2819:     my $self = shift;
 2820:     my ($nfield,$nform)=@_;
 2821:     my $fn=$ENV{'user.name'}.'_'.
 2822:            $ENV{'user.domain'}.'_spreadsheet_'.$self->{'usymb'}.'_'.
 2823:            $self->{'filename'};
 2824:     $fn=~s/\W/\_/g;
 2825:     $fn=$Apache::lonnet::tmpdir.$fn.'.tmp';
 2826:     my $fh;
 2827:     my %fo=();
 2828:     my $countrows=0;
 2829:     if ($fh=Apache::File->new($fn)) {
 2830:         while (<$fh>) {
 2831: 	    chomp;
 2832:             my ($cell,$formula) = split(/=/);
 2833:             $cell    = &Apache::lonnet::unescape($cell);
 2834:             $formula = &Apache::lonnet::unescape($formula);
 2835:             $fo{$cell} = $formula;
 2836:         }
 2837:     }
 2838:     if ($nform eq 'changesheet') {
 2839:         $fo{'A'.$nfield}=(split(/__&&&\__/,$fo{'A'.$nfield}))[0];
 2840:         unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
 2841: 	    $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
 2842:         }
 2843:     } else {
 2844:        if ($nfield) { $fo{$nfield}=$nform; }
 2845:     }
 2846:     $self->formulas(\%fo);
 2847: }
 2848: 
 2849: ##################################################################
 2850: ##                  Row label formatting routines               ##
 2851: ##################################################################
 2852: sub format_html_rowlabel {
 2853:     my $self = shift;
 2854:     my $rowlabel = shift;
 2855:     return '' if ($rowlabel eq '');
 2856:     my ($type,$labeldata) = split(':',$rowlabel,2);
 2857:     my $result = '';
 2858:     if ($type eq 'symb') {
 2859:         my ($symb,$mapid,$resid,$title,$ufn) = split(':',$labeldata);
 2860:         $ufn   = 'default' if (!defined($ufn) || $ufn eq '');
 2861:         $ufn   = &Apache::lonnet::unescape($ufn);
 2862:         $symb  = &Apache::lonnet::unescape($symb);
 2863:         $title = &Apache::lonnet::unescape($title);
 2864:         $result = '<a href="/adm/assesscalc?usymb='.$symb.
 2865:             '&uname='.$self->{'uname'}.'&udom='.$self->{'udom'}.
 2866:                 '&ufn='.$ufn.
 2867:                     '&mapid='.$mapid.'&resid='.$resid.'">'.$title.'</a>';
 2868:     } elsif ($type eq 'student') {
 2869:         my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
 2870:         if ($fullname =~ /^\s*$/) {
 2871:             $fullname = $sname.'@'.$sdom;
 2872:         }
 2873:         $result ='<a href="/adm/studentcalc?uname='.$sname.
 2874:             '&udom='.$sdom.'">';
 2875:         $result.=$section.'&nbsp;'.$id."&nbsp;".$fullname.'</a>';
 2876:     } elsif ($type eq 'parameter') {
 2877:         $result = $labeldata;
 2878:     } else {
 2879:         $result = '<b><font size=+1>'.$rowlabel.'</font></b>';
 2880:     }
 2881:     return $result;
 2882: }
 2883: 
 2884: sub format_csv_rowlabel {
 2885:     my $self = shift;
 2886:     my $rowlabel = shift;
 2887:     return '' if ($rowlabel eq '');
 2888:     my ($type,$labeldata) = split(':',$rowlabel,2);
 2889:     my $result = '';
 2890:     if ($type eq 'symb') {
 2891:         my ($symb,$mapid,$resid,$title,$ufn) = split(':',$labeldata);
 2892:         $ufn   = &Apache::lonnet::unescape($ufn);
 2893:         $symb  = &Apache::lonnet::unescape($symb);
 2894:         $title = &Apache::lonnet::unescape($title);
 2895:         $result = $title;
 2896:     } elsif ($type eq 'student') {
 2897:         my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
 2898:         $result = join('","',($sname,$sdom,$fullname,$section,$id));
 2899:     } elsif ($type eq 'parameter') {
 2900:         $labeldata =~ s/<br>/ /g;
 2901:         $result = $labeldata;
 2902:     } else {
 2903:         $result = $rowlabel;
 2904:     }
 2905:     return '"'.$result.'"';
 2906: }
 2907: 
 2908: sub format_excel_rowlabel {
 2909:     my $self = shift;
 2910:     my $rowlabel = shift;
 2911:     return '' if ($rowlabel eq '');
 2912:     my ($type,$labeldata) = split(':',$rowlabel,2);
 2913:     my $result = '';
 2914:     if ($type eq 'symb') {
 2915:         my ($symb,$mapid,$resid,$title,$ufn) = split(':',$labeldata);
 2916:         $ufn   = &Apache::lonnet::unescape($ufn);
 2917:         $symb  = &Apache::lonnet::unescape($symb);
 2918:         $title = &Apache::lonnet::unescape($title);
 2919:         $result = $title;
 2920:     } elsif ($type eq 'student') {
 2921:         my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
 2922:         $section = '' if (! defined($section));
 2923:         $id      = '' if (! defined($id));
 2924:         my @Data = ($sname,$sdom,$fullname,$section,$id);
 2925:         $result = \@Data;
 2926:     } elsif ($type eq 'parameter') {
 2927:         $labeldata =~ s/<br>/ /g;
 2928:         $result = $labeldata;
 2929:     } else {
 2930:         $result = $rowlabel;
 2931:     }
 2932:     return $result;
 2933: }
 2934: 
 2935: # ---------------------------------------------- Update rows for course listing
 2936: sub updateclasssheet {
 2937:     my $self = shift;
 2938:     my $cnum  =$self->{'cnum'};
 2939:     my $cdom  =$self->{'cdom'};
 2940:     my $cid   =$self->{'cid'};
 2941:     my $chome =$self->{'chome'};
 2942:     #
 2943:     %Section = ();
 2944:     #
 2945:     # Read class list and row labels
 2946:     my $classlist = &Apache::loncoursedata::get_classlist();
 2947:     if (! defined($classlist)) {
 2948:         return 'Could not access course classlist';
 2949:     } 
 2950:     #
 2951:     my %currentlist=();
 2952:     foreach my $student (keys(%$classlist)) {
 2953:         my ($studentDomain,$studentName,$end,$start,$id,$studentSection,
 2954:             $fullname,$status)   =   @{$classlist->{$student}};
 2955:         $Section{$studentName.':'.$studentDomain} = $studentSection;
 2956:         if ($ENV{'form.Status'} eq $status || $ENV{'form.Status'} eq 'Any') {
 2957:             $currentlist{$student}=join(':',('student',$studentName,
 2958:                                              $studentDomain,$fullname,
 2959:                                              $studentSection,$id));
 2960:         }
 2961:     }
 2962:     #
 2963:     # Find discrepancies between the course row table and this
 2964:     #
 2965:     my %f=$self->formulas();
 2966:     my $changed=0;
 2967:     #
 2968:     $self->{'maxrow'}=0;
 2969:     my %existing=();
 2970:     #
 2971:     # Now obsolete rows
 2972:     foreach my $rownum ($self->rows()) {
 2973:         my $cell = 'A'.$rownum;
 2974:         if ($rownum > $self->{'maxrow'}) {
 2975:             $self->{'maxrow'}= $rownum;
 2976:         }
 2977:         $existing{$f{$cell}}=1;
 2978:         if (! defined($currentlist{$f{$cell}}) && ($f{$cell}=~/^(~~~|---)/)) {
 2979:             $f{$cell}='!!! Obsolete';
 2980:             $changed=1;
 2981:         }
 2982:     }
 2983:     #
 2984:     # New and unknown keys
 2985:     foreach my $student (sort keys(%currentlist)) {
 2986:         next if ($existing{$student});
 2987:         $changed=1;
 2988:         $self->{'maxrow'}++;
 2989:         $f{'A'.$self->{'maxrow'}}=$student;
 2990:     }
 2991:     $self->formulas(\%f) if ($changed);
 2992:     #
 2993:     $self->rowlabels(\%currentlist);
 2994: }
 2995: 
 2996: # ----------------------------------- Update rows for student and assess sheets
 2997: sub get_student_rowlabels {
 2998:     my $self = shift;
 2999:     #
 3000:     my %course_db;
 3001:     #
 3002:     my $stype = $self->{'type'};
 3003:     my $uname = $self->{'uname'};
 3004:     my $udom  = $self->{'udom'};
 3005:     #
 3006:     $self->{'rowlabel'} = {};
 3007:     #
 3008:     my $identifier =$self->{'coursefilename'}.'_'.$stype;
 3009:     if  (exists($rowlabel_cache{$identifier})) {
 3010:         my %tmp = split(/___;___/,$rowlabel_cache{$identifier});
 3011:         $self->rowlabels(\%tmp);
 3012:     } else {
 3013:         # Get the data and store it in the cache
 3014:         # Tie hash
 3015:         tie(%course_db,'GDBM_File',$self->{'coursefilename'}.'.db',
 3016:             &GDBM_READER(),0640);
 3017:         if (! tied(%course_db)) {
 3018:             return 'Could not access course data';
 3019:         }
 3020:         #
 3021:         my %assesslist = ();
 3022:         foreach ('Feedback','Evaluation','Tutoring','Discussion') {
 3023:             my $symb = '_'.lc($_);
 3024:             $assesslist{$symb} = join(':',('symb',$symb,0,0,
 3025:                                            &Apache::lonnet::escape($_)));
 3026:         }
 3027:         #
 3028:         while (my ($key,$srcf) = each(%course_db)) {
 3029:             next if ($key !~ /^src_(\d+)\.(\d+)$/);
 3030:             my $mapid = $1;
 3031:             my $resid = $2;
 3032:             my $id   = $mapid.'.'.$resid;
 3033:             if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
 3034:                 my $symb=
 3035:                     &Apache::lonnet::declutter($course_db{'map_id_'.$mapid}).
 3036:                         '___'.$resid.'___'.&Apache::lonnet::declutter($srcf);
 3037:                 $assesslist{$symb} ='symb:'.&Apache::lonnet::escape($symb).':'
 3038:                     .$mapid.':'.$resid.':'.
 3039:                         &Apache::lonnet::escape($course_db{'title_'.$id});
 3040:             }
 3041:         }
 3042:         untie(%course_db);
 3043:         # Store away the data
 3044:         $self->{'rowlabel'} = \%assesslist;
 3045:         $rowlabel_cache{$identifier}=join('___;___',%{$self->{'rowlabel'}});
 3046:     }
 3047:     
 3048: }
 3049: 
 3050: sub get_assess_rowlabels {
 3051:     my $self = shift;
 3052:     #
 3053:     my %course_db;
 3054:     #
 3055:     my $stype = $self->{'type'};
 3056:     my $uname = $self->{'uname'};
 3057:     my $udom  = $self->{'udom'};
 3058:     my $usymb = $self->{'usymb'};
 3059:     #
 3060:     $self->rowlabels({});
 3061:     my $identifier =$self->{'coursefilename'}.'_'.$stype.'_'.$usymb;
 3062:     #
 3063:     if (exists($rowlabel_cache{$identifier})) {
 3064:         my %tmp = split('___;___',$rowlabel_cache{$identifier});
 3065:         $self->rowlabels(\%tmp);
 3066:     } else {
 3067:         # Get the data and store it in the cache
 3068:         # Tie hash
 3069:         tie(%course_db,'GDBM_File',$self->{'coursefilename'}.'.db',
 3070:             &GDBM_READER(),0640);
 3071:         if (! tied(%course_db)) {
 3072:             return 'Could not access course data';
 3073:         }
 3074:         #
 3075:         my %parameter_labels=
 3076:             ('timestamp' => 
 3077:                  'parameter:Timestamp of Last Transaction<br>timestamp',
 3078:              'subnumber' =>
 3079:                  'parameter:Number of Submissions<br>subnumber',
 3080:              'tutornumber' =>
 3081:                  'parameter:Number of Tutor Responses<br>tutornumber',
 3082:              'totalpoints' =>
 3083:                  'parameter:Total Points Granted<br>totalpoints');
 3084:         while (my ($key,$srcf) = each(%course_db)) {
 3085:             next if ($key !~ /^src_(\d+)\.(\d+)$/);
 3086:             my $mapid = $1;
 3087:             my $resid = $2;
 3088:             my $id   = $mapid.'.'.$resid;
 3089:             if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
 3090:                 # Loop through the metadata for this key
 3091:                 my @Metadata = split(/,/,
 3092:                                      &Apache::lonnet::metadata($srcf,'keys'));
 3093:                 foreach my $key (@Metadata) {
 3094:                     next if ($key !~ /^(stores|parameter)_/);
 3095:                     my $display=
 3096:                         &Apache::lonnet::metadata($srcf,$key.'.display');
 3097:                     unless ($display) {
 3098:                         $display.=
 3099:                             &Apache::lonnet::metadata($srcf,$key.'.name');
 3100:                     }
 3101:                     $display.='<br>'.$key;
 3102:                     $parameter_labels{$key}='parameter:'.$display;
 3103:                 } # end of foreach
 3104:             }
 3105:         }
 3106:         untie(%course_db);
 3107:         # Store away the results
 3108:         $self->rowlabels(\%parameter_labels);
 3109:         $rowlabel_cache{$identifier}=join('___;___',%parameter_labels);
 3110:     }
 3111: }
 3112: 
 3113: sub updatestudentassesssheet {
 3114:     my $self = shift;
 3115:     if ($self->{'type'} eq 'studentcalc') {
 3116:         $self->get_student_rowlabels();
 3117:     } else {
 3118:         $self->get_assess_rowlabels();
 3119:     }
 3120:     # Determine if any of the information has changed
 3121:     my %f=$self->formulas();
 3122:     my $changed=0;
 3123:     $self->{'maxrow'} = 0;
 3124:     my %existing=();
 3125:     # Now obsolete rows
 3126:     foreach my $rownum ($self->rows()) {
 3127:         my $cell = 'A'.$rownum;
 3128:         my $formula = $f{$cell};
 3129:         $self->{'maxrow'} = $rownum if ($rownum > $self->{'maxrow'});
 3130:         my ($usy,$ufn)=split(/__&&&\__/,$formula);
 3131:         $existing{$usy}=1;
 3132:         if ( ! exists($self->{'rowlabel'}->{$usy})  ||
 3133:              ! defined($self->{'rowlabel'}->{$usy}) ||
 3134:              ($formula =~ /^(~~~|---)/) ||
 3135:              ($formula =~ /^\s*$/)) {
 3136:             $f{$cell}='!!! Obsolete';
 3137:             $changed=1;
 3138:         }
 3139:     }
 3140:     # New and unknown keys
 3141:     my %keys_hates_me = $self->rowlabels();
 3142:     foreach (keys(%keys_hates_me)) {
 3143:         unless ($existing{$_}) {
 3144:             $changed=1;
 3145:             $self->{'maxrow'}++;
 3146:             $f{'A'.$self->{'maxrow'}}=$_;
 3147:         }
 3148:     }
 3149:     $self->formulas(\%f) if ($changed);
 3150: #    $self->dump_formulas_to_log();    
 3151: }
 3152: 
 3153: # ------------------------------------------------ Load data for one assessment
 3154: sub loadstudent{
 3155:     my $self = shift;
 3156:     my ($r,$c)=@_;
 3157:     my %constants = ();
 3158:     my %formulas  = $self->formulas();
 3159:     $cachedassess = $self->{'uname'}.':'.$self->{'udom'};
 3160:     # Get ALL the student preformance data
 3161:     my @tmp = &Apache::loncoursedata::get_current_state($self->{'uname'},
 3162:                                                         $self->{'udom'},
 3163:                                                         undef,
 3164:                                                         $self->{'cid'});
 3165:     if ((scalar @tmp > 0) && ($tmp[0] !~ /^error:/)) {
 3166:         %cachedstores = @tmp;
 3167:     }
 3168:     undef @tmp;
 3169:     # debugging code
 3170:     # $self->dump_hash_to_log(\%cachedstores);
 3171:     #
 3172:     my @assessdata=();
 3173:     foreach my $row ($self->rows()) {
 3174:         my $cell = 'A'.$row;
 3175:         my $value = $formulas{$cell};
 3176:         if(defined($c) && ($c->aborted())) {
 3177:             last;
 3178:         }
 3179:         next if ($value =~ /^[!~-]/);
 3180:         my ($usy,$ufn)=split(/__&&&\__/,$value);
 3181:         @assessdata=$self->exportsheet($self->{'uname'},
 3182:                                         $self->{'udom'},
 3183:                                         'assesscalc',$usy,$ufn,$r);
 3184:         my $index=0;
 3185:         foreach my $col ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 3186:                          'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 3187:             if (defined($assessdata[$index])) {
 3188:                 if ($assessdata[$index]=~/\D/) {
 3189:                     $constants{$col.$row}="'".$assessdata[$index]."'";
 3190:                 } else {
 3191:                     $constants{$col.$row}=$assessdata[$index];
 3192:                 }
 3193:                 $formulas{$col.$row}='import' if ($col ne 'A');
 3194:             }
 3195:             $index++;
 3196:         }
 3197:     }
 3198:     $cachedassess='';
 3199:     undef %cachedstores;
 3200:     $self->formulas(\%formulas);
 3201:     $self->constants(\%constants);
 3202: }
 3203: 
 3204: # --------------------------------------------------- Load Course Sheet
 3205: #
 3206: sub loadcourse {
 3207:     my $self = shift;
 3208:     my ($r,$c)=@_;
 3209:     #
 3210:     my %constants=();
 3211:     my %formulas=$self->formulas();
 3212:     #
 3213:     my $total=0;
 3214:     foreach ($self->rows()) {
 3215:         $total++ if ($formulas{'A'.$_} !~ /^[!~-]/);
 3216:     }
 3217: 
 3218:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,
 3219: 	      'Spreadsheet Status','Spreadsheet Calculation Progress', $total);
 3220:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
 3221: 					  'Processing Course Assessment Data');
 3222: 
 3223:     # It would be nice to load in the classlist and assessment info at this 
 3224:     # point, before attacking the student spreadsheets.
 3225:     foreach my $row ($self->rows()) {
 3226:         if(defined($c) && ($c->aborted())) {
 3227:             last;
 3228:         }
 3229:         my $cell = 'A'.$row;
 3230:         next if ($formulas{$cell}=~/^[\!\~\-]/);
 3231:         my ($sname,$sdom) = split(':',$formulas{$cell});
 3232:         my $started = time;
 3233:         my @studentdata=$self->exportsheet($sname,$sdom,'studentcalc',
 3234:                                      undef,undef,$r);
 3235:         undef %userrdatas;
 3236: 	&Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
 3237: 						 'last student');
 3238:         my $index=0;
 3239:         foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 3240:                  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 3241:             if (defined($studentdata[$index])) {
 3242:                 my $col=$_;
 3243:                 if ($studentdata[$index]=~/\D/) {
 3244:                     $constants{$col.$row}="'".$studentdata[$index]."'";
 3245:                 } else {
 3246:                     $constants{$col.$row}=$studentdata[$index];
 3247:                 }
 3248:                 unless ($col eq 'A') { 
 3249:                     $formulas{$col.$row}='import';
 3250:                 }
 3251:             } 
 3252:             $index++;
 3253:         }
 3254:     }
 3255:     $self->formulas(\%formulas);
 3256:     $self->constants(\%constants);
 3257:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
 3258: }
 3259: 
 3260: # ------------------------------------------------ Load data for one assessment
 3261: #
 3262: sub loadassessment {
 3263:     my $self = shift;
 3264:     my ($r,$c)=@_;
 3265: 
 3266:     my $uhome = $self->{'uhome'};
 3267:     my $uname = $self->{'uname'};
 3268:     my $udom  = $self->{'udom'};
 3269:     my $symb  = $self->{'usymb'};
 3270:     my $cid   = $self->{'cid'};
 3271:     my $cnum  = $self->{'cnum'};
 3272:     my $cdom  = $self->{'cdom'};
 3273:     my $chome = $self->{'chome'};
 3274:     my $csec  = $self->{'csec'};
 3275: 
 3276:     my $namespace;
 3277:     unless ($namespace=$cid) { return ''; }
 3278:     # Get stored values
 3279:     my %returnhash=();
 3280:     if ($cachedassess eq $uname.':'.$udom) {
 3281:         #
 3282:         # get data out of the dumped stores
 3283:         # 
 3284:         if (exists($cachedstores{$symb})) {
 3285:             %returnhash = %{$cachedstores{$symb}};
 3286:         } else {
 3287:             %returnhash = ();
 3288:         }
 3289:     } else {
 3290:         #
 3291:         # restore individual
 3292:         #
 3293:         %returnhash = &Apache::lonnet::restore($symb,$namespace,$udom,$uname);
 3294:     }
 3295:     #
 3296:     # returnhash now has all stores for this resource
 3297:     # convert all "_" to "." to be able to use libraries, multiparts, etc
 3298:     #
 3299:     # This is dumb.  It is also necessary :(
 3300:     my @oldkeys=keys %returnhash;
 3301:     #
 3302:     foreach my $name (@oldkeys) {
 3303:         my $value=$returnhash{$name};
 3304:         delete $returnhash{$name};
 3305:         $name=~s/\_/\./g;
 3306:         $returnhash{$name}=$value;
 3307:     }
 3308:     # initialize coursedata and userdata for this user
 3309:     undef %courseopt;
 3310:     undef %useropt;
 3311: 
 3312:     my $userprefix=$uname.'_'.$udom.'_';
 3313: 
 3314:     unless ($uhome eq 'no_host') { 
 3315:         # Get coursedata
 3316:         unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
 3317:             my %Tmp = &Apache::lonnet::dump('resourcedata',$cdom,$cnum);
 3318:             $courserdatas{$cid}=\%Tmp;
 3319:             $courserdatas{$cid.'.last_cache'}=time;
 3320:         }
 3321:         while (my ($name,$value) = each(%{$courserdatas{$cid}})) {
 3322:             $courseopt{$userprefix.$name}=$value;
 3323:         }
 3324:         # Get userdata (if present)
 3325:         unless ((time-$userrdatas{$uname.'@'.$udom.'.last_cache'})<240) {
 3326:             my %Tmp = &Apache::lonnet::dump('resourcedata',$udom,$uname);
 3327:             $userrdatas{$cid} = \%Tmp;
 3328:             # Most of the time the user does not have a 'resourcedata.db' 
 3329:             # file.  We need to cache that we got nothing instead of bothering
 3330:             # with requesting it every time.
 3331:             $userrdatas{$uname.'@'.$udom.'.last_cache'}=time;
 3332:         }
 3333:         while (my ($name,$value) = each(%{$userrdatas{$cid}})) {
 3334:             $useropt{$userprefix.$name}=$value;
 3335:         }
 3336:     }
 3337:     # now courseopt, useropt initialized for this user and course
 3338:     # (used by parmval)
 3339:     #
 3340:     # Load keys for this assessment only
 3341:     #
 3342:     my %thisassess=();
 3343:     my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
 3344:     foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
 3345:         $thisassess{$_}=1;
 3346:     } 
 3347:     #
 3348:     # Load parameters
 3349:     #
 3350:     my %c=();
 3351:     if (tie(%parmhash,'GDBM_File',
 3352:             $self->{'coursefilename'}.'_parms.db',&GDBM_READER(),0640)) {
 3353:         my %f=$self->formulas();
 3354:         foreach my $row ($self->rows())  {
 3355:             my $cell = 'A'.$row;
 3356:             my $formula = $self->formula($cell);
 3357:             next if ($formula =~/^[\!\~\-]/);
 3358:             if ($formula =~ /^parameter/) {
 3359:                 if (defined($thisassess{$formula})) {
 3360:                     my $val   = &parmval($formula,$symb,$uname,$udom,$csec);
 3361:                     $c{$cell}    = $val;
 3362:                     $c{$formula} = $val;
 3363:                 }
 3364:             } else {
 3365:                 my $ckey=$formula;
 3366:                 $formula=~s/^stores\_/resource\./;
 3367:                 $formula=~s/\_/\./g;
 3368:                 $c{$cell}=$returnhash{$formula};
 3369:                 $c{$ckey}=$returnhash{$formula};
 3370:             }
 3371:         }
 3372:         untie(%parmhash);
 3373:     }
 3374:     $self->constants(\%c);
 3375: }
 3376: 
 3377: 
 3378: # =============================================== Update information in a sheet
 3379: #
 3380: # Add new users or assessments, etc.
 3381: #
 3382: sub updatesheet {
 3383:     my $self = shift;
 3384:     if ($self->{'type'} eq 'classcalc') {
 3385:         return $self->updateclasssheet();
 3386:     } else {
 3387:         return $self->updatestudentassesssheet();
 3388:     }
 3389: }
 3390: 
 3391: # =================================================== Load the rows for a sheet
 3392: #
 3393: # Import the data for rows
 3394: #
 3395: sub loadrows {
 3396:     my $self = shift;
 3397:     my ($r)=@_;
 3398:     my $c = $r->connection;
 3399:     if ($self->{'type'} eq 'classcalc') {
 3400:         $self->loadcourse($r,$c);
 3401:     } elsif ($self->{'type'} eq 'studentcalc') {
 3402:         $self->loadstudent($r,$c);
 3403:     } else {
 3404:         $self->loadassessment($r,$c);
 3405:     }
 3406: }
 3407: 
 3408: # ============================================================== Export handler
 3409: # exportsheet
 3410: # returns the export row for a spreadsheet.
 3411: #
 3412: sub exportsheet {
 3413:     my $self = shift;
 3414:     my ($uname,$udom,$stype,$usymb,$fn,$r)=@_;
 3415:     my $flag = 0;
 3416:     $uname = $uname || $self->{'uname'};
 3417:     $udom  = $udom  || $self->{'udom'};
 3418:     $stype = $stype || $self->{'type'};
 3419:     my @exportarr=();
 3420:     # This handles the assessment sheets for '_feedback', etc
 3421:     if (defined($usymb) && ($usymb=~/^\_(\w+)/) && 
 3422:         (!defined($fn) || $fn eq '')) {
 3423:         $fn='default_'.$1;
 3424:     }
 3425:     #
 3426:     # Check if cached
 3427:     #
 3428:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3429:     my $found='';
 3430:     if ($Apache::lonspreadsheet::oldsheets{$key}) {
 3431:         foreach (split(/___&\___/,$Apache::lonspreadsheet::oldsheets{$key})) {
 3432:             my ($name,$value)=split(/___=___/,$_);
 3433:             if ($name eq $fn) {
 3434:                 $found=$value;
 3435:             }
 3436:         }
 3437:     }
 3438:     unless ($found) {
 3439:         &cachedssheets($self,$uname,$udom);
 3440:         if ($Apache::lonspreadsheet::oldsheets{$key}) {
 3441:             foreach (split(/___&\___/,$Apache::lonspreadsheet::oldsheets{$key})) {
 3442:                 my ($name,$value)=split(/___=___/,$_);
 3443:                 if ($name eq $fn) {
 3444:                     $found=$value;
 3445:                 }
 3446:             } 
 3447:         }
 3448:     }
 3449:     #
 3450:     # Check if still valid
 3451:     #
 3452:     if ($found) {
 3453:         if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
 3454:             $found='';
 3455:         }
 3456:     }
 3457:     if ($found) {
 3458:         #
 3459:         # Return what was cached
 3460:         #
 3461:         @exportarr=split(/___;___/,$found);
 3462:         return @exportarr;
 3463:     }
 3464:     #
 3465:     # Not cached
 3466:     #
 3467:     my $newsheet = Apache::lonspreadsheet::Spreadsheet->new($uname,$udom,
 3468:                                                          $stype,$usymb);
 3469:     $newsheet->readsheet($fn);
 3470:     $newsheet->updatesheet();
 3471:     $newsheet->loadrows($r);
 3472:     $newsheet->calcsheet(); 
 3473:     @exportarr=$newsheet->exportdata();
 3474:     ##
 3475:     ## Store now
 3476:     ##
 3477:     #
 3478:     # load in the old value
 3479:     #
 3480:     my %currentlystored=();
 3481:     if ($stype eq 'studentcalc') {
 3482:         my @tmp = &Apache::lonnet::get('nohist_calculatedsheets',
 3483:                                        [$key],
 3484:                                        $self->{'cdom'},$self->{'cnum'});
 3485:         if ($tmp[0]!~/^error/) {
 3486:             # We only got one key, so we will access it directly.
 3487:             foreach (split('___&___',$tmp[1])) {
 3488:                 my ($key,$value) = split('___=___',$_);
 3489:                 $key = '' if (! defined($key));
 3490:                 $currentlystored{$key} = $value;
 3491:             }
 3492:         }
 3493:     } else {
 3494:         my @tmp = &Apache::lonnet::get('nohist_calculatedsheets_'.
 3495:                                        $self->{'cid'},[$key],
 3496:                                        $self->{'udom'},$self->{'uname'});
 3497:         if ($tmp[0]!~/^error/) {
 3498:             # We only got one key, so we will access it directly.
 3499:             foreach (split('___&___',$tmp[1])) {
 3500:                 my ($key,$value) = split('___=___',$_);
 3501:                 $key = '' if (! defined($key));
 3502:                 $currentlystored{$key} = $value;
 3503:             }
 3504:         }
 3505:     }
 3506:     #
 3507:     # Add the new line
 3508:     #
 3509:     $currentlystored{$fn}=join('___;___',@exportarr);
 3510:     #
 3511:     # Stick everything back together
 3512:     #
 3513:     my $newstore='';
 3514:     foreach (keys(%currentlystored)) {
 3515:         if ($newstore) { $newstore.='___&___'; }
 3516:         $newstore.=$_.'___=___'.$currentlystored{$_};
 3517:     }
 3518:     my $now=time;
 3519:     #
 3520:     # Store away the new value
 3521:     #
 3522:     my $timekey = $key.'.time';
 3523:     if ($stype eq 'studentcalc') {
 3524:         my $result = &Apache::lonnet::put('nohist_calculatedsheets',
 3525:                                           { $key     => $newstore,
 3526:                                             $timekey => $now },
 3527:                                           $self->{'cdom'},
 3528:                                           $self->{'cnum'});
 3529:     } else {
 3530:         my $result = &Apache::lonnet::put('nohist_calculatedsheets_'.$self->{'cid'},
 3531:                                           { $key     => $newstore,
 3532:                                             $timekey => $now },
 3533:                                           $self->{'udom'},
 3534:                                           $self->{'uname'});
 3535:     }
 3536:     return @exportarr;
 3537: }
 3538: 
 3539: 1;
 3540: 
 3541: __END__
 3542: 
 3543: 

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