File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.174: download - view: text, annotated - select for diffs
Fri Mar 7 04:20:20 2003 UTC (21 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- cascading up the part list now works
- accepts parts with : and - in them

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

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