File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.108: download - view: text, annotated - select for diffs
Mon Sep 9 17:18:33 2002 UTC (21 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Added $sheetdata goodness to &updateclasssheet and &updatestudentassesssheet.
Fixed a caching bug which caused caching to only happen on a sheet basis, not
a student basis.  Thus the instructor could only see one students assessment
sheets, regardless of which student she wanted to see.

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

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