File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.179: download - view: text, annotated - select for diffs
Tue May 27 15:50:30 2003 UTC (21 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #1496: long-running spreadsheet did not register with Remote before
completely loaded. Produces "extra windows".

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

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