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

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

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