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

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

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