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

1.79      matthew     1: #
1.100   ! matthew     2: # $Id: lonspreadsheet.pm,v 1.99 2002/08/12 18:21:42 albertel 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.15      www        29: # 11/11,11/15,11/27,12/04,12/05,12/06,12/07,
1.23      www        30: # 12/08,12/09,12/11,12/12,12/15,12/16,12/18,12/19,12/30,
1.39      www        31: # 01/01/01,02/01,03/01,19/01,20/01,22/01,
1.47      www        32: # 03/05,03/08,03/10,03/12,03/13,03/15,03/17,
1.55      www        33: # 03/19,03/20,03/21,03/27,04/05,04/09,
1.69      www        34: # 07/09,07/14,07/21,09/01,09/10,9/11,9/12,9/13,9/14,9/17,
1.77      www        35: # 10/16,10/17,10/20,11/05,11/28,12/27 Gerd Kortemeyer
1.78      matthew    36: # 01/14/02 Matthew
1.80      matthew    37: # 02/04/02 Matthew
                     38: 
                     39: # POD required stuff:
                     40: 
                     41: =head1 NAME
                     42: 
                     43: lonspreadsheet
                     44: 
                     45: =head1 SYNOPSIS
                     46: 
                     47: Spreadsheet interface to internal LON-CAPA data
                     48: 
                     49: =head1 DESCRIPTION
                     50: 
                     51: Lonspreadsheet provides course coordinators the ability to manage their
                     52: students grades online.  The students are able to view their own grades, but
                     53: not the grades of their peers.  The spreadsheet is highly customizable,
                     54: offering the ability to use Perl code to manipulate data, as well as many
                     55: built-in functions.
                     56: 
                     57: 
                     58: =head2 Functions available to user of lonspreadsheet
                     59: 
                     60: =over 4
                     61: 
                     62: =cut
1.1       www        63: 
                     64: package Apache::lonspreadsheet;
1.36      www        65:             
1.1       www        66: use strict;
                     67: use Safe;
1.3       www        68: use Safe::Hole;
1.1       www        69: use Opcode;
                     70: use Apache::lonnet;
1.7       www        71: use Apache::Constants qw(:common :http);
1.19      www        72: use GDBM_File;
1.3       www        73: use HTML::TokeParser;
1.98      matthew    74: use Apache::lonhtmlcommon;
1.11      www        75: #
1.44      www        76: # Caches for previously calculated spreadsheets
                     77: #
                     78: 
                     79: my %oldsheets;
1.46      www        80: my %loadedcaches;
1.47      www        81: my %expiredates;
1.44      www        82: 
                     83: #
1.39      www        84: # Cache for stores of an individual user
                     85: #
                     86: 
                     87: my $cachedassess;
                     88: my %cachedstores;
                     89: 
                     90: #
1.11      www        91: # These cache hashes need to be independent of user, resource and course
1.27      www        92: # (user and course can/should be in the keys)
1.11      www        93: #
1.33      www        94: 
                     95: my %spreadsheets;
                     96: my %courserdatas;
                     97: my %userrdatas;
                     98: my %defaultsheets;
1.35      www        99: my %updatedata;
1.27      www       100: 
1.11      www       101: #
                    102: # These global hashes are dependent on user, course and resource, 
                    103: # and need to be initialized every time when a sheet is calculated
                    104: #
                    105: my %courseopt;
                    106: my %useropt;
                    107: my %parmhash;
                    108: 
1.95      www       109: #
                    110: # Some hashes for stats on timing and performance
                    111: #
                    112: 
                    113: my %starttimes;
                    114: my %usedtimes;
1.96      www       115: my %numbertimes;
1.95      www       116: 
1.28      www       117: # Stuff that only the screen handler can know
                    118: 
                    119: my $includedir;
                    120: my $tmpdir;
                    121: 
1.5       www       122: # =============================================================================
                    123: # ===================================== Implements an instance of a spreadsheet
1.4       www       124: 
                    125: sub initsheet {
1.36      www       126:     my $safeeval = new Safe(shift);
1.4       www       127:     my $safehole = new Safe::Hole;
                    128:     $safeeval->permit("entereval");
                    129:     $safeeval->permit(":base_math");
                    130:     $safeeval->permit("sort");
                    131:     $safeeval->deny(":base_io");
                    132:     $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
1.96      www       133:     $safeeval->share('$@');
1.4       www       134:     my $code=<<'ENDDEFS';
                    135: # ---------------------------------------------------- Inside of the safe space
                    136: 
1.3       www       137: #
                    138: # f: formulas
1.4       www       139: # t: intermediate format (variable references expanded)
                    140: # v: output values
1.6       www       141: # c: preloaded constants (A-column)
                    142: # rl: row label
1.55      www       143: # os: other spreadsheets (for student spreadsheet only)
1.3       www       144: 
1.36      www       145: undef %v; 
                    146: undef %t;
                    147: undef %f;
                    148: undef %c;
                    149: undef %rl;
1.55      www       150: undef @os;
                    151: 
1.6       www       152: $maxrow=0;
1.5       www       153: $sheettype='';
1.27      www       154: 
                    155: # filename/reference of the sheet
                    156: 
1.5       www       157: $filename='';
1.1       www       158: 
1.27      www       159: # user data
                    160: $uname='';
                    161: $uhome='';
                    162: $udom='';
                    163: 
                    164: # course data
                    165: 
                    166: $csec='';
                    167: $chome='';
                    168: $cnum='';
                    169: $cdom='';
1.28      www       170: $cid='';
1.29      www       171: $cfn='';
1.27      www       172: 
                    173: # symb
                    174: 
                    175: $usymb='';
                    176: 
1.95      www       177: # error messages
                    178: 
                    179: $errormsg='';
                    180: 
1.1       www       181: sub mask {
                    182:     my ($lower,$upper)=@_;
                    183: 
1.7       www       184:     $lower=~/([A-Za-z]|\*)(\d+|\*)/;
1.1       www       185:     my $la=$1;
                    186:     my $ld=$2;
                    187: 
1.7       www       188:     $upper=~/([A-Za-z]|\*)(\d+|\*)/;
1.1       www       189:     my $ua=$1;
                    190:     my $ud=$2;
                    191:     my $alpha='';
                    192:     my $num='';
                    193: 
                    194:     if (($la eq '*') || ($ua eq '*')) {
1.7       www       195:        $alpha='[A-Za-z]';
1.1       www       196:     } else {
1.7       www       197:        if (($la=~/[A-Z]/) && ($ua=~/[A-Z]/) ||
                    198:            ($la=~/[a-z]/) && ($ua=~/[a-z]/)) {
                    199:           $alpha='['.$la.'-'.$ua.']';
                    200:        } else {
                    201:           $alpha='['.$la.'-Za-'.$ua.']';
                    202:        }
1.1       www       203:     }   
                    204: 
                    205:     if (($ld eq '*') || ($ud eq '*')) {
                    206: 	$num='\d+';
                    207:     } else {
                    208:         if (length($ld)!=length($ud)) {
                    209:            $num.='(';
1.78      matthew   210: 	   foreach ($ld=~m/\d/g) {
1.1       www       211:               $num.='['.$_.'-9]';
1.78      matthew   212: 	   }
1.1       www       213:            if (length($ud)-length($ld)>1) {
                    214:               $num.='|\d{'.(length($ld)+1).','.(length($ud)-1).'}';
                    215: 	   }
                    216:            $num.='|';
1.78      matthew   217:            foreach ($ud=~m/\d/g) {
1.1       www       218:                $num.='[0-'.$_.']';
1.78      matthew   219:            }
1.1       www       220:            $num.=')';
                    221:        } else {
                    222:            my @lda=($ld=~m/\d/g);
                    223:            my @uda=($ud=~m/\d/g);
1.7       www       224:            my $i; $j=0; $notdone=1;
                    225:            for ($i=0;($i<=$#lda)&&($notdone);$i++) {
1.1       www       226:                if ($lda[$i]==$uda[$i]) {
                    227: 		   $num.=$lda[$i];
                    228:                    $j=$i;
1.7       www       229:                } else {
                    230:                    $notdone=0;
1.1       www       231:                }
                    232:            }
                    233:            if ($j<$#lda-1) {
                    234: 	       $num.='('.$lda[$j+1];
                    235:                for ($i=$j+2;$i<=$#lda;$i++) {
                    236:                    $num.='['.$lda[$i].'-9]';
                    237:                }
                    238:                if ($uda[$j+1]-$lda[$j+1]>1) {
                    239: 		   $num.='|['.($lda[$j+1]+1).'-'.($uda[$j+1]-1).']\d{'.
                    240:                    ($#lda-$j-1).'}';
                    241:                }
                    242: 	       $num.='|'.$uda[$j+1];
                    243:                for ($i=$j+2;$i<=$#uda;$i++) {
                    244:                    $num.='[0-'.$uda[$i].']';
                    245:                }
                    246:                $num.=')';
                    247:            } else {
1.7       www       248:                if ($lda[$#lda]!=$uda[$#uda]) {
                    249:                   $num.='['.$lda[$#lda].'-'.$uda[$#uda].']';
                    250: 	       }
1.1       www       251:            }
                    252:        }
                    253:     }
1.4       www       254:     return '^'.$alpha.$num."\$";
1.80      matthew   255: }
                    256: 
                    257: #-------------------------------------------------------
                    258: 
                    259: =item UWCALC(hashname,modules,units,date) 
                    260: 
                    261: returns the proportion of the module 
                    262: weights not previously completed by the student.
                    263: 
                    264: =over 4
                    265: 
                    266: =item hashname 
                    267: 
                    268: name of the hash the module dates have been inserted into
                    269: 
                    270: =item modules 
                    271: 
                    272: reference to a cell which contains a comma deliminated list of modules 
                    273: covered by the assignment.
                    274: 
                    275: =item units 
                    276: 
                    277: reference to a cell which contains a comma deliminated list of module 
                    278: weights with respect to the assignment
                    279: 
                    280: =item date 
                    281: 
                    282: reference to a cell which contains the date the assignment was completed.
                    283: 
                    284: =back 
                    285: 
                    286: =cut
                    287: 
                    288: #-------------------------------------------------------
                    289: sub UWCALC {
                    290:     my ($hashname,$modules,$units,$date) = @_;
                    291:     my @Modules = split(/,/,$modules);
                    292:     my @Units   = split(/,/,$units);
                    293:     my $total_weight;
                    294:     foreach (@Units) {
                    295: 	$total_weight += $_;
                    296:     }
                    297:     my $usum=0;
                    298:     for (my $i=0; $i<=$#Modules; $i++) {
                    299: 	if (&HASH($hashname,$Modules[$i]) eq $date) {
                    300: 	    $usum += $Units[$i];
                    301: 	}
                    302:     }
                    303:     return $usum/$total_weight;
                    304: }
                    305: 
                    306: #-------------------------------------------------------
                    307: 
                    308: =item CDLSUM(list) 
                    309: 
                    310: returns the sum of the elements in a cell which contains
                    311: a Comma Deliminate List of numerical values.
                    312: 'list' is a reference to a cell which contains a comma deliminated list.
                    313: 
                    314: =cut
                    315: 
                    316: #-------------------------------------------------------
                    317: sub CDLSUM {
                    318:     my ($list)=@_;
                    319:     my $sum;
                    320:     foreach (split/,/,$list) {
                    321: 	$sum += $_;
                    322:     }
                    323:     return $sum;
                    324: }
                    325: 
                    326: #-------------------------------------------------------
                    327: 
                    328: =item CDLITEM(list,index) 
                    329: 
                    330: returns the item at 'index' in a Comma Deliminated List.
                    331: 
                    332: =over 4
                    333: 
                    334: =item list
                    335: 
                    336: reference to a cell which contains a comma deliminated list.
                    337: 
                    338: =item index 
                    339: 
                    340: the Perl index of the item requested (first element in list has
                    341: an index of 0) 
                    342: 
                    343: =back
                    344: 
                    345: =cut
                    346: 
                    347: #-------------------------------------------------------
                    348: sub CDLITEM {
                    349:     my ($list,$index)=@_;
                    350:     my @Temp = split/,/,$list;
                    351:     return $Temp[$index];
                    352: }
                    353: 
                    354: #-------------------------------------------------------
                    355: 
                    356: =item CDLHASH(name,key,value) 
                    357: 
                    358: loads a comma deliminated list of keys into
                    359: the hash 'name', all with a value of 'value'.
                    360: 
                    361: =over 4
                    362: 
                    363: =item name  
                    364: 
                    365: name of the hash.
                    366: 
                    367: =item key
                    368: 
                    369: (a pointer to) a comma deliminated list of keys.
                    370: 
                    371: =item value
                    372: 
                    373: a single value to be entered for each key.
                    374: 
                    375: =back
                    376: 
                    377: =cut
                    378: 
                    379: #-------------------------------------------------------
                    380: sub CDLHASH {
                    381:     my ($name,$key,$value)=@_;
                    382:     my @Keys;
                    383:     my @Values;
                    384:     # Check to see if we have multiple $key values
                    385:     if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
                    386: 	my $keymask = &mask($key);
                    387: 	# Assume the keys are addresses
                    388: 	my @Temp = grep /$keymask/,keys(%v);
                    389: 	@Keys = $v{@Temp};
                    390:     } else {
                    391: 	$Keys[0]= $key;
                    392:     }
                    393:     my @Temp;
                    394:     foreach $key (@Keys) {
                    395: 	@Temp = (@Temp, split/,/,$key);
                    396:     }
                    397:     @Keys = @Temp;
                    398:     if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
                    399: 	my $valmask = &mask($value);
                    400: 	my @Temp = grep /$valmask/,keys(%v);
                    401: 	@Values =$v{@Temp};
                    402:     } else {
                    403: 	$Values[0]= $value;
                    404:     }
                    405:     $value = $Values[0];
                    406:     # Add values to hash
                    407:     for (my $i = 0; $i<=$#Keys; $i++) {
                    408: 	my $key   = $Keys[$i];
                    409: 	if (! exists ($hashes{$name}->{$key})) {
                    410: 	    $hashes{$name}->{$key}->[0]=$value;
                    411: 	} else {
                    412: 	    my @Temp = sort(@{$hashes{$name}->{$key}},$value);
                    413: 	    $hashes{$name}->{$key} = \@Temp;
                    414: 	}
                    415:     }
                    416:     return "hash '$name' updated";
                    417: }
                    418: 
                    419: #-------------------------------------------------------
                    420: 
                    421: =item GETHASH(name,key,index) 
                    422: 
                    423: returns the element in hash 'name' 
                    424: reference by the key 'key', at index 'index' in the values list.
                    425: 
                    426: =cut
                    427: 
                    428: #-------------------------------------------------------
                    429: sub GETHASH {
                    430:     my ($name,$key,$index)=@_;
                    431:     if (! defined($index)) {
                    432: 	$index = 0;
                    433:     }
                    434:     if ($key =~ /^[A-z]\d+$/) {
                    435: 	$key = $v{$key};
                    436:     }
                    437:     return $hashes{$name}->{$key}->[$index];
                    438: }
                    439: 
                    440: #-------------------------------------------------------
                    441: 
                    442: =item CLEARHASH(name) 
                    443: 
                    444: clears all the values from the hash 'name'
                    445: 
                    446: =item CLEARHASH(name,key) 
                    447: 
                    448: clears all the values from the hash 'name' associated with the given key.
                    449: 
                    450: =cut
                    451: 
                    452: #-------------------------------------------------------
                    453: sub CLEARHASH {
                    454:     my ($name,$key)=@_;
                    455:     if (defined($key)) {
                    456: 	if (exists($hashes{$name}->{$key})) {
                    457: 	    $hashes{$name}->{$key}=undef;
                    458: 	    return "hash '$name' key '$key' cleared";
                    459: 	}
                    460:     } else {
                    461: 	if (exists($hashes{$name})) {
                    462: 	    $hashes{$name}=undef;
                    463: 	    return "hash '$name' cleared";
                    464: 	}
                    465:     }
                    466:     return "Error in clearing hash";
                    467: }
                    468: 
                    469: #-------------------------------------------------------
                    470: 
                    471: =item HASH(name,key,value) 
                    472: 
                    473: loads values into an internal hash.  If a key 
                    474: already has a value associated with it, the values are sorted numerically.  
                    475: 
                    476: =item HASH(name,key) 
                    477: 
                    478: returns the 0th value in the hash 'name' associated with 'key'.
                    479: 
                    480: =cut
                    481: 
                    482: #-------------------------------------------------------
                    483: sub HASH {
                    484:     my ($name,$key,$value)=@_;
                    485:     my @Keys;
                    486:     undef @Keys;
                    487:     my @Values;
                    488:     # Check to see if we have multiple $key values
                    489:     if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
                    490: 	my $keymask = &mask($key);
                    491: 	# Assume the keys are addresses
                    492: 	my @Temp = grep /$keymask/,keys(%v);
                    493: 	@Keys = $v{@Temp};
                    494:     } else {
                    495: 	$Keys[0]= $key;
                    496:     }
                    497:     # If $value is empty, return the first value associated 
                    498:     # with the first key.
                    499:     if (! $value) {
                    500: 	return $hashes{$name}->{$Keys[0]}->[0];
                    501:     }
                    502:     # Check to see if we have multiple $value(s) 
                    503:     if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
                    504: 	my $valmask = &mask($value);
                    505: 	my @Temp = grep /$valmask/,keys(%v);
                    506: 	@Values =$v{@Temp};
                    507:     } else {
                    508: 	$Values[0]= $value;
                    509:     }
                    510:     # Add values to hash
                    511:     for (my $i = 0; $i<=$#Keys; $i++) {
                    512: 	my $key   = $Keys[$i];
                    513: 	my $value = ($i<=$#Values ? $Values[$i] : $Values[0]);
                    514: 	if (! exists ($hashes{$name}->{$key})) {
                    515: 	    $hashes{$name}->{$key}->[0]=$value;
                    516: 	} else {
                    517: 	    my @Temp = sort(@{$hashes{$name}->{$key}},$value);
                    518: 	    $hashes{$name}->{$key} = \@Temp;
                    519: 	}
                    520:     }
                    521:     return $Values[-1];
1.1       www       522: }
                    523: 
1.84      matthew   524: #-------------------------------------------------------
                    525: 
                    526: =item NUM(range)
                    527: 
                    528: returns the number of items in the range.
                    529: 
                    530: =cut
                    531: 
                    532: #-------------------------------------------------------
1.1       www       533: sub NUM {
                    534:     my $mask=mask(@_);
1.78      matthew   535:     my $num= $#{@{grep(/$mask/,keys(%v))}}+1;
1.1       www       536:     return $num;   
                    537: }
                    538: 
                    539: sub BIN {
                    540:     my ($low,$high,$lower,$upper)=@_;
                    541:     my $mask=mask($lower,$upper);
                    542:     my $num=0;
1.78      matthew   543:     foreach (grep /$mask/,keys(%v)) {
1.1       www       544:         if (($v{$_}>=$low) && ($v{$_}<=$high)) {
                    545:             $num++;
                    546:         }
1.78      matthew   547:     }
1.1       www       548:     return $num;   
                    549: }
                    550: 
                    551: 
1.84      matthew   552: #-------------------------------------------------------
                    553: 
                    554: =item SUM(range)
                    555: 
                    556: returns the sum of items in the range.
                    557: 
                    558: =cut
                    559: 
                    560: #-------------------------------------------------------
1.1       www       561: sub SUM {
                    562:     my $mask=mask(@_);
                    563:     my $sum=0;
1.78      matthew   564:     foreach (grep /$mask/,keys(%v)) {
1.1       www       565:         $sum+=$v{$_};
1.78      matthew   566:     }
1.1       www       567:     return $sum;   
                    568: }
                    569: 
1.84      matthew   570: #-------------------------------------------------------
                    571: 
                    572: =item MEAN(range)
                    573: 
                    574: compute the average of the items in the range.
                    575: 
                    576: =cut
                    577: 
                    578: #-------------------------------------------------------
1.1       www       579: sub MEAN {
                    580:     my $mask=mask(@_);
                    581:     my $sum=0; my $num=0;
1.78      matthew   582:     foreach (grep /$mask/,keys(%v)) {
1.1       www       583:         $sum+=$v{$_};
                    584:         $num++;
1.78      matthew   585:     }
1.1       www       586:     if ($num) {
                    587:        return $sum/$num;
                    588:     } else {
                    589:        return undef;
                    590:     }   
                    591: }
                    592: 
1.84      matthew   593: #-------------------------------------------------------
                    594: 
                    595: =item STDDEV(range)
                    596: 
                    597: compute the standard deviation of the items in the range.
                    598: 
                    599: =cut
                    600: 
                    601: #-------------------------------------------------------
1.1       www       602: sub STDDEV {
                    603:     my $mask=mask(@_);
                    604:     my $sum=0; my $num=0;
1.78      matthew   605:     foreach (grep /$mask/,keys(%v)) {
1.1       www       606:         $sum+=$v{$_};
                    607:         $num++;
1.78      matthew   608:     }
1.1       www       609:     unless ($num>1) { return undef; }
                    610:     my $mean=$sum/$num;
                    611:     $sum=0;
1.78      matthew   612:     foreach (grep /$mask/,keys(%v)) {
1.1       www       613:         $sum+=($v{$_}-$mean)**2;
1.78      matthew   614:     }
1.1       www       615:     return sqrt($sum/($num-1));    
                    616: }
                    617: 
1.84      matthew   618: #-------------------------------------------------------
                    619: 
                    620: =item PROD(range)
                    621: 
                    622: compute the product of the items in the range.
                    623: 
                    624: =cut
                    625: 
                    626: #-------------------------------------------------------
1.1       www       627: sub PROD {
                    628:     my $mask=mask(@_);
                    629:     my $prod=1;
1.78      matthew   630:     foreach (grep /$mask/,keys(%v)) {
1.1       www       631:         $prod*=$v{$_};
1.78      matthew   632:     }
1.1       www       633:     return $prod;   
                    634: }
                    635: 
1.84      matthew   636: #-------------------------------------------------------
                    637: 
                    638: =item MAX(range)
                    639: 
                    640: compute the maximum of the items in the range.
                    641: 
                    642: =cut
                    643: 
                    644: #-------------------------------------------------------
1.1       www       645: sub MAX {
                    646:     my $mask=mask(@_);
                    647:     my $max='-';
1.78      matthew   648:     foreach (grep /$mask/,keys(%v)) {
1.1       www       649:         unless ($max) { $max=$v{$_}; }
                    650:         if (($v{$_}>$max) || ($max eq '-')) { $max=$v{$_}; }
1.78      matthew   651:     } 
1.1       www       652:     return $max;   
                    653: }
                    654: 
1.84      matthew   655: #-------------------------------------------------------
                    656: 
                    657: =item MIN(range)
                    658: 
                    659: compute the minimum of the items in the range.
                    660: 
                    661: =cut
                    662: 
                    663: #-------------------------------------------------------
1.1       www       664: sub MIN {
                    665:     my $mask=mask(@_);
                    666:     my $min='-';
1.78      matthew   667:     foreach (grep /$mask/,keys(%v)) {
1.1       www       668:         unless ($max) { $max=$v{$_}; }
                    669:         if (($v{$_}<$min) || ($min eq '-')) { $min=$v{$_}; }
1.78      matthew   670:     }
1.1       www       671:     return $min;   
                    672: }
                    673: 
1.84      matthew   674: #-------------------------------------------------------
                    675: 
                    676: =item SUMMAX(num,lower,upper)
                    677: 
                    678: compute the sum of the largest 'num' items in the range from
                    679: 'lower' to 'upper'
                    680: 
                    681: =cut
                    682: 
                    683: #-------------------------------------------------------
1.1       www       684: sub SUMMAX {
                    685:     my ($num,$lower,$upper)=@_;
                    686:     my $mask=mask($lower,$upper);
                    687:     my @inside=();
1.78      matthew   688:     foreach (grep /$mask/,keys(%v)) {
1.84      matthew   689: 	push (@inside,$v{$_});
1.78      matthew   690:     }
1.1       www       691:     @inside=sort(@inside);
                    692:     my $sum=0; my $i;
                    693:     for ($i=$#inside;(($i>$#inside-$num) && ($i>=0));$i--) { 
                    694:         $sum+=$inside[$i];
                    695:     }
                    696:     return $sum;   
                    697: }
                    698: 
1.84      matthew   699: #-------------------------------------------------------
                    700: 
                    701: =item SUMMIN(num,lower,upper)
                    702: 
                    703: compute the sum of the smallest 'num' items in the range from
                    704: 'lower' to 'upper'
                    705: 
                    706: =cut
                    707: 
                    708: #-------------------------------------------------------
1.1       www       709: sub SUMMIN {
                    710:     my ($num,$lower,$upper)=@_;
                    711:     my $mask=mask($lower,$upper);
                    712:     my @inside=();
1.78      matthew   713:     foreach (grep /$mask/,keys(%v)) {
1.1       www       714: 	$inside[$#inside+1]=$v{$_};
1.78      matthew   715:     }
1.1       www       716:     @inside=sort(@inside);
                    717:     my $sum=0; my $i;
                    718:     for ($i=0;(($i<$num) && ($i<=$#inside));$i++) { 
                    719:         $sum+=$inside[$i];
                    720:     }
                    721:     return $sum;   
                    722: }
                    723: 
1.59      www       724: sub expandnamed {
                    725:     my $expression=shift;
                    726:     if ($expression=~/^\&/) {
                    727: 	my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/);
                    728: 	my @vars=split(/\W+/,$formula);
                    729:         my %values=();
                    730:         undef %values;
1.78      matthew   731: 	foreach ( @vars ) {
1.59      www       732:             my $varname=$_;
                    733:             if ($varname=~/\D/) {
                    734:                $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
                    735:                $varname=~s/$var/\(\\w\+\)/g;
1.78      matthew   736: 	       foreach (keys(%c)) {
1.59      www       737: 		  if ($_=~/$varname/) {
                    738: 		      $values{$1}=1;
                    739:                   }
1.78      matthew   740:                }
1.59      www       741: 	    }
1.78      matthew   742:         }
1.59      www       743:         if ($func eq 'EXPANDSUM') {
                    744:             my $result='';
1.78      matthew   745: 	    foreach (keys(%values)) {
1.59      www       746:                 my $thissum=$formula;
                    747:                 $thissum=~s/$var/$_/g;
                    748:                 $result.=$thissum.'+';
1.78      matthew   749:             } 
1.59      www       750:             $result=~s/\+$//;
                    751:             return $result;
                    752:         } else {
                    753: 	    return 0;
                    754:         }
                    755:     } else {
1.88      matthew   756:         # it is not a function, so it is a parameter name
                    757:         # We should do the following:
                    758:         #    1. Take the list of parameter names
                    759:         #    2. look through the list for ones that match the parameter we want
                    760:         #    3. If there are no collisions, return the one that matches
                    761:         #    4. If there is a collision, return 'bad parameter name error'
                    762:         my $returnvalue = '';
                    763:         my @matches = ();
                    764:         $#matches = -1;
                    765:         study $expression;
                    766:         foreach $parameter (keys(%c)) {
                    767:             push @matches,$parameter if ($parameter =~ /$expression/);
                    768:         }
                    769:         if ($#matches == 0) {
                    770:             $returnvalue = '$c{\''.$matches[0].'\'}';
1.100   ! matthew   771:         } elsif ($#matches > 0) {
        !           772:             # more than one match.  Look for a concise one
        !           773:             $returnvalue =  "'non-unique parameter name : $expression'";
        !           774:             foreach (@matches) {
        !           775:                 if (/^$expression$/) {
        !           776:                     $returnvalue = '$c{\''.$_.'\'}';
        !           777:                 }
        !           778:             }
1.88      matthew   779:         } else {
                    780:             $returnvalue =  "'bad parameter name : $expression'";
                    781:         }
                    782:         return $returnvalue;
1.59      www       783:     }
                    784: }
                    785: 
1.1       www       786: sub sett {
                    787:     %t=();
1.16      www       788:     my $pattern='';
                    789:     if ($sheettype eq 'assesscalc') {
                    790: 	$pattern='A';
                    791:     } else {
                    792:         $pattern='[A-Z]';
                    793:     }
1.97      www       794: 
                    795: # Deal with the template row
1.78      matthew   796:     foreach (keys(%f)) {
1.20      www       797: 	if ($_=~/template\_(\w)/) {
                    798: 	  my $col=$1;
                    799:           unless ($col=~/^$pattern/) {
1.78      matthew   800: 	    foreach (keys(%f)) {
1.20      www       801: 	      if ($_=~/A(\d+)/) {
                    802: 		my $trow=$1;
                    803:                 if ($trow) {
1.88      matthew   804:                     # Get the name of this cell
1.20      www       805: 		    my $lb=$col.$trow;
1.88      matthew   806:                     # Grab the template declaration
1.20      www       807:                     $t{$lb}=$f{'template_'.$col};
1.88      matthew   808:                     # Replace '#' with the row number
1.20      www       809:                     $t{$lb}=~s/\#/$trow/g;
1.88      matthew   810:                     # Replace '....' with ','
1.20      www       811:                     $t{$lb}=~s/\.\.+/\,/g;
1.88      matthew   812:                     # Replace 'A0' with the value from 'A0'
1.20      www       813:                     $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
1.88      matthew   814:                     # Replace parameters
1.59      www       815:                     $t{$lb}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
1.20      www       816:                 }
                    817: 	      }
1.78      matthew   818: 	    }
1.20      www       819: 	  }
                    820:       }
1.78      matthew   821:     }
1.97      www       822: 
                    823: # Deal with the normal cells
1.78      matthew   824:     foreach (keys(%f)) {
1.20      www       825: 	if (($f{$_}) && ($_!~/template\_/)) {
1.42      www       826:             my $matches=($_=~/^$pattern(\d+)/);
                    827:             if  (($matches) && ($1)) {
1.6       www       828: 	        unless ($f{$_}=~/^\!/) {
                    829: 		    $t{$_}=$c{$_};
                    830:                 }
                    831:             } else {
                    832: 	       $t{$_}=$f{$_};
1.7       www       833:                $t{$_}=~s/\.\.+/\,/g;
                    834:                $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
1.59      www       835:                $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
1.6       www       836:             }
1.1       www       837:         }
1.78      matthew   838:     }
1.97      www       839: # For inserted lines, [B-Z] is also valid
                    840: 
                    841:     unless ($sheettype eq 'assesscalc') {
                    842:        foreach (keys(%f)) {
                    843: 	   if ($_=~/[B-Z](\d+)/) {
                    844: 	       if ($f{'A'.$1}=~/^[\~\-]/) {
                    845:   	          $t{$_}=$f{$_};
                    846:                   $t{$_}=~s/\.\.+/\,/g;
                    847:                   $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
                    848:                   $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
                    849:                }
                    850:            }
                    851:        }
                    852:     }
                    853: 
1.88      matthew   854:     # For some reason 'A0' gets special treatment...  This seems superfluous
                    855:     # but I imagine it is here for a reason.
1.17      www       856:     $t{'A0'}=$f{'A0'};
                    857:     $t{'A0'}=~s/\.\.+/\,/g;
                    858:     $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
1.59      www       859:     $t{'A0'}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
1.1       www       860: }
                    861: 
1.4       www       862: sub calc {
1.95      www       863:     undef %v;
1.4       www       864:     &sett();
1.1       www       865:     my $notfinished=1;
1.97      www       866:     my $lastcalc='';
1.1       www       867:     my $depth=0;
                    868:     while ($notfinished) {
                    869: 	$notfinished=0;
1.78      matthew   870:         foreach (keys(%t)) {
1.1       www       871:             my $old=$v{$_};
1.96      www       872:             $v{$_}=eval $t{$_};
1.1       www       873: 	    if ($@) {
1.96      www       874: 		undef %v;
                    875:                 return $_.': '.$@;
1.1       www       876:             }
1.97      www       877: 	    if ($v{$_} ne $old) { $notfinished=1; $lastcalc=$_; }
1.78      matthew   878:         }
1.1       www       879:         $depth++;
                    880:         if ($depth>100) {
1.95      www       881: 	    undef %v;
1.97      www       882:             return $lastcalc.': Maximum calculation depth exceeded';
1.1       www       883:         }
                    884:     }
1.96      www       885:     return '';
1.1       www       886: }
                    887: 
1.21      www       888: sub templaterow {
                    889:     my @cols=();
                    890:     $cols[0]='<b><font size=+1>Template</font></b>';
1.78      matthew   891:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
                    892: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                    893: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
                    894: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.21      www       895:         my $fm=$f{'template_'.$_};
                    896:         $fm=~s/[\'\"]/\&\#34;/g;
                    897:         $cols[$#cols+1]="'template_$_','$fm'".'___eq___'.$fm;
1.78      matthew   898:     }
1.21      www       899:     return @cols;
                    900: }
                    901: 
1.16      www       902: sub outrowassess {
1.6       www       903:     my $n=shift;
                    904:     my @cols=();
                    905:     if ($n) {
1.55      www       906:        my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{'A'.$n});
1.92      www       907:       if ($rl{$usy}) {
1.58      www       908:        $cols[0]=$rl{$usy}.'<br>'.
1.55      www       909:                 '<select name="sel_'.$n.'" onChange="changesheet('.$n.
                    910:                 ')"><option name="default">Default</option>';
1.92      www       911:       } else { $cols[0]=''; }
1.78      matthew   912:        foreach (@os) {
1.55      www       913:            $cols[0].='<option name="'.$_.'"';
                    914:             if ($ufn eq $_) {
                    915:                $cols[0].=' selected';
                    916:             }
                    917:             $cols[0].='>'.$_.'</option>';
1.78      matthew   918:        }
1.55      www       919:        $cols[0].='</select>';
1.6       www       920:     } else {
                    921:        $cols[0]='<b><font size=+1>Export</font></b>';
                    922:     }
1.78      matthew   923:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
                    924: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                    925: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
                    926: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.6       www       927:         my $fm=$f{$_.$n};
                    928:         $fm=~s/[\'\"]/\&\#34;/g;
1.83      matthew   929:         push(@cols,"'$_$n','$fm'".'___eq___'.$v{$_.$n});
1.78      matthew   930:     }
1.6       www       931:     return @cols;
                    932: }
                    933: 
1.18      www       934: sub outrow {
                    935:     my $n=shift;
                    936:     my @cols=();
                    937:     if ($n) {
1.21      www       938:        $cols[0]=$rl{$f{'A'.$n}};
1.18      www       939:     } else {
                    940:        $cols[0]='<b><font size=+1>Export</font></b>';
                    941:     }
1.78      matthew   942:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
                    943: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                    944: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
                    945: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.18      www       946:         my $fm=$f{$_.$n};
                    947:         $fm=~s/[\'\"]/\&\#34;/g;
                    948:         $cols[$#cols+1]="'$_$n','$fm'".'___eq___'.$v{$_.$n};
1.78      matthew   949:     }
1.18      www       950:     return @cols;
                    951: }
                    952: 
1.14      www       953: sub exportrowa {
1.28      www       954:     my @exportarray=();
1.78      matthew   955:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
                    956: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1.28      www       957: 	$exportarray[$#exportarray+1]=$v{$_.'0'};
1.78      matthew   958:     } 
1.28      www       959:     return @exportarray;
1.14      www       960: }
                    961: 
1.4       www       962: # ------------------------------------------- End of "Inside of the safe space"
                    963: ENDDEFS
                    964:     $safeeval->reval($code);
                    965:     return $safeeval;
                    966: }
                    967: 
                    968: # ------------------------------------------------ Add or change formula values
                    969: 
                    970: sub setformulas {
1.34      www       971:     my ($safeeval,%f)=@_;
                    972:     %{$safeeval->varglob('f')}=%f;
1.6       www       973: }
                    974: 
                    975: # ------------------------------------------------ Add or change formula values
                    976: 
                    977: sub setconstants {
1.34      www       978:     my ($safeeval,%c)=@_;
                    979:     %{$safeeval->varglob('c')}=%c;
1.6       www       980: }
                    981: 
1.55      www       982: # --------------------------------------------- Set names of other spreadsheets
                    983: 
                    984: sub setothersheets {
                    985:     my ($safeeval,@os)=@_;
                    986:     @{$safeeval->varglob('os')}=@os;
                    987: }
                    988: 
1.6       www       989: # ------------------------------------------------ Add or change formula values
                    990: 
                    991: sub setrowlabels {
1.34      www       992:     my ($safeeval,%rl)=@_;
                    993:     %{$safeeval->varglob('rl')}=%rl;
1.4       www       994: }
                    995: 
                    996: # ------------------------------------------------------- Calculate spreadsheet
                    997: 
                    998: sub calcsheet {
                    999:     my $safeeval=shift;
1.95      www      1000:     return $safeeval->reval('&calc();');
1.4       www      1001: }
                   1002: 
                   1003: # ------------------------------------------------------------------ Get values
                   1004: 
                   1005: sub getvalues {
                   1006:     my $safeeval=shift;
                   1007:     return $safeeval->reval('%v');
                   1008: }
                   1009: 
                   1010: # ---------------------------------------------------------------- Get formulas
                   1011: 
                   1012: sub getformulas {
                   1013:     my $safeeval=shift;
1.34      www      1014:     return %{$safeeval->varglob('f')};
1.4       www      1015: }
                   1016: 
1.97      www      1017: # ----------------------------------------------------- Get value of $f{'A'.$n}
                   1018: 
                   1019: sub getfa {
                   1020:     my ($safeeval,$n)=@_;
                   1021:     return $safeeval->reval('$f{"A'.$n.'"}');
                   1022: }
                   1023: 
1.5       www      1024: # -------------------------------------------------------------------- Get type
                   1025: 
                   1026: sub gettype {
                   1027:     my $safeeval=shift;
                   1028:     return $safeeval->reval('$sheettype');
                   1029: }
1.27      www      1030: 
1.6       www      1031: # ------------------------------------------------------------------ Set maxrow
                   1032: 
                   1033: sub setmaxrow {
                   1034:     my ($safeeval,$row)=@_;
                   1035:     $safeeval->reval('$maxrow='.$row.';');
                   1036: }
                   1037: 
                   1038: # ------------------------------------------------------------------ Get maxrow
                   1039: 
                   1040: sub getmaxrow {
                   1041:     my $safeeval=shift;
                   1042:     return $safeeval->reval('$maxrow');
                   1043: }
1.5       www      1044: 
1.6       www      1045: # ---------------------------------------------------------------- Set filename
1.5       www      1046: 
                   1047: sub setfilename {
                   1048:     my ($safeeval,$fn)=@_;
1.11      www      1049:     $safeeval->reval('$filename="'.$fn.'";');
1.5       www      1050: }
                   1051: 
1.6       www      1052: # ---------------------------------------------------------------- Get filename
1.5       www      1053: 
                   1054: sub getfilename {
                   1055:     my $safeeval=shift;
                   1056:     return $safeeval->reval('$filename');
                   1057: }
1.29      www      1058: 
1.28      www      1059: # --------------------------------------------------------------- Get course ID
                   1060: 
                   1061: sub getcid {
                   1062:     my $safeeval=shift;
                   1063:     return $safeeval->reval('$cid');
                   1064: }
1.14      www      1065: 
1.29      www      1066: # --------------------------------------------------------- Get course filename
                   1067: 
                   1068: sub getcfn {
                   1069:     my $safeeval=shift;
                   1070:     return $safeeval->reval('$cfn');
                   1071: }
                   1072: 
1.27      www      1073: # ----------------------------------------------------------- Get course number
                   1074: 
                   1075: sub getcnum {
                   1076:     my $safeeval=shift;
                   1077:     return $safeeval->reval('$cnum');
                   1078: }
                   1079: 
                   1080: # ------------------------------------------------------------- Get course home
                   1081: 
                   1082: sub getchome {
                   1083:     my $safeeval=shift;
                   1084:     return $safeeval->reval('$chome');
                   1085: }
                   1086: 
                   1087: # ----------------------------------------------------------- Get course domain
                   1088: 
                   1089: sub getcdom {
                   1090:     my $safeeval=shift;
                   1091:     return $safeeval->reval('$cdom');
                   1092: }
                   1093: 
                   1094: # ---------------------------------------------------------- Get course section
                   1095: 
                   1096: sub getcsec {
                   1097:     my $safeeval=shift;
                   1098:     return $safeeval->reval('$csec');
                   1099: }
                   1100: 
                   1101: # --------------------------------------------------------------- Get user name
                   1102: 
                   1103: sub getuname {
                   1104:     my $safeeval=shift;
                   1105:     return $safeeval->reval('$uname');
                   1106: }
                   1107: 
                   1108: # ------------------------------------------------------------- Get user domain
                   1109: 
                   1110: sub getudom {
                   1111:     my $safeeval=shift;
                   1112:     return $safeeval->reval('$udom');
                   1113: }
                   1114: 
                   1115: # --------------------------------------------------------------- Get user home
                   1116: 
                   1117: sub getuhome {
                   1118:     my $safeeval=shift;
                   1119:     return $safeeval->reval('$uhome');
                   1120: }
                   1121: 
                   1122: # -------------------------------------------------------------------- Get symb
                   1123: 
                   1124: sub getusymb {
                   1125:     my $safeeval=shift;
                   1126:     return $safeeval->reval('$usymb');
                   1127: }
                   1128: 
1.14      www      1129: # ------------------------------------------------------------- Export of A-row
                   1130: 
1.28      www      1131: sub exportdata {
1.14      www      1132:     my $safeeval=shift;
                   1133:     return $safeeval->reval('&exportrowa()');
                   1134: }
                   1135: 
1.55      www      1136: 
1.5       www      1137: # ========================================================== End of Spreadsheet
                   1138: # =============================================================================
                   1139: 
1.27      www      1140: #
                   1141: # Procedures for screen output
                   1142: #
1.6       www      1143: # --------------------------------------------- Produce output row n from sheet
                   1144: 
                   1145: sub rown {
                   1146:     my ($safeeval,$n)=@_;
1.21      www      1147:     my $defaultbg;
1.24      www      1148:     my $rowdata='';
1.61      www      1149:     my $dataflag=0;
1.21      www      1150:     unless ($n eq '-') {
                   1151:        $defaultbg=((($n-1)/5)==int(($n-1)/5))?'#E0E0':'#FFFF';
                   1152:     } else {
                   1153:        $defaultbg='#E0FF';
                   1154:     }
1.71      www      1155:     unless ($ENV{'form.showcsv'}) {
                   1156:        $rowdata.="\n<tr><td><b><font size=+1>$n</font></b></td>";
                   1157:     } else {
                   1158:        $rowdata.="\n".'"'.$n.'"';
                   1159:     }
1.6       www      1160:     my $showf=0;
1.16      www      1161:     my $proc;
1.97      www      1162:     my $maxred=1;
1.62      www      1163:     my $sheettype=&gettype($safeeval);
                   1164:     if ($sheettype eq 'studentcalc') {
1.55      www      1165:         $proc='&outrowassess';
                   1166:         $maxred=26;
                   1167:     } else {
                   1168:         $proc='&outrow';
                   1169:     }
1.62      www      1170:     if ($sheettype eq 'assesscalc') {
1.18      www      1171:         $maxred=1;
1.16      www      1172:     } else {
1.18      www      1173:         $maxred=26;
1.16      www      1174:     }
1.97      www      1175:     if (&getfa($safeeval,$n)=~/^[\~\-]/) { $maxred=1; }
1.61      www      1176:     if ($n eq '-') { $proc='&templaterow'; $n=-1; $dataflag=1; }
1.78      matthew  1177:     foreach ($safeeval->reval($proc.'('.$n.')')) {
1.9       www      1178:        my $bgcolor=$defaultbg.((($showf-1)/5==int(($showf-1)/5))?'99':'DD');
1.6       www      1179:        my ($fm,$vl)=split(/\_\_\_eq\_\_\_/,$_);
1.62      www      1180:        if ((($vl ne '') || ($vl eq '0')) &&
                   1181:            (($showf==1) || ($sheettype ne 'studentcalc'))) { $dataflag=1; }
1.6       www      1182:        if ($showf==0) { $vl=$_; }
1.71      www      1183:       unless ($ENV{'form.showcsv'}) {
1.18      www      1184:        if ($showf<=$maxred) { $bgcolor='#FFDDDD'; }
1.9       www      1185:        if (($n==0) && ($showf<=26)) { $bgcolor='#CCCCFF'; } 
1.18      www      1186:        if (($showf>$maxred) || ((!$n) && ($showf>0))) {
1.6       www      1187: 	   if ($vl eq '') {
1.9       www      1188: 	       $vl='<font size=+2 color='.$bgcolor.'>&#35;</font>';
1.6       www      1189:            }
                   1190:            $rowdata.=
1.10      www      1191:        '<td bgcolor='.$bgcolor.'><a href="javascript:celledit('.$fm.');">'.$vl.
1.6       www      1192: 	       '</a></td>';
                   1193:        } else {
1.9       www      1194:            $rowdata.='<td bgcolor='.$bgcolor.'>&nbsp;'.$vl.'&nbsp;</td>';
1.6       www      1195:        }
1.71      www      1196:       } else {
                   1197: 	  $rowdata.=',"'.$vl.'"';
                   1198:       }
1.6       www      1199:        $showf++;
1.78      matthew  1200:     }  # End of foreach($safeval...)
1.61      www      1201:     if ($ENV{'form.showall'} || ($dataflag)) {
1.71      www      1202:        return $rowdata.($ENV{'form.showcsv'}?'':'</tr>');
1.61      www      1203:     } else {
1.63      www      1204:        return '';
1.61      www      1205:     }
1.6       www      1206: }
                   1207: 
                   1208: # ------------------------------------------------------------- Print out sheet
                   1209: 
                   1210: sub outsheet {
1.24      www      1211:     my ($r,$safeeval)=@_;
1.18      www      1212:     my $maxred;
                   1213:     my $realm;
                   1214:     if (&gettype($safeeval) eq 'assesscalc') {
                   1215:         $maxred=1;
                   1216:         $realm='Assessment';
                   1217:     } elsif (&gettype($safeeval) eq 'studentcalc') {
                   1218:         $maxred=26;
                   1219:         $realm='User';
                   1220:     } else {
                   1221:         $maxred=26;
                   1222:         $realm='Course';
                   1223:     }
                   1224:     my $maxyellow=52-$maxred;
1.71      www      1225:     my $tabledata;
                   1226:     unless ($ENV{'form.showcsv'}) {
                   1227:        $tabledata=
1.24      www      1228:         '<table border=2><tr><th colspan=2 rowspan=2><font size=+2>'.
1.18      www      1229:                   $realm.'</font></th>'.
                   1230:                   '<td bgcolor=#FFDDDD colspan='.$maxred.
                   1231:                   '><b><font size=+1>Import</font></b></td>'.
                   1232:                   '<td colspan='.$maxyellow.
                   1233: 		  '><b><font size=+1>Calculations</font></b></td></tr><tr>';
                   1234:     my $showf=0;
1.78      matthew  1235:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
                   1236: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                   1237: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
                   1238: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.18      www      1239:         $showf++;
                   1240:         if ($showf<=$maxred) { 
                   1241:            $tabledata.='<td bgcolor="#FFDDDD">'; 
                   1242:         } else {
                   1243:            $tabledata.='<td>';
                   1244:         }
                   1245:         $tabledata.="<b><font size=+1>$_</font></b></td>";
1.78      matthew  1246:     }
1.71      www      1247:     $tabledata.='</tr>'.&rown($safeeval,'-').&rown($safeeval,0);
                   1248:    } else { $tabledata='<pre>'; }
                   1249: 
                   1250:     $r->print($tabledata);
                   1251: 
1.6       www      1252:     my $row;
                   1253:     my $maxrow=&getmaxrow($safeeval);
1.64      www      1254: 
1.65      www      1255:     my @sortby=();
                   1256:     my @sortidx=();
                   1257:     for ($row=1;$row<=$maxrow;$row++) {
                   1258:        $sortby[$row-1]=$safeeval->reval('$f{"A'.$row.'"}');
                   1259:        $sortidx[$row-1]=$row-1;
                   1260:     }
                   1261:     @sortidx=sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1.64      www      1262: 
1.63      www      1263:         my $what='Student';
                   1264:         if (&gettype($safeeval) eq 'assesscalc') {
                   1265: 	    $what='Item';
                   1266: 	} elsif (&gettype($safeeval) eq 'studentcalc') {
                   1267:             $what='Assessment';
                   1268:         }
1.65      www      1269: 
                   1270:     my $n=0;
                   1271:     for ($row=0;$row<$maxrow;$row++) {
                   1272:      my $thisrow=&rown($safeeval,$sortidx[$row]+1);
                   1273:      if ($thisrow) {
1.71      www      1274:        if (($n/25==int($n/25)) && (!$ENV{'form.showcsv'})) {
1.65      www      1275: 	$r->print("</table>\n<br>\n");
                   1276:         $r->rflush();
                   1277:         $r->print('<table border=2><tr><td>&nbsp;<td>'.$what.'</td>');
1.78      matthew  1278:         foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
                   1279: 		 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                   1280: 		 'a','b','c','d','e','f','g','h','i','j','k','l','m',
                   1281: 		 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1.63      www      1282:            $r->print('<td>'.$_.'</td>');
1.78      matthew  1283:         }
1.63      www      1284:         $r->print('</tr>');
                   1285:        }
1.64      www      1286:        $n++;
                   1287:        $r->print($thisrow);
1.63      www      1288:       }
1.6       www      1289:     }
1.71      www      1290:     $r->print($ENV{'form.showcsv'}?'</pre>':'</table>');
1.6       www      1291: }
                   1292: 
1.27      www      1293: #
1.55      www      1294: # ----------------------------------------------- Read list of available sheets
                   1295: # 
                   1296: sub othersheets {
                   1297:     my ($safeeval,$stype)=@_;
1.81      matthew  1298:     #
1.55      www      1299:     my $cnum=&getcnum($safeeval);
                   1300:     my $cdom=&getcdom($safeeval);
                   1301:     my $chome=&getchome($safeeval);
1.81      matthew  1302:     #
1.55      www      1303:     my @alternatives=();
1.81      matthew  1304:     my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
                   1305:     my ($tmp) = keys(%results);
                   1306:     unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
                   1307:         @alternatives = sort (keys(%results));
                   1308:     }
1.55      www      1309:     return @alternatives; 
                   1310: }
                   1311: 
1.82      matthew  1312: 
                   1313: #
                   1314: # -------------------------------------- Parse a spreadsheet
                   1315: # 
                   1316: sub parse_sheet {
                   1317:     # $sheetxml is a scalar reference or a scalar
                   1318:     my ($sheetxml) = @_;
                   1319:     if (! ref($sheetxml)) {
                   1320:         my $tmp = $sheetxml;
                   1321:         $sheetxml = \$tmp;
                   1322:     }
                   1323:     my %f;
                   1324:     my $parser=HTML::TokeParser->new($sheetxml);
                   1325:     my $token;
                   1326:     while ($token=$parser->get_token) {
                   1327:         if ($token->[0] eq 'S') {
                   1328:             if ($token->[1] eq 'field') {
                   1329:                 $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
                   1330:                     $parser->get_text('/field');
                   1331:             }
                   1332:             if ($token->[1] eq 'template') {
                   1333:                 $f{'template_'.$token->[2]->{'col'}}=
                   1334:                     $parser->get_text('/template');
                   1335:             }
                   1336:         }
                   1337:     }
                   1338:     return \%f;
                   1339: }
                   1340: 
1.55      www      1341: #
1.27      www      1342: # -------------------------------------- Read spreadsheet formulas for a course
                   1343: #
                   1344: 
                   1345: sub readsheet {
                   1346:   my ($safeeval,$fn)=@_;
                   1347:   my $stype=&gettype($safeeval);
                   1348:   my $cnum=&getcnum($safeeval);
1.28      www      1349:   my $cdom=&getcdom($safeeval);
                   1350:   my $chome=&getchome($safeeval);
1.27      www      1351: 
1.83      matthew  1352:   if (! defined($fn)) {
1.82      matthew  1353:       # There is no filename. Look for defaults in course and global, cache
1.28      www      1354:       unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
1.82      matthew  1355:           my %tmphash = &Apache::lonnet::get('environment',
                   1356:                                              ['spreadsheet_default_'.$stype],
                   1357:                                              $cdom,$cnum);
                   1358:           my ($tmp) = keys(%tmphash);
                   1359:           if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
                   1360:               $fn = 'default_'.$stype;
                   1361:           } else {
                   1362:               $fn = $tmphash{'spreadsheet_default_'.$stype};
                   1363:           } 
1.90      www      1364:           unless (($fn) && ($fn!~/^error\:/)) {
                   1365:  	     $fn='default_'.$stype;
                   1366:           }
1.82      matthew  1367:           $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn; 
                   1368:       }
1.27      www      1369:   }
                   1370: 
                   1371: # ---------------------------------------------------------- fn now has a value
                   1372: 
                   1373:   &setfilename($safeeval,$fn);
                   1374: 
                   1375: # ------------------------------------------------------ see if sheet is cached
                   1376:   my $fstring='';
1.28      www      1377:   if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
                   1378:       &setformulas($safeeval,split(/\_\_\_\;\_\_\_/,$fstring));
1.27      www      1379:   } else {
1.6       www      1380: 
1.27      www      1381: # ---------------------------------------------------- Not cached, need to read
1.5       www      1382: 
1.27      www      1383:      my %f=();
1.3       www      1384: 
1.27      www      1385:      if ($fn=~/^default\_/) {
1.82      matthew  1386:          my $sheetxml='';
1.10      www      1387:          my $fh;
1.73      www      1388:          my $dfn=$fn;
                   1389:          $dfn=~s/\_/\./g;
                   1390:          if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
1.82      matthew  1391:              $sheetxml=join('',<$fh>);
                   1392:          } else {
1.73      www      1393:              $sheetxml='<field row="0" col="A">"Error"</field>';
1.82      matthew  1394:          }
1.83      matthew  1395:          %f=%{&parse_sheet(\$sheetxml)};
1.82      matthew  1396:      } elsif($fn=~/\/*\.spreadsheet$/) {
1.83      matthew  1397:          my $sheetxml=&Apache::lonnet::getfile
                   1398:              (&Apache::lonnet::filelocation('',$fn));
                   1399:          if ($sheetxml == -1) {
1.82      matthew  1400:              $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
                   1401:                  .$fn.'"</field>';
                   1402:          }
1.83      matthew  1403:          %f=%{&parse_sheet(\$sheetxml)};
1.82      matthew  1404:      } else {
                   1405:          my $sheet='';
                   1406:          my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
                   1407:          my ($tmp) = keys(%tmphash);
                   1408:          unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
                   1409:              foreach (keys(%tmphash)) {
                   1410:                  $f{$_}=$tmphash{$_};
1.20      www      1411:              }
1.82      matthew  1412:          }
                   1413:      }
1.27      www      1414: # --------------------------------------------------------------- Cache and set
1.28      www      1415:        $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);  
1.27      www      1416:        &setformulas($safeeval,%f);
1.3       www      1417:     }
                   1418: }
                   1419: 
1.28      www      1420: # -------------------------------------------------------- Make new spreadsheet
                   1421: 
                   1422: sub makenewsheet {
                   1423:     my ($uname,$udom,$stype,$usymb)=@_;
1.36      www      1424:     my $safeeval=initsheet($stype);
1.28      www      1425:     $safeeval->reval(
1.29      www      1426:        '$uname="'.$uname.
                   1427:       '";$udom="'.$udom.
                   1428:       '";$uhome="'.&Apache::lonnet::homeserver($uname,$udom).
                   1429:       '";$sheettype="'.$stype.
                   1430:       '";$usymb="'.$usymb.
1.30      www      1431:       '";$csec="'.&Apache::lonnet::usection($udom,$uname,
                   1432:                                             $ENV{'request.course.id'}).
1.29      www      1433:       '";$cid="'.$ENV{'request.course.id'}.
                   1434:       '";$cfn="'.$ENV{'request.course.fn'}.
                   1435:       '";$cnum="'.$ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
                   1436:       '";$cdom="'.$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
                   1437:       '";$chome="'.$ENV{'course.'.$ENV{'request.course.id'}.'.home'}.'";');
1.28      www      1438:     return $safeeval;
                   1439: }
                   1440: 
1.19      www      1441: # ------------------------------------------------------------ Save spreadsheet
                   1442: 
                   1443: sub writesheet {
1.28      www      1444:   my ($safeeval,$makedef)=@_;
                   1445:   my $cid=&getcid($safeeval);
                   1446:   if (&Apache::lonnet::allowed('opa',$cid)) {
1.19      www      1447:     my %f=&getformulas($safeeval);
1.28      www      1448:     my $stype=&gettype($safeeval);
                   1449:     my $cnum=&getcnum($safeeval);
                   1450:     my $cdom=&getcdom($safeeval);
                   1451:     my $chome=&getchome($safeeval);
                   1452:     my $fn=&getfilename($safeeval);
                   1453: 
                   1454: # ------------------------------------------------------------- Cache new sheet
                   1455:     $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);    
                   1456: # ----------------------------------------------------------------- Write sheet
1.19      www      1457:     my $sheetdata='';
1.78      matthew  1458:     foreach (keys(%f)) {
1.56      www      1459:      unless ($f{$_} eq 'import') {
1.19      www      1460:        $sheetdata.=&Apache::lonnet::escape($_).'='.
                   1461: 	   &Apache::lonnet::escape($f{$_}).'&';
1.56      www      1462:      }
1.78      matthew  1463:     }
1.19      www      1464:     $sheetdata=~s/\&$//;
1.28      www      1465:     my $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.$fn.':'.
                   1466:               $sheetdata,$chome);
1.22      www      1467:     if ($reply eq 'ok') {
1.28      www      1468:           $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.
1.30      www      1469:               $stype.'_spreadsheets:'.
1.55      www      1470:               &Apache::lonnet::escape($fn).'='.$ENV{'user.name'}.'@'.
                   1471:                                                $ENV{'user.domain'},
1.28      www      1472:               $chome);
                   1473:           if ($reply eq 'ok') {
                   1474:               if ($makedef) { 
                   1475:                 return &Apache::lonnet::reply('put:'.$cdom.':'.$cnum.
                   1476:                                 ':environment:spreadsheet_default_'.$stype.'='.
                   1477:                                 &Apache::lonnet::escape($fn),
                   1478:                                 $chome);
                   1479: 	      } else {
                   1480: 		  return $reply;
                   1481:     	      }
                   1482: 	   } else {
                   1483: 	       return $reply;
                   1484:            }
1.22      www      1485:       } else {
                   1486: 	  return $reply;
                   1487:       }
                   1488:   }
                   1489:   return 'unauthorized';
1.19      www      1490: }
                   1491: 
1.10      www      1492: # ----------------------------------------------- Make a temp copy of the sheet
1.28      www      1493: # "Modified workcopy" - interactive only
                   1494: #
1.10      www      1495: 
                   1496: sub tmpwrite {
1.28      www      1497:     my $safeeval=shift;
                   1498:     my $fn=$ENV{'user.name'}.'_'.
                   1499:            $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
                   1500:            &getfilename($safeeval);
1.10      www      1501:     $fn=~s/\W/\_/g;
                   1502:     $fn=$tmpdir.$fn.'.tmp';
                   1503:     my $fh;
                   1504:     if ($fh=Apache::File->new('>'.$fn)) {
                   1505: 	print $fh join("\n",&getformulas($safeeval));
                   1506:     }
                   1507: }
                   1508: 
                   1509: # ---------------------------------------------------------- Read the temp copy
                   1510: 
                   1511: sub tmpread {
1.28      www      1512:     my ($safeeval,$nfield,$nform)=@_;
                   1513:     my $fn=$ENV{'user.name'}.'_'.
                   1514:            $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
                   1515:            &getfilename($safeeval);
1.10      www      1516:     $fn=~s/\W/\_/g;
                   1517:     $fn=$tmpdir.$fn.'.tmp';
                   1518:     my $fh;
                   1519:     my %fo=();
1.92      www      1520:     my $countrows=0;
1.10      www      1521:     if ($fh=Apache::File->new($fn)) {
                   1522:         my $name;
                   1523:         while ($name=<$fh>) {
                   1524: 	    chomp($name);
                   1525:             my $value=<$fh>;
                   1526:             chomp($value);
                   1527:             $fo{$name}=$value;
1.93      www      1528:             if ($name=~/^A(\d+)$/) {
                   1529: 		if ($1>$countrows) {
                   1530: 		    $countrows=$1;
                   1531:                 }
                   1532:             }
1.10      www      1533:         }
                   1534:     }
1.55      www      1535:     if ($nform eq 'changesheet') {
1.57      www      1536:         $fo{'A'.$nfield}=(split(/\_\_\&\&\&\_\_/,$fo{'A'.$nfield}))[0];
1.55      www      1537:         unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
1.57      www      1538: 	    $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
1.55      www      1539:         }
1.92      www      1540:     } elsif ($nfield eq 'insertrow') {
1.93      www      1541:         $countrows++;
1.95      www      1542:         my $newrow=substr('000000'.$countrows,-7);
1.92      www      1543:         if ($nform eq 'top') {
1.94      www      1544: 	    $fo{'A'.$countrows}='--- '.$newrow;
1.92      www      1545:         } else {
1.94      www      1546:             $fo{'A'.$countrows}='~~~ '.$newrow;
1.92      www      1547:         }
1.55      www      1548:     } else {
                   1549:        if ($nfield) { $fo{$nfield}=$nform; }
                   1550:     }
1.10      www      1551:     &setformulas($safeeval,%fo);
                   1552: }
                   1553: 
1.11      www      1554: # ================================================================== Parameters
                   1555: # -------------------------------------------- Figure out a cascading parameter
1.28      www      1556: #
1.29      www      1557: # For this function to work
                   1558: #
                   1559: # * parmhash needs to be tied
                   1560: # * courseopt and useropt need to be initialized for this user and course
                   1561: #
1.11      www      1562: 
                   1563: sub parmval {
1.28      www      1564:     my ($what,$safeeval)=@_;
                   1565:     my $cid=&getcid($safeeval);
                   1566:     my $csec=&getcsec($safeeval);
                   1567:     my $uname=&getuname($safeeval);
                   1568:     my $udom=&getudom($safeeval);
                   1569:     my $symb=&getusymb($safeeval);
1.11      www      1570: 
                   1571:     unless ($symb) { return ''; }
                   1572:     my $result='';
                   1573: 
                   1574:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
                   1575: # ----------------------------------------------------- Cascading lookup scheme
1.12      www      1576:        my $rwhat=$what;
                   1577:        $what=~s/^parameter\_//;
1.68      www      1578:        $what=~s/\_([^\_]+)$/\.$1/;
1.11      www      1579: 
                   1580:        my $symbparm=$symb.'.'.$what;
                   1581:        my $mapparm=$mapname.'___(all).'.$what;
1.29      www      1582:        my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
1.11      www      1583: 
                   1584:        my $seclevel=
1.28      www      1585:             $usercourseprefix.'.['.
1.11      www      1586: 		$csec.'].'.$what;
                   1587:        my $seclevelr=
1.28      www      1588:             $usercourseprefix.'.['.
1.11      www      1589: 		$csec.'].'.$symbparm;
                   1590:        my $seclevelm=
1.28      www      1591:             $usercourseprefix.'.['.
1.11      www      1592: 		$csec.'].'.$mapparm;
                   1593: 
                   1594:        my $courselevel=
1.28      www      1595:             $usercourseprefix.'.'.$what;
1.11      www      1596:        my $courselevelr=
1.28      www      1597:             $usercourseprefix.'.'.$symbparm;
1.11      www      1598:        my $courselevelm=
1.28      www      1599:             $usercourseprefix.'.'.$mapparm;
1.12      www      1600: 
1.11      www      1601: # ---------------------------------------------------------- fourth, check user
                   1602:       
                   1603:       if ($uname) { 
                   1604: 
                   1605:        if ($useropt{$courselevelr}) { return $useropt{$courselevelr}; }
                   1606: 
                   1607:        if ($useropt{$courselevelm}) { return $useropt{$courselevelm}; }
                   1608: 
                   1609:        if ($useropt{$courselevel}) { return $useropt{$courselevel}; }
                   1610: 
                   1611:       }
                   1612: 
                   1613: # --------------------------------------------------------- third, check course
                   1614:      
                   1615:        if ($csec) {
                   1616:  
                   1617:         if ($courseopt{$seclevelr}) { return $courseopt{$seclevelr}; }
                   1618: 
                   1619:         if ($courseopt{$seclevelm}) { return $courseopt{$seclevelm}; }  
                   1620: 
                   1621:         if ($courseopt{$seclevel}) { return $courseopt{$seclevel}; }
                   1622:   
                   1623:       }
                   1624: 
                   1625:        if ($courseopt{$courselevelr}) { return $courseopt{$courselevelr}; }
                   1626: 
                   1627:        if ($courseopt{$courselevelm}) { return $courseopt{$courselevelm}; }
                   1628: 
                   1629:        if ($courseopt{$courselevel}) { return $courseopt{$courselevel}; }
                   1630: 
                   1631: # ----------------------------------------------------- second, check map parms
                   1632: 
                   1633:        my $thisparm=$parmhash{$symbparm};
                   1634:        if ($thisparm) { return $thisparm; }
                   1635: 
                   1636: # -------------------------------------------------------- first, check default
                   1637: 
1.12      www      1638:        return &Apache::lonnet::metadata($fn,$rwhat.'.default');
1.11      www      1639:         
                   1640: }
                   1641: 
1.23      www      1642: # ---------------------------------------------- Update rows for course listing
1.11      www      1643: 
1.28      www      1644: sub updateclasssheet {
1.23      www      1645:     my $safeeval=shift;
1.28      www      1646:     my $cnum=&getcnum($safeeval);
                   1647:     my $cdom=&getcdom($safeeval);
                   1648:     my $cid=&getcid($safeeval);
                   1649:     my $chome=&getchome($safeeval);
                   1650: 
                   1651: # ---------------------------------------------- Read class list and row labels
                   1652: 
1.23      www      1653:     my $classlst=&Apache::lonnet::reply
1.28      www      1654:                                  ('dump:'.$cdom.':'.$cnum.':classlist',$chome);
1.23      www      1655:     my %currentlist=();
                   1656:     my $now=time;
                   1657:     unless ($classlst=~/^error\:/) {
1.78      matthew  1658:         foreach (split(/\&/,$classlst)) {
1.23      www      1659:             my ($name,$value)=split(/\=/,$_);
1.24      www      1660:             my ($end,$start)=split(/\:/,&Apache::lonnet::unescape($value));
1.23      www      1661:             my $active=1;
                   1662:             if (($end) && ($now>$end)) { $active=0; }
1.98      matthew  1663:             $active = 1 if ($ENV{'form.Status'} eq 'Any');
                   1664:             $active = !$active if ($ENV{'form.Status'} eq 'Expired');
1.23      www      1665:             if ($active) {
1.24      www      1666:                 my $rowlabel='';
                   1667:                 $name=&Apache::lonnet::unescape($name);
1.28      www      1668:                 my ($sname,$sdom)=split(/\:/,$name);
                   1669:                 my $ssec=&Apache::lonnet::usection($sdom,$sname,$cid);
                   1670:                 if ($ssec==-1) {
1.71      www      1671: 		   unless ($ENV{'form.showcsv'}) {
1.24      www      1672:                     $rowlabel='<font color=red>Data not available: '.$name.
                   1673: 			      '</font>';
1.71      www      1674: 		   } else {
                   1675: 		       $rowlabel='ERROR","'.$name.
                   1676:                                  '","Data not available","","","';
                   1677:                    }
1.24      www      1678:                 } else {
1.28      www      1679:                     my %reply=&Apache::lonnet::idrget($sdom,$sname);
                   1680:                     my $reply=&Apache::lonnet::reply('get:'.$sdom.':'.$sname.
1.24      www      1681: 		      ':environment:firstname&middlename&lastname&generation',
1.28      www      1682:                       &Apache::lonnet::homeserver($sname,$sdom));
1.71      www      1683: 		   unless ($ENV{'form.showcsv'}) {
1.45      www      1684:                     $rowlabel='<a href="/adm/studentcalc?uname='.$sname.
                   1685:                               '&udom='.$sdom.'">'.
                   1686:                               $ssec.'&nbsp;'.$reply{$sname}.'<br>';
1.78      matthew  1687:                     foreach ( split(/\&/,$reply)) {
1.24      www      1688:                         $rowlabel.=&Apache::lonnet::unescape($_).' ';
1.78      matthew  1689:                     }
1.45      www      1690:                     $rowlabel.='</a>';
1.71      www      1691: 		   } else {
                   1692: 		    $rowlabel=$ssec.'","'.$reply{$sname}.'"';
                   1693:                     my $ncount=0;
1.78      matthew  1694:                     foreach (split(/\&/,$reply)) {
1.71      www      1695:                         $rowlabel.=',"'.&Apache::lonnet::unescape($_).'"';
                   1696:                         $ncount++;
1.78      matthew  1697:                     }
1.71      www      1698:                     unless ($ncount==4) { $rowlabel.=',""'; }
                   1699:                     $rowlabel=~s/\"$//;
                   1700: 		   }
1.24      www      1701:                 }
                   1702: 		$currentlist{&Apache::lonnet::unescape($name)}=$rowlabel;
1.23      www      1703:             }
1.78      matthew  1704:         } # end of foreach (split(/\&/,$classlst))
1.23      www      1705: #
                   1706: # -------------------- Find discrepancies between the course row table and this
                   1707: #
                   1708:         my %f=&getformulas($safeeval);
                   1709:         my $changed=0;
                   1710: 
                   1711:         my $maxrow=0;
                   1712:         my %existing=();
                   1713: 
                   1714: # ----------------------------------------------------------- Now obsolete rows
1.78      matthew  1715: 	foreach (keys(%f)) {
1.23      www      1716: 	    if ($_=~/^A(\d+)/) {
                   1717:                 $maxrow=($1>$maxrow)?$1:$maxrow;
                   1718:                 $existing{$f{$_}}=1;
1.97      www      1719: 		unless ((defined($currentlist{$f{$_}})) || (!$1) ||
                   1720:                         ($f{$_}=~/^(\~\~\~|\-\-\-)/)) {
1.23      www      1721: 		   $f{$_}='!!! Obsolete';
                   1722:                    $changed=1;
                   1723:                 }
                   1724:             }
1.78      matthew  1725:         }
1.23      www      1726: 
                   1727: # -------------------------------------------------------- New and unknown keys
                   1728:      
1.78      matthew  1729:         foreach (sort keys(%currentlist)) {
1.23      www      1730:             unless ($existing{$_}) {
                   1731: 		$changed=1;
                   1732:                 $maxrow++;
                   1733:                 $f{'A'.$maxrow}=$_;
                   1734:             }
1.78      matthew  1735:         }
1.23      www      1736:      
                   1737:         if ($changed) { &setformulas($safeeval,%f); }
                   1738: 
                   1739:         &setmaxrow($safeeval,$maxrow);
                   1740:         &setrowlabels($safeeval,%currentlist);
                   1741: 
                   1742:     } else {
                   1743:         return 'Could not access course data';
                   1744:     }
                   1745: }
1.5       www      1746: 
1.28      www      1747: # ----------------------------------- Update rows for student and assess sheets
                   1748: 
                   1749: sub updatestudentassesssheet {
1.5       www      1750:     my $safeeval=shift;
                   1751:     my %bighash;
1.35      www      1752:     my $stype=&gettype($safeeval);
                   1753:     my %current=();
                   1754:     unless ($updatedata{$ENV{'request.course.fn'}.'_'.$stype}) {
1.5       www      1755: # -------------------------------------------------------------------- Tie hash
                   1756:       if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1.99      albertel 1757:                        &GDBM_READER(),0640)) {
1.5       www      1758: # --------------------------------------------------------- Get all assessments
                   1759: 
1.52      www      1760: 	my %allkeys=('timestamp' => 
1.75      www      1761:                      'Timestamp of Last Transaction<br>timestamp',
                   1762:                      'subnumber' =>
                   1763:                      'Number of Submissions<br>subnumber',
                   1764:                      'tutornumber' =>
                   1765:                      'Number of Tutor Responses<br>tutornumber',
                   1766:                      'totalpoints' =>
                   1767:                      'Total Points Granted<br>totalpoints');
1.5       www      1768: 
1.50      www      1769:         my $adduserstr='';
                   1770:         if ((&getuname($safeeval) ne $ENV{'user.name'}) ||
                   1771:             (&getudom($safeeval) ne $ENV{'user.domain'})) {
                   1772:             $adduserstr='&uname='.&getuname($safeeval).
                   1773: 		'&udom='.&getudom($safeeval);
                   1774:         }
                   1775: 
1.72      www      1776:         my %allassess=('_feedback' =>
                   1777: 	              '<a href="/adm/assesscalc?usymb=_feedback'.$adduserstr.
                   1778:                        '">Feedback</a>',
                   1779:                        '_evaluation' =>
                   1780: 	              '<a href="/adm/assesscalc?usymb=_evaluation'.$adduserstr.
                   1781:                        '">Evaluation</a>',
                   1782:                        '_tutoring' =>
                   1783: 	              '<a href="/adm/assesscalc?usymb=_tutoring'.$adduserstr.
1.74      www      1784:                        '">Tutoring</a>',
                   1785:                        '_discussion' =>
                   1786: 	              '<a href="/adm/assesscalc?usymb=_discussion'.$adduserstr.
                   1787:                        '">Discussion</a>'
1.72      www      1788:         );
                   1789: 
1.78      matthew  1790:         foreach (keys(%bighash)) {
1.5       www      1791: 	    if ($_=~/^src\_(\d+)\.(\d+)$/) {
                   1792: 	       my $mapid=$1;
                   1793:                my $resid=$2;
                   1794:                my $id=$mapid.'.'.$resid;
                   1795:                my $srcf=$bighash{$_};
                   1796:                if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
                   1797:                  my $symb=
                   1798:                      &Apache::lonnet::declutter($bighash{'map_id_'.$mapid}).
                   1799: 			    '___'.$resid.'___'.
                   1800: 			    &Apache::lonnet::declutter($srcf);
1.38      www      1801: 		 $allassess{$symb}=
1.50      www      1802: 	            '<a href="/adm/assesscalc?usymb='.$symb.$adduserstr.'">'.
                   1803:                      $bighash{'title_'.$id}.'</a>';
1.6       www      1804:                  if ($stype eq 'assesscalc') {
1.78      matthew  1805: 		     foreach (split(/\,/,
                   1806: 				    &Apache::lonnet::metadata($srcf,'keys'))) {
1.11      www      1807:                        if (($_=~/^stores\_(.*)/) || ($_=~/^parameter\_(.*)/)) {
1.5       www      1808: 			  my $key=$_;
                   1809:                           my $display=
                   1810: 			      &Apache::lonnet::metadata($srcf,$key.'.display');
                   1811:                           unless ($display) {
1.40      www      1812:                               $display.=
1.5       www      1813: 			         &Apache::lonnet::metadata($srcf,$key.'.name');
                   1814:                           }
1.40      www      1815:                           $display.='<br>'.$key;
1.5       www      1816:                           $allkeys{$key}=$display;
                   1817: 		       }
1.78      matthew  1818:                    } # end of foreach
1.5       www      1819: 	         }
                   1820: 	      }
                   1821: 	   }
1.78      matthew  1822:         } # end of foreach (keys(%bighash))
1.5       www      1823:         untie(%bighash);
                   1824:     
                   1825: #
1.11      www      1826: # %allkeys has a list of storage and parameter displays by unikey
1.5       www      1827: # %allassess has a list of all resource displays by symb
                   1828: #
1.6       www      1829: 
                   1830:         if ($stype eq 'assesscalc') {
                   1831: 	    %current=%allkeys;
                   1832:         } elsif ($stype eq 'studentcalc') {
                   1833:             %current=%allassess;
                   1834:         }
1.35      www      1835:         $updatedata{$ENV{'request.course.fn'}.'_'.$stype}=
                   1836: 	    join('___;___',%current);
                   1837:     } else {
                   1838:         return 'Could not access course data';
                   1839:     }
                   1840: # ------------------------------------------------------ Get current from cache
                   1841:     } else {
                   1842:         %current=split(/\_\_\_\;\_\_\_/,
                   1843: 		       $updatedata{$ENV{'request.course.fn'}.'_'.$stype});
                   1844:     }
                   1845: # -------------------- Find discrepancies between the course row table and this
                   1846: #
                   1847:         my %f=&getformulas($safeeval);
                   1848:         my $changed=0;
1.6       www      1849: 
                   1850:         my $maxrow=0;
                   1851:         my %existing=();
                   1852: 
                   1853: # ----------------------------------------------------------- Now obsolete rows
1.78      matthew  1854: 	foreach (keys(%f)) {
1.6       www      1855: 	    if ($_=~/^A(\d+)/) {
                   1856:                 $maxrow=($1>$maxrow)?$1:$maxrow;
1.57      www      1857:                 my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
                   1858:                 $existing{$usy}=1;
1.97      www      1859: 		unless ((defined($current{$usy})) || (!$1) ||
                   1860:                         ($f{$_}=~/^(\~\~\~|\-\-\-)/)){
                   1861:  		   $f{$_}='!!! Obsolete';
1.6       www      1862:                    $changed=1;
1.57      www      1863: 	        } elsif ($ufn) {
                   1864: 		    $current{$usy}
                   1865:                        =~s/assesscalc\?usymb\=/assesscalc\?ufn\=$ufn\&usymb\=/;
1.5       www      1866:                 }
                   1867:             }
1.78      matthew  1868:         }
1.6       www      1869: 
                   1870: # -------------------------------------------------------- New and unknown keys
                   1871:      
1.78      matthew  1872:         foreach (keys(%current)) {
1.6       www      1873:             unless ($existing{$_}) {
                   1874: 		$changed=1;
                   1875:                 $maxrow++;
                   1876:                 $f{'A'.$maxrow}=$_;
                   1877:             }
1.78      matthew  1878:         }
1.35      www      1879:     
1.6       www      1880:         if ($changed) { &setformulas($safeeval,%f); }
                   1881: 
                   1882:         &setmaxrow($safeeval,$maxrow);
                   1883:         &setrowlabels($safeeval,%current);
1.35      www      1884:  
                   1885:         undef %current;
                   1886:         undef %existing;
1.5       www      1887: }
1.3       www      1888: 
1.24      www      1889: # ------------------------------------------------ Load data for one assessment
1.16      www      1890: 
1.29      www      1891: sub loadstudent {
1.16      www      1892:     my $safeeval=shift;
                   1893:     my %c=();
                   1894:     my %f=&getformulas($safeeval);
1.39      www      1895:     $cachedassess=&getuname($safeeval).':'.&getudom($safeeval);
                   1896:     %cachedstores=();
                   1897:     {
                   1898:       my $reply=&Apache::lonnet::reply('dump:'.&getudom($safeeval).':'.
                   1899:                                                &getuname($safeeval).':'.
                   1900:                                                &getcid($safeeval),
                   1901:                                                &getuhome($safeeval));
                   1902:       unless ($reply=~/^error\:/) {
1.78      matthew  1903: 	 foreach ( split(/\&/,$reply)) {
1.39      www      1904:             my ($name,$value)=split(/\=/,$_);
                   1905:             $cachedstores{&Apache::lonnet::unescape($name)}=
                   1906: 	                  &Apache::lonnet::unescape($value);
1.78      matthew  1907: 	}
1.39      www      1908:       }
                   1909:     }
1.36      www      1910:     my @assessdata=();
1.78      matthew  1911:     foreach (keys(%f)) {
1.17      www      1912: 	if ($_=~/^A(\d+)/) {
                   1913: 	   my $row=$1;
1.97      www      1914:            unless (($f{$_}=~/^[\!\~\-]/) || ($row==0)) {
1.55      www      1915: 	      my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
1.36      www      1916: 	      @assessdata=&exportsheet(&getuname($safeeval),
                   1917:                                        &getudom($safeeval),
1.55      www      1918:                                        'assesscalc',$usy,$ufn);
1.17      www      1919:               my $index=0;
1.78      matthew  1920:               foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
                   1921: 	               'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1.30      www      1922:                   if ($assessdata[$index]) {
1.41      www      1923: 		     my $col=$_;
                   1924: 		     if ($assessdata[$index]=~/\D/) {
                   1925:                          $c{$col.$row}="'".$assessdata[$index]."'";
                   1926:  		     } else {
                   1927: 		         $c{$col.$row}=$assessdata[$index];
                   1928: 		     }
                   1929:                      unless ($col eq 'A') { 
                   1930: 			 $f{$col.$row}='import';
1.30      www      1931:                      }
                   1932: 		  }
                   1933:                   $index++;
1.78      matthew  1934:               }
1.16      www      1935: 	   }
                   1936:         }
1.78      matthew  1937:     }
1.39      www      1938:     $cachedassess='';
                   1939:     undef %cachedstores;
1.18      www      1940:     &setformulas($safeeval,%f);
1.16      www      1941:     &setconstants($safeeval,%c);
                   1942: }
                   1943: 
1.24      www      1944: # --------------------------------------------------- Load data for one student
                   1945: 
1.30      www      1946: sub loadcourse {
1.37      www      1947:     my ($safeeval,$r)=@_;
1.24      www      1948:     my %c=();
                   1949:     my %f=&getformulas($safeeval);
1.37      www      1950:     my $total=0;
1.78      matthew  1951:     foreach (keys(%f)) {
1.37      www      1952: 	if ($_=~/^A(\d+)/) {
1.97      www      1953: 	    unless ($f{$_}=~/^[\!\~\-]/) { $total++; }
1.37      www      1954:         }
1.78      matthew  1955:     }
1.37      www      1956:     my $now=0;
                   1957:     my $since=time;
1.39      www      1958:     $r->print(<<ENDPOP);
                   1959: <script>
                   1960:     popwin=open('','popwin','width=400,height=100');
                   1961:     popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
1.50      www      1962:       '<h3>Spreadsheet Calculation Progress</h3>'+
1.39      www      1963:       '<form name=popremain>'+
                   1964:       '<input type=text size=35 name=remaining value=Starting></form>'+
                   1965:       '</body></html>');
1.42      www      1966:     popwin.document.close();
1.39      www      1967: </script>
                   1968: ENDPOP
1.37      www      1969:     $r->rflush();
1.78      matthew  1970:     foreach (keys(%f)) {
1.24      www      1971: 	if ($_=~/^A(\d+)/) {
                   1972: 	   my $row=$1;
1.97      www      1973:            unless (($f{$_}=~/^[\!\~\-]/)  || ($row==0)) {
1.37      www      1974: 	      my @studentdata=&exportsheet(split(/\:/,$f{$_}),
1.30      www      1975:                                            'studentcalc');
1.37      www      1976:               undef %userrdatas;
                   1977:               $now++;
1.39      www      1978:               $r->print('<script>popwin.document.popremain.remaining.value="'.
1.37      www      1979:                   $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
1.39      www      1980:                         ' secs remaining";</script>');
1.37      www      1981:               $r->rflush(); 
                   1982: 
1.24      www      1983:               my $index=0;
1.78      matthew  1984:              foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
                   1985: 	              'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1.30      www      1986:                   if ($studentdata[$index]) {
1.41      www      1987: 		     my $col=$_;
                   1988: 		     if ($studentdata[$index]=~/\D/) {
                   1989:                          $c{$col.$row}="'".$studentdata[$index]."'";
                   1990:  		     } else {
                   1991: 		         $c{$col.$row}=$studentdata[$index];
                   1992: 		     }
                   1993:                      unless ($col eq 'A') { 
                   1994: 			 $f{$col.$row}='import';
1.30      www      1995:                      }
                   1996: 		  }
                   1997:                   $index++;
1.78      matthew  1998:               }
1.24      www      1999: 	   }
                   2000:         }
1.78      matthew  2001:     }
1.24      www      2002:     &setformulas($safeeval,%f);
                   2003:     &setconstants($safeeval,%c);
1.43      www      2004:     $r->print('<script>popwin.close()</script>');
1.37      www      2005:     $r->rflush(); 
1.24      www      2006: }
                   2007: 
1.6       www      2008: # ------------------------------------------------ Load data for one assessment
                   2009: 
1.29      www      2010: sub loadassessment {
                   2011:     my $safeeval=shift;
                   2012: 
                   2013:     my $uhome=&getuhome($safeeval);
                   2014:     my $uname=&getuname($safeeval);
                   2015:     my $udom=&getudom($safeeval);
                   2016:     my $symb=&getusymb($safeeval);
                   2017:     my $cid=&getcid($safeeval);
                   2018:     my $cnum=&getcnum($safeeval);
                   2019:     my $cdom=&getcdom($safeeval);
                   2020:     my $chome=&getchome($safeeval);
                   2021: 
1.6       www      2022:     my $namespace;
1.29      www      2023:     unless ($namespace=$cid) { return ''; }
1.11      www      2024: 
                   2025: # ----------------------------------------------------------- Get stored values
1.39      www      2026: 
                   2027:    my %returnhash=();
                   2028: 
                   2029:    if ($cachedassess eq $uname.':'.$udom) {
                   2030: #
                   2031: # get data out of the dumped stores
                   2032: # 
                   2033: 
                   2034:        my $version=$cachedstores{'version:'.$symb};
                   2035:        my $scope;
                   2036:        for ($scope=1;$scope<=$version;$scope++) {
1.78      matthew  2037:            foreach (split(/\:/,$cachedstores{$scope.':keys:'.$symb})) {
1.39      www      2038:                $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
1.78      matthew  2039:            } 
1.39      www      2040:        }
                   2041: 
                   2042:    } else {
                   2043: #
                   2044: # restore individual
                   2045: #
                   2046: 
1.11      www      2047:     my $answer=&Apache::lonnet::reply(
1.15      www      2048:        "restore:$udom:$uname:".
                   2049:        &Apache::lonnet::escape($namespace).":".
                   2050:        &Apache::lonnet::escape($symb),$uhome);
1.78      matthew  2051:     foreach (split(/\&/,$answer)) {
1.6       www      2052: 	my ($name,$value)=split(/\=/,$_);
1.11      www      2053:         $returnhash{&Apache::lonnet::unescape($name)}=
                   2054:                     &Apache::lonnet::unescape($value);
1.78      matthew  2055:     }
1.6       www      2056:     my $version;
                   2057:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.78      matthew  2058:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
1.6       www      2059:           $returnhash{$_}=$returnhash{$version.':'.$_};
1.78      matthew  2060:        } 
1.6       www      2061:     }
1.39      www      2062:    }
1.11      www      2063: # ----------------------------- returnhash now has all stores for this resource
1.76      www      2064: 
                   2065: # --------- convert all "_" to "." to be able to use libraries, multiparts, etc
                   2066: 
                   2067:     my @oldkeys=keys %returnhash;
                   2068: 
1.78      matthew  2069:     foreach (@oldkeys) {
1.76      www      2070:         my $name=$_;
                   2071:         my $value=$returnhash{$_};
                   2072:         delete $returnhash{$_};
                   2073:         $name=~s/\_/\./g;
                   2074:         $returnhash{$name}=$value;
1.78      matthew  2075:     }
1.11      www      2076: 
                   2077: # ---------------------------- initialize coursedata and userdata for this user
1.31      www      2078:     undef %courseopt;
                   2079:     undef %useropt;
1.29      www      2080: 
                   2081:     my $userprefix=$uname.'_'.$udom.'_';
                   2082: 
1.11      www      2083:     unless ($uhome eq 'no_host') { 
                   2084: # -------------------------------------------------------------- Get coursedata
1.13      www      2085:       unless
1.32      www      2086:         ((time-$courserdatas{$cid.'.last_cache'})<240) {
1.29      www      2087:          my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
                   2088:               ':resourcedata',$chome);
1.11      www      2089:          if ($reply!~/^error\:/) {
1.29      www      2090:             $courserdatas{$cid}=$reply;
                   2091:             $courserdatas{$cid.'.last_cache'}=time;
1.11      www      2092:          }
                   2093:       }
1.78      matthew  2094:       foreach (split(/\&/,$courserdatas{$cid})) {
1.11      www      2095:          my ($name,$value)=split(/\=/,$_);
1.29      www      2096:          $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
1.11      www      2097:                     &Apache::lonnet::unescape($value);  
1.78      matthew  2098:       }
1.11      www      2099: # --------------------------------------------------- Get userdata (if present)
1.13      www      2100:       unless
1.32      www      2101:         ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
1.11      www      2102:          my $reply=
                   2103:        &Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
                   2104:          if ($reply!~/^error\:/) {
                   2105: 	     $userrdatas{$uname.'___'.$udom}=$reply;
1.13      www      2106: 	     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
1.11      www      2107:          }
                   2108:       }
1.78      matthew  2109:       foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
1.11      www      2110:          my ($name,$value)=split(/\=/,$_);
1.29      www      2111:          $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
1.15      www      2112: 	          &Apache::lonnet::unescape($value);
1.78      matthew  2113:       }
1.29      www      2114:     }
                   2115: # ----------------- now courseopt, useropt initialized for this user and course
                   2116: # (used by parmval)
                   2117: 
1.60      www      2118: #
                   2119: # Load keys for this assessment only
                   2120: #
                   2121:     my %thisassess=();
                   2122:     my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
                   2123:     
1.78      matthew  2124:     foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
1.60      www      2125:         $thisassess{$_}=1;
1.78      matthew  2126:     } 
1.60      www      2127: #
                   2128: # Load parameters
                   2129: #
1.29      www      2130:    my %c=();
1.6       www      2131: 
1.29      www      2132:    if (tie(%parmhash,'GDBM_File',
1.99      albertel 2133:            &getcfn($safeeval).'_parms.db',&GDBM_READER(),0640)) {
1.6       www      2134:     my %f=&getformulas($safeeval);
1.78      matthew  2135:     foreach (keys(%f))  {
1.6       www      2136: 	if ($_=~/^A/) {
1.97      www      2137:             unless ($f{$_}=~/^[\!\~\-]/) {
1.11      www      2138:   	       if ($f{$_}=~/^parameter/) {
1.60      www      2139: 		if ($thisassess{$f{$_}}) {
1.40      www      2140:                   my $val=&parmval($f{$_},$safeeval);
                   2141:                   $c{$_}=$val;
                   2142:                   $c{$f{$_}}=$val;
1.60      www      2143: 	        }
1.11      www      2144: 	       } else {
1.15      www      2145: 		  my $key=$f{$_};
1.40      www      2146:                   my $ckey=$key;
1.15      www      2147:                   $key=~s/^stores\_/resource\./;
1.70      www      2148:                   $key=~s/\_/\./g;
1.15      www      2149:  	          $c{$_}=$returnhash{$key};
1.40      www      2150:                   $c{$ckey}=$returnhash{$key};
1.11      www      2151: 	       }
                   2152: 	   }
1.6       www      2153:         }
1.78      matthew  2154:     }
1.29      www      2155:     untie(%parmhash);
                   2156:    }
                   2157:    &setconstants($safeeval,%c);
1.6       www      2158: }
                   2159: 
1.10      www      2160: # --------------------------------------------------------- Various form fields
                   2161: 
                   2162: sub textfield {
                   2163:     my ($title,$name,$value)=@_;
                   2164:     return "\n<p><b>$title:</b><br>".
                   2165:            '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
                   2166: }
                   2167: 
                   2168: sub hiddenfield {
                   2169:     my ($name,$value)=@_;
                   2170:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
                   2171: }
                   2172: 
                   2173: sub selectbox {
                   2174:     my ($title,$name,$value,%options)=@_;
                   2175:     my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
1.78      matthew  2176:     foreach (sort keys(%options)) {
1.10      www      2177:         $selout.='<option value="'.$_.'"';
                   2178:         if ($_ eq $value) { $selout.=' selected'; }
                   2179:         $selout.='>'.$options{$_}.'</option>';
1.78      matthew  2180:     }
1.10      www      2181:     return $selout.'</select>';
                   2182: }
                   2183: 
1.28      www      2184: # =============================================== Update information in a sheet
                   2185: #
                   2186: # Add new users or assessments, etc.
                   2187: #
                   2188: 
                   2189: sub updatesheet {
                   2190:     my $safeeval=shift;
                   2191:     my $stype=&gettype($safeeval);
                   2192:     if ($stype eq 'classcalc') {
                   2193: 	return &updateclasssheet($safeeval);
                   2194:     } else {
                   2195:         return &updatestudentassesssheet($safeeval);
                   2196:     }
                   2197: }
                   2198: 
                   2199: # =================================================== Load the rows for a sheet
                   2200: #
                   2201: # Import the data for rows
                   2202: #
                   2203: 
1.37      www      2204: sub loadrows {
                   2205:     my ($safeeval,$r)=@_;
1.28      www      2206:     my $stype=&gettype($safeeval);
                   2207:     if ($stype eq 'classcalc') {
1.37      www      2208: 	&loadcourse($safeeval,$r);
1.28      www      2209:     } elsif ($stype eq 'studentcalc') {
1.29      www      2210:         &loadstudent($safeeval);
1.28      www      2211:     } else {
1.29      www      2212:         &loadassessment($safeeval);
1.28      www      2213:     }
                   2214: }
                   2215: 
1.47      www      2216: # ======================================================= Forced recalculation?
                   2217: 
                   2218: sub checkthis {
                   2219:     my ($keyname,$time)=@_;
                   2220:     return ($time<$expiredates{$keyname});
                   2221: }
                   2222: sub forcedrecalc {
                   2223:     my ($uname,$udom,$stype,$usymb)=@_;
                   2224:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
                   2225:     my $time=$oldsheets{$key.'.time'};
1.53      www      2226:     if ($ENV{'form.forcerecalc'}) { return 1; }
1.47      www      2227:     unless ($time) { return 1; }
                   2228:     if ($stype eq 'assesscalc') {
                   2229:         my $map=(split(/\_\_\_/,$usymb))[0];
                   2230:         if (&checkthis('::assesscalc:',$time) ||
                   2231:             &checkthis('::assesscalc:'.$map,$time) ||
                   2232:             &checkthis('::assesscalc:'.$usymb,$time) ||
1.49      www      2233:             &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
                   2234:             &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
                   2235:             &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
1.47      www      2236:             return 1;
                   2237:         } 
                   2238:     } else {
                   2239:         if (&checkthis('::studentcalc:',$time) || 
1.51      www      2240:             &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
1.47      www      2241: 	    return 1;
                   2242:         }
                   2243:     }
                   2244:     return 0; 
                   2245: }
                   2246: 
1.28      www      2247: # ============================================================== Export handler
                   2248: #
                   2249: # Non-interactive call from with program
                   2250: #
                   2251: 
                   2252: sub exportsheet {
1.44      www      2253:  my ($uname,$udom,$stype,$usymb,$fn)=@_;
                   2254:  my @exportarr=();
1.74      www      2255: 
                   2256:  if (($usymb=~/^\_(\w+)/) && (!$fn)) {
                   2257:     $fn='default_'.$1;
                   2258:  }
                   2259: 
1.44      www      2260: #
                   2261: # Check if cached
                   2262: #
1.46      www      2263: 
1.44      www      2264:  my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
                   2265:  my $found='';
                   2266: 
                   2267:  if ($oldsheets{$key}) {
1.78      matthew  2268:      foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
1.44      www      2269:          my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
                   2270:          if ($name eq $fn) {
                   2271: 	     $found=$value;
                   2272:          }
1.78      matthew  2273:      }
1.44      www      2274:  }
                   2275: 
1.46      www      2276:  unless ($found) {
                   2277:      &cachedssheets($uname,$udom,&Apache::lonnet::homeserver($uname,$udom));
                   2278:      if ($oldsheets{$key}) {
1.78      matthew  2279: 	foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
1.46      www      2280:             my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
                   2281:             if ($name eq $fn) {
                   2282: 	        $found=$value;
                   2283:             }
1.78      matthew  2284:         } 
1.46      www      2285:      }
                   2286:  }
1.47      www      2287: #
                   2288: # Check if still valid
                   2289: #
                   2290:  if ($found) {
                   2291:      if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
                   2292: 	 $found='';
                   2293:      }
                   2294:  }
                   2295:  
1.44      www      2296:  if ($found) {
                   2297: #
                   2298: # Return what was cached
                   2299: #
                   2300:      @exportarr=split(/\_\_\_\;\_\_\_/,$found);
                   2301: 
                   2302:  } else {
                   2303: #
                   2304: # Not cached
1.46      www      2305: #        
                   2306: 
1.29      www      2307:     my $thissheet=&makenewsheet($uname,$udom,$stype,$usymb);
1.28      www      2308:     &readsheet($thissheet,$fn);
                   2309:     &updatesheet($thissheet);
                   2310:     &loadrows($thissheet);
1.44      www      2311:     &calcsheet($thissheet); 
                   2312:     @exportarr=&exportdata($thissheet);
                   2313: #
                   2314: # Store now
                   2315: #
                   2316:     my $cid=$ENV{'request.course.id'}; 
1.47      www      2317:     my $current='';
1.46      www      2318:     if ($stype eq 'studentcalc') {
                   2319:        $current=&Apache::lonnet::reply('get:'.
1.44      www      2320:                                      $ENV{'course.'.$cid.'.domain'}.':'.
                   2321:                                      $ENV{'course.'.$cid.'.num'}.
                   2322: 				     ':nohist_calculatedsheets:'.
                   2323:                                      &Apache::lonnet::escape($key),
                   2324:                                      $ENV{'course.'.$cid.'.home'});
1.46      www      2325:     } else {
                   2326:        $current=&Apache::lonnet::reply('get:'.
                   2327:                                      &getudom($thissheet).':'.
                   2328:                                      &getuname($thissheet).
                   2329: 				     ':nohist_calculatedsheets_'.
                   2330:                                      $ENV{'request.course.id'}.':'.
                   2331:                                      &Apache::lonnet::escape($key),
                   2332:                                      &getuhome($thissheet));
                   2333: 
                   2334:     }
1.44      www      2335:     my %currentlystored=();
                   2336:     unless ($current=~/^error\:/) {
1.78      matthew  2337:        foreach (split(/\_\_\_\&\_\_\_/,&Apache::lonnet::unescape($current))) {
1.44      www      2338:            my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
                   2339:            $currentlystored{$name}=$value;
1.78      matthew  2340:        }
1.44      www      2341:     }
                   2342:     $currentlystored{$fn}=join('___;___',@exportarr);
                   2343: 
                   2344:     my $newstore='';
1.78      matthew  2345:     foreach (keys(%currentlystored)) {
1.44      www      2346:         if ($newstore) { $newstore.='___&___'; }
                   2347:         $newstore.=$_.'___=___'.$currentlystored{$_};
1.78      matthew  2348:     }
1.47      www      2349:     my $now=time;
1.46      www      2350:     if ($stype eq 'studentcalc') {
                   2351:        &Apache::lonnet::reply('put:'.
1.44      www      2352:                          $ENV{'course.'.$cid.'.domain'}.':'.
                   2353:                          $ENV{'course.'.$cid.'.num'}.
                   2354: 			 ':nohist_calculatedsheets:'.
                   2355:                          &Apache::lonnet::escape($key).'='.
1.47      www      2356: 			 &Apache::lonnet::escape($newstore).'&'.
                   2357:                          &Apache::lonnet::escape($key).'.time='.$now,
1.44      www      2358:                          $ENV{'course.'.$cid.'.home'});
1.46      www      2359:    } else {
                   2360:        &Apache::lonnet::reply('put:'.
                   2361:                          &getudom($thissheet).':'.
                   2362:                          &getuname($thissheet).
                   2363: 			 ':nohist_calculatedsheets_'.
                   2364:                          $ENV{'request.course.id'}.':'.
                   2365:                          &Apache::lonnet::escape($key).'='.
1.47      www      2366: 			 &Apache::lonnet::escape($newstore).'&'.
                   2367:                          &Apache::lonnet::escape($key).'.time='.$now,
1.46      www      2368:                          &getuhome($thissheet));
                   2369:    }
1.44      www      2370:  }
                   2371:  return @exportarr;
                   2372: }
1.48      www      2373: # ============================================================ Expiration Dates
                   2374: #
                   2375: # Load previously cached student spreadsheets for this course
                   2376: #
                   2377: 
                   2378: sub expirationdates {
                   2379:     undef %expiredates;
                   2380:     my $cid=$ENV{'request.course.id'};
                   2381:     my $reply=&Apache::lonnet::reply('dump:'.
                   2382: 				     $ENV{'course.'.$cid.'.domain'}.':'.
                   2383:                                      $ENV{'course.'.$cid.'.num'}.
                   2384: 				     ':nohist_expirationdates',
                   2385:                                      $ENV{'course.'.$cid.'.home'});
                   2386:     unless ($reply=~/^error\:/) {
1.78      matthew  2387: 	foreach (split(/\&/,$reply)) {
1.48      www      2388:             my ($name,$value)=split(/\=/,$_);
                   2389:             $expiredates{&Apache::lonnet::unescape($name)}
                   2390:                         =&Apache::lonnet::unescape($value);
1.78      matthew  2391:         }
1.48      www      2392:     }
                   2393: }
1.44      www      2394: 
                   2395: # ===================================================== Calculated sheets cache
                   2396: #
1.46      www      2397: # Load previously cached student spreadsheets for this course
1.44      www      2398: #
                   2399: 
1.46      www      2400: sub cachedcsheets {
1.44      www      2401:     my $cid=$ENV{'request.course.id'};
                   2402:     my $reply=&Apache::lonnet::reply('dump:'.
                   2403: 				     $ENV{'course.'.$cid.'.domain'}.':'.
                   2404:                                      $ENV{'course.'.$cid.'.num'}.
                   2405: 				     ':nohist_calculatedsheets',
                   2406:                                      $ENV{'course.'.$cid.'.home'});
                   2407:     unless ($reply=~/^error\:/) {
1.78      matthew  2408: 	foreach ( split(/\&/,$reply)) {
1.44      www      2409:             my ($name,$value)=split(/\=/,$_);
                   2410:             $oldsheets{&Apache::lonnet::unescape($name)}
                   2411:                       =&Apache::lonnet::unescape($value);
1.78      matthew  2412:         }
1.44      www      2413:     }
1.28      www      2414: }
                   2415: 
1.46      www      2416: # ===================================================== Calculated sheets cache
                   2417: #
                   2418: # Load previously cached assessment spreadsheets for this student
                   2419: #
                   2420: 
                   2421: sub cachedssheets {
                   2422:   my ($sname,$sdom,$shome)=@_;
                   2423:   unless (($loadedcaches{$sname.'_'.$sdom}) || ($shome eq 'no_host')) {
                   2424:     my $cid=$ENV{'request.course.id'};
                   2425:     my $reply=&Apache::lonnet::reply('dump:'.$sdom.':'.$sname.
                   2426: 			             ':nohist_calculatedsheets_'.
                   2427:                                       $ENV{'request.course.id'},
                   2428:                                      $shome);
                   2429:     unless ($reply=~/^error\:/) {
1.78      matthew  2430: 	foreach ( split(/\&/,$reply)) {
1.46      www      2431:             my ($name,$value)=split(/\=/,$_);
                   2432:             $oldsheets{&Apache::lonnet::unescape($name)}
                   2433:                       =&Apache::lonnet::unescape($value);
1.78      matthew  2434:         }
1.46      www      2435:     }
                   2436:     $loadedcaches{$sname.'_'.$sdom}=1;
                   2437:   }
                   2438: }
                   2439: 
                   2440: # ===================================================== Calculated sheets cache
                   2441: #
                   2442: # Load previously cached assessment spreadsheets for this student
                   2443: #
                   2444: 
1.12      www      2445: # ================================================================ Main handler
1.28      www      2446: #
                   2447: # Interactive call to screen
                   2448: #
                   2449: #
                   2450: 
1.3       www      2451: 
                   2452: sub handler {
1.7       www      2453:     my $r=shift;
                   2454: 
1.28      www      2455:     if ($r->header_only) {
1.7       www      2456:       $r->content_type('text/html');
                   2457:       $r->send_http_header;
                   2458:       return OK;
1.28      www      2459:     }
                   2460: 
                   2461: # ---------------------------------------------------- Global directory configs
                   2462: 
1.29      www      2463: $includedir=$r->dir_config('lonIncludes');
1.28      www      2464: $tmpdir=$r->dir_config('lonDaemons').'/tmp/';
1.3       www      2465: 
1.7       www      2466: # ----------------------------------------------------- Needs to be in a course
1.3       www      2467: 
1.29      www      2468:   if ($ENV{'request.course.fn'}) { 
1.10      www      2469: 
                   2470: # --------------------------- Get query string for limited number of parameters
1.17      www      2471: 
1.89      matthew  2472:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   2473:                                             ['uname','udom','usymb','ufn']);
1.72      www      2474: 
                   2475:     if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'})) {
                   2476: 	$ENV{'form.ufn'}='default_'.$1;
                   2477:     }
1.10      www      2478: 
1.55      www      2479: # -------------------------------------- Interactive loading of specific sheet?
                   2480:     if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
                   2481: 	$ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
                   2482:     }
1.10      www      2483: # ------------------------------------------- Nothing there? Must be login user
1.29      www      2484: 
                   2485:     my $aname;
                   2486:     my $adom;
                   2487: 
1.10      www      2488:     unless ($ENV{'form.uname'}) {
1.29      www      2489: 	$aname=$ENV{'user.name'};
                   2490:         $adom=$ENV{'user.domain'};
1.11      www      2491:     } else {
1.29      www      2492:         $aname=$ENV{'form.uname'};
                   2493:         $adom=$ENV{'form.udom'};
1.10      www      2494:     }
1.14      www      2495: 
1.10      www      2496: # ------------------------------------------------------------------- Open page
                   2497: 
1.7       www      2498:     $r->content_type('text/html');
1.11      www      2499:     $r->header_out('Cache-control','no-cache');
                   2500:     $r->header_out('Pragma','no-cache');
1.7       www      2501:     $r->send_http_header;
1.3       www      2502: 
1.14      www      2503: # --------------------------------------------------------------- Screen output
                   2504: 
1.10      www      2505:     $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
                   2506:     $r->print(<<ENDSCRIPT);
                   2507: <script language="JavaScript">
                   2508: 
                   2509:     function celledit(cn,cf) {
                   2510:         var cnf=prompt(cn,cf);
1.86      matthew  2511:         if (cnf!=null) {
                   2512:             document.sheet.unewfield.value=cn;
1.10      www      2513:             document.sheet.unewformula.value=cnf;
                   2514:             document.sheet.submit();
                   2515:         }
                   2516:     }
                   2517: 
1.55      www      2518:     function changesheet(cn) {
                   2519: 	document.sheet.unewfield.value=cn;
                   2520:         document.sheet.unewformula.value='changesheet';
                   2521:         document.sheet.submit();
                   2522:     }
                   2523: 
1.92      www      2524:     function insertrow(cn) {
                   2525: 	document.sheet.unewfield.value='insertrow';
                   2526:         document.sheet.unewformula.value=cn;
                   2527:         document.sheet.submit();
                   2528:     }
                   2529: 
1.10      www      2530: </script>
                   2531: ENDSCRIPT
                   2532:     $r->print('</head><body bgcolor="#FFFFFF">'.
1.21      www      2533:        '<img align=right src=/adm/lonIcons/lonlogos.gif>'.
                   2534:        '<h1>LON-CAPA Spreadsheet</h1>'.
1.10      www      2535:        '<form action="'.$r->uri.'" name=sheet method=post>'.
                   2536:        &hiddenfield('uname',$ENV{'form.uname'}).
                   2537:        &hiddenfield('udom',$ENV{'form.udom'}).
                   2538:        &hiddenfield('usymb',$ENV{'form.usymb'}).
                   2539:        &hiddenfield('unewfield','').
                   2540:        &hiddenfield('unewformula',''));
1.29      www      2541: 
                   2542: # ---------------------- Make sure that this gets out, even if user hits "stop"
                   2543: 
1.24      www      2544:     $r->rflush();
1.29      www      2545: 
1.54      www      2546: # ---------------------------------------------------------------- Full recalc?
                   2547: 
                   2548: 
                   2549:     if ($ENV{'form.forcerecalc'}) {
                   2550: 	$r->print('<h4>Completely Recalculating Sheet ...</h4>');
                   2551:         undef %spreadsheets;
                   2552:         undef %courserdatas;
                   2553:         undef %userrdatas;
                   2554:         undef %defaultsheets;
                   2555:         undef %updatedata;
                   2556:    }
                   2557:  
1.14      www      2558: # ---------------------------------------- Read new sheet or modified worksheet
                   2559: 
1.19      www      2560:     $r->uri=~/\/(\w+)$/;
1.14      www      2561: 
1.29      www      2562:     my $asheet=&makenewsheet($aname,$adom,$1,$ENV{'form.usymb'});
                   2563: 
1.30      www      2564: # ------------------------ If a new formula had been entered, go from work copy
                   2565: 
                   2566:     if ($ENV{'form.unewfield'}) {
                   2567:         $r->print('<h2>Modified Workcopy</h2>');
                   2568:         $ENV{'form.unewformula'}=~s/\'/\"/g;
                   2569:         $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
                   2570:                   $ENV{'form.unewformula'}.'<p>');
                   2571:         &setfilename($asheet,$ENV{'form.ufn'});
                   2572: 	&tmpread($asheet,
                   2573:                  $ENV{'form.unewfield'},$ENV{'form.unewformula'});
                   2574: 
                   2575:      } elsif ($ENV{'form.saveas'}) {
                   2576:         &setfilename($asheet,$ENV{'form.ufn'});
                   2577: 	&tmpread($asheet);
                   2578:     } else {
                   2579:         &readsheet($asheet,$ENV{'form.ufn'});
                   2580:     }
                   2581: 
                   2582: # -------------------------------------------------- Print out user information
                   2583: 
                   2584:     unless (&gettype($asheet) eq 'classcalc') {
                   2585:         $r->print('<p><b>User:</b> '.&getuname($asheet).
                   2586:                   '<br><b>Domain:</b> '.&getudom($asheet));
                   2587:         if (&getcsec($asheet) eq '-1') {
                   2588:            $r->print('<h3><font color=red>'.
                   2589:                      'Not a student in this course</font></h3>');
                   2590:         } else {
                   2591:            $r->print('<br><b>Section/Group:</b> '.&getcsec($asheet));
                   2592:         }
1.77      www      2593:         if ($ENV{'form.usymb'}) {
                   2594:            $r->print('<br><b>Assessment:</b> <tt>'.$ENV{'form.usymb'}.'</tt>');
                   2595:         }
1.30      www      2596:     }
                   2597: 
                   2598: # ---------------------------------------------------------------- Course title
                   2599: 
                   2600:     $r->print('<h1>'.
1.61      www      2601:             $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.
                   2602:              '</h1><h3>'.localtime().'</h3>');
1.30      www      2603: 
1.53      www      2604: # ---------------------------------------------------- See if user can see this
                   2605: 
                   2606:     if ((&gettype($asheet) eq 'classcalc') || 
                   2607:         (&getuname($asheet) ne $ENV{'user.name'}) ||
                   2608:         (&getudom($asheet) ne $ENV{'user.domain'})) {
                   2609:         unless (&Apache::lonnet::allowed('vgr',&getcid($asheet))) {
                   2610: 	    $r->print(
                   2611:            '<h1>Access Permission Denied</h1></form></body></html>');
                   2612:             return OK;
                   2613:         }
                   2614:     }
1.30      www      2615: 
1.53      www      2616: # ---------------------------------------------------------- Additional options
                   2617: 
                   2618:     $r->print(
                   2619:  '<input type=submit name=forcerecalc value="Completely Recalculate Sheet"><p>'
                   2620: 		 );
                   2621:     if (&gettype($asheet) eq 'assesscalc') {
                   2622:        $r->print ('<p><font size=+2><a href="/adm/studentcalc?uname='.
                   2623:                                                &getuname($asheet).
                   2624:                                                '&udom='.&getudom($asheet).
                   2625:                   '">Level up: Student Sheet</a></font><p>');
                   2626:     }
                   2627:     
                   2628:     if ((&gettype($asheet) eq 'studentcalc') && 
                   2629:         (&Apache::lonnet::allowed('vgr',&getcid($asheet)))) {
                   2630:        $r->print (
                   2631:                    '<p><font size=+2><a href="/adm/classcalc">'.
                   2632:                    'Level up: Course Sheet</a></font><p>');
                   2633:     }
                   2634:     
1.30      www      2635: 
                   2636: # ----------------------------------------------------------------- Save dialog
                   2637: 
                   2638: 
                   2639:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
                   2640:         my $fname=$ENV{'form.ufn'};
                   2641:         $fname=~s/\_[^\_]+$//;
                   2642:         if ($fname eq 'default') { $fname='course_default'; }
                   2643:         $r->print('<input type=submit name=saveas value="Save as ...">'.
                   2644:               '<input type=text size=20 name=newfn value="'.$fname.
                   2645:               '"> (make default: <input type=checkbox name="makedefufn">)<p>');
                   2646:     }
                   2647: 
                   2648:     $r->print(&hiddenfield('ufn',&getfilename($asheet)));
1.55      www      2649: 
                   2650: # ----------------------------------------------------------------- Load dialog
                   2651:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
                   2652: 	$r->print('<p><input type=submit name=load value="Load ...">'.
                   2653:                   '<select name="loadthissheet">'.
                   2654:                   '<option name="default">Default</option>');
1.78      matthew  2655:         foreach (&othersheets($asheet,&gettype($asheet))) {
1.55      www      2656: 	    $r->print('<option name="'.$_.'"');
                   2657:             if ($ENV{'form.ufn'} eq $_) {
                   2658:                $r->print(' selected');
                   2659:             }
                   2660:             $r->print('>'.$_.'</option>');
1.78      matthew  2661:         } 
1.55      www      2662:         $r->print('</select><p>');
                   2663:         if (&gettype($asheet) eq 'studentcalc') {
                   2664: 	    &setothersheets($asheet,&othersheets($asheet,'assesscalc'));
                   2665:         }
                   2666:     }
1.30      www      2667: 
1.46      www      2668: # --------------------------------------------------------------- Cached sheets
1.48      www      2669: 
                   2670:     &expirationdates();
1.46      www      2671: 
                   2672:     undef %oldsheets;
                   2673:     undef %loadedcaches;
1.44      www      2674: 
1.46      www      2675:     if (&gettype($asheet) eq 'classcalc') {
                   2676:         $r->print("Loading previously calculated student sheets ...<br>\n");
                   2677:         $r->rflush();
                   2678:         &cachedcsheets();
                   2679:     } elsif (&gettype($asheet) eq 'studentcalc') {
                   2680:         $r->print("Loading previously calculated assessment sheets ...<br>\n");
                   2681:         $r->rflush();
                   2682:         &cachedssheets(&getuname($asheet),&getudom($asheet),
                   2683:                        &getuhome($asheet));
                   2684:     }
1.30      www      2685: 
                   2686: # ----------------------------------------------------- Update sheet, load rows
1.14      www      2687: 
1.44      www      2688:     $r->print("Loaded sheet(s), updating rows ...<br>\n");
1.36      www      2689:     $r->rflush();
                   2690: 
1.29      www      2691:     &updatesheet($asheet);
1.36      www      2692: 
                   2693:     $r->print("Updated rows, loading row data ...<br>\n");
                   2694:     $r->rflush();
                   2695: 
1.37      www      2696:     &loadrows($asheet,$r);
1.14      www      2697: 
1.36      www      2698:     $r->print("Loaded row data, calculating sheet ...<br>\n");
                   2699:     $r->rflush();
1.14      www      2700: 
1.29      www      2701:     my $calcoutput=&calcsheet($asheet);
                   2702:     $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
1.56      www      2703: 
                   2704: # ---------------------------------------------------- See if something to save
                   2705: 
                   2706:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
                   2707:         my $fname='';
                   2708: 	if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
                   2709:             $fname=~s/\W/\_/g;
                   2710:             if ($fname eq 'default') { $fname='course_default'; }
                   2711:             $fname.='_'.&gettype($asheet);
                   2712:             &setfilename($asheet,$fname);
                   2713:             $ENV{'form.ufn'}=$fname;
                   2714: 	    $r->print('<p>Saving spreadsheet: '.
                   2715:                          &writesheet($asheet,$ENV{'form.makedefufn'}).'<p>');
                   2716: 	}
                   2717:     }
                   2718: 
                   2719: # ------------------------------------------------ Write the modified worksheet
                   2720: 
                   2721:    $r->print('<b>Current sheet:</b> '.&getfilename($asheet).'<p>');
                   2722: 
                   2723:    &tmpwrite($asheet);
1.61      www      2724: 
1.62      www      2725:     if (&gettype($asheet) eq 'studentcalc') {
                   2726: 	$r->print('<br>Show rows with empty A column: ');
                   2727:     } else {
                   2728:         $r->print('<br>Show empty rows: ');
                   2729:     } 
1.77      www      2730: 
                   2731:     $r->print(&hiddenfield('userselhidden','true').
                   2732:              '<input type=checkbox name=showall onClick="submit()"');
                   2733: 
                   2734:     if ($ENV{'form.showall'}) { 
                   2735:        $r->print(' checked'); 
                   2736:     } else {
                   2737: 	unless ($ENV{'form.userselhidden'}) {
                   2738:            unless 
                   2739: 	($ENV{'course.'.$ENV{'request.course.id'}.'.hideemptyrows'} eq 'yes') {
                   2740:           $r->print(' checked');
                   2741:           $ENV{'form.showall'}=1;
                   2742:            }
                   2743:        }
                   2744:     }
1.61      www      2745:     $r->print('>');
1.87      matthew  2746: 
1.69      www      2747:     if (&gettype($asheet) eq 'classcalc') {
                   2748:        $r->print(
                   2749:    ' Output CSV format: <input type=checkbox name=showcsv onClick="submit()"');
                   2750:        if ($ENV{'form.showcsv'}) { $r->print(' checked'); }
                   2751:        $r->print('>');
                   2752:     }
1.92      www      2753: 
                   2754: # ------------------------------------------------------------------ Insertrows
1.98      matthew  2755:     $r->print('&nbsp;Student Status: '.
                   2756:               &Apache::lonhtmlcommon::StatusOptions
                   2757:               ($ENV{'form.Status'},'sheet'));
1.92      www      2758: 
                   2759:    $r->print(<<ENDINSERTBUTTONS);
                   2760: <br>
                   2761: <input type='button' onClick='insertrow("top");' 
                   2762: value='Insert Row Top'>
                   2763: <input type='button' onClick='insertrow("bottom");' 
                   2764: value='Insert Row Bottom'><br>
                   2765: ENDINSERTBUTTONS
                   2766: 
1.56      www      2767: # ------------------------------------------------------------- Print out sheet
1.8       www      2768: 
1.29      www      2769:     &outsheet($r,$asheet);
1.10      www      2770:     $r->print('</form></body></html>');
1.29      www      2771: 
1.14      www      2772: # ------------------------------------------------------------------------ Done
1.7       www      2773:   } else {
                   2774: # ----------------------------- Not in a course, or not allowed to modify parms
                   2775:       $ENV{'user.error.msg'}=
                   2776:         $r->uri.":opa:0:0:Cannot modify spreadsheet";
                   2777:       return HTTP_NOT_ACCEPTABLE; 
                   2778:   }
1.3       www      2779:     return OK;
1.28      www      2780: 
1.1       www      2781: }
                   2782: 
                   2783: 1;
                   2784: __END__
1.77      www      2785: 
                   2786: 
                   2787: 
                   2788: 

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