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

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

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