Annotation of loncom/interface/lonspreadsheet.pm, revision 1.172

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

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