File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.95: download - view: text, annotated - select for diffs
Fri Jul 5 01:31:25 2002 UTC (22 years ago) by www
Branches: MAIN
CVS tags: HEAD
Working on better debugging

    1: #
    2: # $Id: lonspreadsheet.pm,v 1.95 2002/07/05 01:31:25 www 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: 
   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: 
  116: # Stuff that only the screen handler can know
  117: 
  118: my $includedir;
  119: my $tmpdir;
  120: 
  121: # =============================================================================
  122: # ===================================== Implements an instance of a spreadsheet
  123: 
  124: sub initsheet {
  125:     my $safeeval = new Safe(shift);
  126:     my $safehole = new Safe::Hole;
  127:     $safeeval->permit("entereval");
  128:     $safeeval->permit(":base_math");
  129:     $safeeval->permit("sort");
  130:     $safeeval->deny(":base_io");
  131:     $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  132:     my $code=<<'ENDDEFS';
  133: # ---------------------------------------------------- Inside of the safe space
  134: 
  135: #
  136: # f: formulas
  137: # t: intermediate format (variable references expanded)
  138: # v: output values
  139: # c: preloaded constants (A-column)
  140: # rl: row label
  141: # os: other spreadsheets (for student spreadsheet only)
  142: 
  143: undef %v; 
  144: undef %t;
  145: undef %f;
  146: undef %c;
  147: undef %rl;
  148: undef @os;
  149: 
  150: $maxrow=0;
  151: $sheettype='';
  152: 
  153: # filename/reference of the sheet
  154: 
  155: $filename='';
  156: 
  157: # user data
  158: $uname='';
  159: $uhome='';
  160: $udom='';
  161: 
  162: # course data
  163: 
  164: $csec='';
  165: $chome='';
  166: $cnum='';
  167: $cdom='';
  168: $cid='';
  169: $cfn='';
  170: 
  171: # symb
  172: 
  173: $usymb='';
  174: 
  175: # error messages
  176: 
  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(%v);
  387: 	@Keys = $v{@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(%v);
  399: 	@Values =$v{@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 = $v{$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(%v);
  491: 	@Keys = $v{@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(%v);
  504: 	@Values =$v{@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(%v))}}+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(%v)) {
  542:         if (($v{$_}>=$low) && ($v{$_}<=$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(%v)) {
  563:         $sum+=$v{$_};
  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(%v)) {
  581:         $sum+=$v{$_};
  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(%v)) {
  604:         $sum+=$v{$_};
  605:         $num++;
  606:     }
  607:     unless ($num>1) { return undef; }
  608:     my $mean=$sum/$num;
  609:     $sum=0;
  610:     foreach (grep /$mask/,keys(%v)) {
  611:         $sum+=($v{$_}-$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(%v)) {
  629:         $prod*=$v{$_};
  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(%v)) {
  647:         unless ($max) { $max=$v{$_}; }
  648:         if (($v{$_}>$max) || ($max eq '-')) { $max=$v{$_}; }
  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(%v)) {
  666:         unless ($max) { $max=$v{$_}; }
  667:         if (($v{$_}<$min) || ($min eq '-')) { $min=$v{$_}; }
  668:     }
  669:     return $min;   
  670: }
  671: 
  672: #-------------------------------------------------------
  673: 
  674: =item SUMMAX(num,lower,upper)
  675: 
  676: compute the sum of the largest 'num' items in the range from
  677: 'lower' to 'upper'
  678: 
  679: =cut
  680: 
  681: #-------------------------------------------------------
  682: sub SUMMAX {
  683:     my ($num,$lower,$upper)=@_;
  684:     my $mask=mask($lower,$upper);
  685:     my @inside=();
  686:     foreach (grep /$mask/,keys(%v)) {
  687: 	push (@inside,$v{$_});
  688:     }
  689:     @inside=sort(@inside);
  690:     my $sum=0; my $i;
  691:     for ($i=$#inside;(($i>$#inside-$num) && ($i>=0));$i--) { 
  692:         $sum+=$inside[$i];
  693:     }
  694:     return $sum;   
  695: }
  696: 
  697: #-------------------------------------------------------
  698: 
  699: =item SUMMIN(num,lower,upper)
  700: 
  701: compute the sum of the smallest 'num' items in the range from
  702: 'lower' to 'upper'
  703: 
  704: =cut
  705: 
  706: #-------------------------------------------------------
  707: sub SUMMIN {
  708:     my ($num,$lower,$upper)=@_;
  709:     my $mask=mask($lower,$upper);
  710:     my @inside=();
  711:     foreach (grep /$mask/,keys(%v)) {
  712: 	$inside[$#inside+1]=$v{$_};
  713:     }
  714:     @inside=sort(@inside);
  715:     my $sum=0; my $i;
  716:     for ($i=0;(($i<$num) && ($i<=$#inside));$i++) { 
  717:         $sum+=$inside[$i];
  718:     }
  719:     return $sum;   
  720: }
  721: 
  722: sub expandnamed {
  723:     my $expression=shift;
  724:     if ($expression=~/^\&/) {
  725: 	my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/);
  726: 	my @vars=split(/\W+/,$formula);
  727:         my %values=();
  728:         undef %values;
  729: 	foreach ( @vars ) {
  730:             my $varname=$_;
  731:             if ($varname=~/\D/) {
  732:                $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
  733:                $varname=~s/$var/\(\\w\+\)/g;
  734: 	       foreach (keys(%c)) {
  735: 		  if ($_=~/$varname/) {
  736: 		      $values{$1}=1;
  737:                   }
  738:                }
  739: 	    }
  740:         }
  741:         if ($func eq 'EXPANDSUM') {
  742:             my $result='';
  743: 	    foreach (keys(%values)) {
  744:                 my $thissum=$formula;
  745:                 $thissum=~s/$var/$_/g;
  746:                 $result.=$thissum.'+';
  747:             } 
  748:             $result=~s/\+$//;
  749:             return $result;
  750:         } else {
  751: 	    return 0;
  752:         }
  753:     } else {
  754:         # it is not a function, so it is a parameter name
  755:         # We should do the following:
  756:         #    1. Take the list of parameter names
  757:         #    2. look through the list for ones that match the parameter we want
  758:         #    3. If there are no collisions, return the one that matches
  759:         #    4. If there is a collision, return 'bad parameter name error'
  760:         my $returnvalue = '';
  761:         my @matches = ();
  762:         $#matches = -1;
  763:         study $expression;
  764:         foreach $parameter (keys(%c)) {
  765:             push @matches,$parameter if ($parameter =~ /$expression/);
  766:         }
  767:         if ($#matches == 0) {
  768:             $returnvalue = '$c{\''.$matches[0].'\'}';
  769:         } else {
  770:             $returnvalue =  "'bad parameter name : $expression'";
  771:         }
  772:         return $returnvalue;
  773:     }
  774: }
  775: 
  776: sub sett {
  777:     %t=();
  778:     my $pattern='';
  779:     if ($sheettype eq 'assesscalc') {
  780: 	$pattern='A';
  781:     } else {
  782:         $pattern='[A-Z]';
  783:     }
  784:     foreach (keys(%f)) {
  785: 	if ($_=~/template\_(\w)/) {
  786: 	  my $col=$1;
  787:           unless ($col=~/^$pattern/) {
  788: 	    foreach (keys(%f)) {
  789: 	      if ($_=~/A(\d+)/) {
  790: 		my $trow=$1;
  791:                 if ($trow) {
  792:                     # Get the name of this cell
  793: 		    my $lb=$col.$trow;
  794:                     # Grab the template declaration
  795:                     $t{$lb}=$f{'template_'.$col};
  796:                     # Replace '#' with the row number
  797:                     $t{$lb}=~s/\#/$trow/g;
  798:                     # Replace '....' with ','
  799:                     $t{$lb}=~s/\.\.+/\,/g;
  800:                     # Replace 'A0' with the value from 'A0'
  801:                     $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
  802:                     # Replace parameters
  803:                     $t{$lb}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  804:                 }
  805: 	      }
  806: 	    }
  807: 	  }
  808:       }
  809:     }
  810:     foreach (keys(%f)) {
  811: 	if (($f{$_}) && ($_!~/template\_/)) {
  812:             my $matches=($_=~/^$pattern(\d+)/);
  813:             if  (($matches) && ($1)) {
  814: 	        unless ($f{$_}=~/^\!/) {
  815: 		    $t{$_}=$c{$_};
  816:                 }
  817:             } else {
  818: 	       $t{$_}=$f{$_};
  819:                $t{$_}=~s/\.\.+/\,/g;
  820:                $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
  821:                $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  822:             }
  823:         }
  824:     }
  825:     # For some reason 'A0' gets special treatment...  This seems superfluous
  826:     # but I imagine it is here for a reason.
  827:     $t{'A0'}=$f{'A0'};
  828:     $t{'A0'}=~s/\.\.+/\,/g;
  829:     $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
  830:     $t{'A0'}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  831: }
  832: 
  833: sub calc {
  834:     undef %v;
  835:     &sett();
  836:     my $notfinished=1;
  837:     my $depth=0;
  838:     my $errormsg;
  839:     while ($notfinished) {
  840: 	$notfinished=0;
  841:         foreach (keys(%t)) {
  842:             my $old=$v{$_};
  843:             $v{$_}=eval($t{$_});
  844: 	    if ($@) {
  845: 		$v{$_}='"error"';
  846:                 $errormsg.=$_.': '.$@."\n";
  847:             }
  848: 	    if ($v{$_} ne $old) { $notfinished=1; }
  849:         }
  850:         $depth++;
  851:         if ($depth>100) {
  852: 	    undef %v;
  853:             return 'Maximum calculation depth exceeded';
  854:         }
  855:     }
  856:     return $errormsg;
  857: }
  858: 
  859: sub templaterow {
  860:     my @cols=();
  861:     $cols[0]='<b><font size=+1>Template</font></b>';
  862:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  863: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  864: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
  865: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
  866:         my $fm=$f{'template_'.$_};
  867:         $fm=~s/[\'\"]/\&\#34;/g;
  868:         $cols[$#cols+1]="'template_$_','$fm'".'___eq___'.$fm;
  869:     }
  870:     return @cols;
  871: }
  872: 
  873: sub outrowassess {
  874:     my $n=shift;
  875:     my @cols=();
  876:     if ($n) {
  877:        my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{'A'.$n});
  878:       if ($rl{$usy}) {
  879:        $cols[0]=$rl{$usy}.'<br>'.
  880:                 '<select name="sel_'.$n.'" onChange="changesheet('.$n.
  881:                 ')"><option name="default">Default</option>';
  882:       } else { $cols[0]=''; }
  883:        foreach (@os) {
  884:            $cols[0].='<option name="'.$_.'"';
  885:             if ($ufn eq $_) {
  886:                $cols[0].=' selected';
  887:             }
  888:             $cols[0].='>'.$_.'</option>';
  889:        }
  890:        $cols[0].='</select>';
  891:     } else {
  892:        $cols[0]='<b><font size=+1>Export</font></b>';
  893:     }
  894:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  895: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  896: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
  897: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
  898:         my $fm=$f{$_.$n};
  899:         $fm=~s/[\'\"]/\&\#34;/g;
  900:         push(@cols,"'$_$n','$fm'".'___eq___'.$v{$_.$n});
  901:     }
  902:     return @cols;
  903: }
  904: 
  905: sub outrow {
  906:     my $n=shift;
  907:     my @cols=();
  908:     if ($n) {
  909:        $cols[0]=$rl{$f{'A'.$n}};
  910:     } else {
  911:        $cols[0]='<b><font size=+1>Export</font></b>';
  912:     }
  913:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  914: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  915: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
  916: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
  917:         my $fm=$f{$_.$n};
  918:         $fm=~s/[\'\"]/\&\#34;/g;
  919:         $cols[$#cols+1]="'$_$n','$fm'".'___eq___'.$v{$_.$n};
  920:     }
  921:     return @cols;
  922: }
  923: 
  924: sub exportrowa {
  925:     my @exportarray=();
  926:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  927: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
  928: 	$exportarray[$#exportarray+1]=$v{$_.'0'};
  929:     } 
  930:     return @exportarray;
  931: }
  932: 
  933: # ------------------------------------------- End of "Inside of the safe space"
  934: ENDDEFS
  935:     $safeeval->reval($code);
  936:     return $safeeval;
  937: }
  938: 
  939: # ------------------------------------------------ Add or change formula values
  940: 
  941: sub setformulas {
  942:     my ($safeeval,%f)=@_;
  943:     %{$safeeval->varglob('f')}=%f;
  944: }
  945: 
  946: # ------------------------------------------------ Add or change formula values
  947: 
  948: sub setconstants {
  949:     my ($safeeval,%c)=@_;
  950:     %{$safeeval->varglob('c')}=%c;
  951: }
  952: 
  953: # --------------------------------------------- Set names of other spreadsheets
  954: 
  955: sub setothersheets {
  956:     my ($safeeval,@os)=@_;
  957:     @{$safeeval->varglob('os')}=@os;
  958: }
  959: 
  960: # ------------------------------------------------ Add or change formula values
  961: 
  962: sub setrowlabels {
  963:     my ($safeeval,%rl)=@_;
  964:     %{$safeeval->varglob('rl')}=%rl;
  965: }
  966: 
  967: # ------------------------------------------------------- Calculate spreadsheet
  968: 
  969: sub calcsheet {
  970:     my $safeeval=shift;
  971:     return $safeeval->reval('&calc();');
  972: }
  973: 
  974: # ------------------------------------------------------------------ Get values
  975: 
  976: sub getvalues {
  977:     my $safeeval=shift;
  978:     return $safeeval->reval('%v');
  979: }
  980: 
  981: # ---------------------------------------------------------------- Get formulas
  982: 
  983: sub getformulas {
  984:     my $safeeval=shift;
  985:     return %{$safeeval->varglob('f')};
  986: }
  987: 
  988: # -------------------------------------------------------------------- Get type
  989: 
  990: sub gettype {
  991:     my $safeeval=shift;
  992:     return $safeeval->reval('$sheettype');
  993: }
  994: 
  995: # ------------------------------------------------------------------ Set maxrow
  996: 
  997: sub setmaxrow {
  998:     my ($safeeval,$row)=@_;
  999:     $safeeval->reval('$maxrow='.$row.';');
 1000: }
 1001: 
 1002: # ------------------------------------------------------------------ Get maxrow
 1003: 
 1004: sub getmaxrow {
 1005:     my $safeeval=shift;
 1006:     return $safeeval->reval('$maxrow');
 1007: }
 1008: 
 1009: # ---------------------------------------------------------------- Set filename
 1010: 
 1011: sub setfilename {
 1012:     my ($safeeval,$fn)=@_;
 1013:     $safeeval->reval('$filename="'.$fn.'";');
 1014: }
 1015: 
 1016: # ---------------------------------------------------------------- Get filename
 1017: 
 1018: sub getfilename {
 1019:     my $safeeval=shift;
 1020:     return $safeeval->reval('$filename');
 1021: }
 1022: 
 1023: # --------------------------------------------------------------- Get course ID
 1024: 
 1025: sub getcid {
 1026:     my $safeeval=shift;
 1027:     return $safeeval->reval('$cid');
 1028: }
 1029: 
 1030: # --------------------------------------------------------- Get course filename
 1031: 
 1032: sub getcfn {
 1033:     my $safeeval=shift;
 1034:     return $safeeval->reval('$cfn');
 1035: }
 1036: 
 1037: # ----------------------------------------------------------- Get course number
 1038: 
 1039: sub getcnum {
 1040:     my $safeeval=shift;
 1041:     return $safeeval->reval('$cnum');
 1042: }
 1043: 
 1044: # ------------------------------------------------------------- Get course home
 1045: 
 1046: sub getchome {
 1047:     my $safeeval=shift;
 1048:     return $safeeval->reval('$chome');
 1049: }
 1050: 
 1051: # ----------------------------------------------------------- Get course domain
 1052: 
 1053: sub getcdom {
 1054:     my $safeeval=shift;
 1055:     return $safeeval->reval('$cdom');
 1056: }
 1057: 
 1058: # ---------------------------------------------------------- Get course section
 1059: 
 1060: sub getcsec {
 1061:     my $safeeval=shift;
 1062:     return $safeeval->reval('$csec');
 1063: }
 1064: 
 1065: # --------------------------------------------------------------- Get user name
 1066: 
 1067: sub getuname {
 1068:     my $safeeval=shift;
 1069:     return $safeeval->reval('$uname');
 1070: }
 1071: 
 1072: # ------------------------------------------------------------- Get user domain
 1073: 
 1074: sub getudom {
 1075:     my $safeeval=shift;
 1076:     return $safeeval->reval('$udom');
 1077: }
 1078: 
 1079: # --------------------------------------------------------------- Get user home
 1080: 
 1081: sub getuhome {
 1082:     my $safeeval=shift;
 1083:     return $safeeval->reval('$uhome');
 1084: }
 1085: 
 1086: # -------------------------------------------------------------------- Get symb
 1087: 
 1088: sub getusymb {
 1089:     my $safeeval=shift;
 1090:     return $safeeval->reval('$usymb');
 1091: }
 1092: 
 1093: # ------------------------------------------------------------- Export of A-row
 1094: 
 1095: sub exportdata {
 1096:     my $safeeval=shift;
 1097:     return $safeeval->reval('&exportrowa()');
 1098: }
 1099: 
 1100: 
 1101: # ========================================================== End of Spreadsheet
 1102: # =============================================================================
 1103: 
 1104: #
 1105: # Procedures for screen output
 1106: #
 1107: # --------------------------------------------- Produce output row n from sheet
 1108: 
 1109: sub rown {
 1110:     my ($safeeval,$n)=@_;
 1111:     my $defaultbg;
 1112:     my $rowdata='';
 1113:     my $dataflag=0;
 1114:     unless ($n eq '-') {
 1115:        $defaultbg=((($n-1)/5)==int(($n-1)/5))?'#E0E0':'#FFFF';
 1116:     } else {
 1117:        $defaultbg='#E0FF';
 1118:     }
 1119:     unless ($ENV{'form.showcsv'}) {
 1120:        $rowdata.="\n<tr><td><b><font size=+1>$n</font></b></td>";
 1121:     } else {
 1122:        $rowdata.="\n".'"'.$n.'"';
 1123:     }
 1124:     my $showf=0;
 1125:     my $proc;
 1126:     my $maxred;
 1127:     my $sheettype=&gettype($safeeval);
 1128:     if ($sheettype eq 'studentcalc') {
 1129:         $proc='&outrowassess';
 1130:         $maxred=26;
 1131:     } else {
 1132:         $proc='&outrow';
 1133:     }
 1134:     if ($sheettype eq 'assesscalc') {
 1135:         $maxred=1;
 1136:     } else {
 1137:         $maxred=26;
 1138:     }
 1139:     if ($n eq '-') { $proc='&templaterow'; $n=-1; $dataflag=1; }
 1140:     foreach ($safeeval->reval($proc.'('.$n.')')) {
 1141:        my $bgcolor=$defaultbg.((($showf-1)/5==int(($showf-1)/5))?'99':'DD');
 1142:        my ($fm,$vl)=split(/\_\_\_eq\_\_\_/,$_);
 1143:        if ((($vl ne '') || ($vl eq '0')) &&
 1144:            (($showf==1) || ($sheettype ne 'studentcalc'))) { $dataflag=1; }
 1145:        if ($showf==0) { $vl=$_; }
 1146:       unless ($ENV{'form.showcsv'}) {
 1147:        if ($showf<=$maxred) { $bgcolor='#FFDDDD'; }
 1148:        if (($n==0) && ($showf<=26)) { $bgcolor='#CCCCFF'; } 
 1149:        if (($showf>$maxred) || ((!$n) && ($showf>0))) {
 1150: 	   if ($vl eq '') {
 1151: 	       $vl='<font size=+2 color='.$bgcolor.'>&#35;</font>';
 1152:            }
 1153:            $rowdata.=
 1154:        '<td bgcolor='.$bgcolor.'><a href="javascript:celledit('.$fm.');">'.$vl.
 1155: 	       '</a></td>';
 1156:        } else {
 1157:            $rowdata.='<td bgcolor='.$bgcolor.'>&nbsp;'.$vl.'&nbsp;</td>';
 1158:        }
 1159:       } else {
 1160: 	  $rowdata.=',"'.$vl.'"';
 1161:       }
 1162:        $showf++;
 1163:     }  # End of foreach($safeval...)
 1164:     if ($ENV{'form.showall'} || ($dataflag)) {
 1165:        return $rowdata.($ENV{'form.showcsv'}?'':'</tr>');
 1166:     } else {
 1167:        return '';
 1168:     }
 1169: }
 1170: 
 1171: # ------------------------------------------------------------- Print out sheet
 1172: 
 1173: sub outsheet {
 1174:     my ($r,$safeeval)=@_;
 1175:     my $maxred;
 1176:     my $realm;
 1177:     if (&gettype($safeeval) eq 'assesscalc') {
 1178:         $maxred=1;
 1179:         $realm='Assessment';
 1180:     } elsif (&gettype($safeeval) eq 'studentcalc') {
 1181:         $maxred=26;
 1182:         $realm='User';
 1183:     } else {
 1184:         $maxred=26;
 1185:         $realm='Course';
 1186:     }
 1187:     my $maxyellow=52-$maxred;
 1188:     my $tabledata;
 1189:     unless ($ENV{'form.showcsv'}) {
 1190:        $tabledata=
 1191:         '<table border=2><tr><th colspan=2 rowspan=2><font size=+2>'.
 1192:                   $realm.'</font></th>'.
 1193:                   '<td bgcolor=#FFDDDD colspan='.$maxred.
 1194:                   '><b><font size=+1>Import</font></b></td>'.
 1195:                   '<td colspan='.$maxyellow.
 1196: 		  '><b><font size=+1>Calculations</font></b></td></tr><tr>';
 1197:     my $showf=0;
 1198:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1199: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 1200: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1201: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1202:         $showf++;
 1203:         if ($showf<=$maxred) { 
 1204:            $tabledata.='<td bgcolor="#FFDDDD">'; 
 1205:         } else {
 1206:            $tabledata.='<td>';
 1207:         }
 1208:         $tabledata.="<b><font size=+1>$_</font></b></td>";
 1209:     }
 1210:     $tabledata.='</tr>'.&rown($safeeval,'-').&rown($safeeval,0);
 1211:    } else { $tabledata='<pre>'; }
 1212: 
 1213:     $r->print($tabledata);
 1214: 
 1215:     my $row;
 1216:     my $maxrow=&getmaxrow($safeeval);
 1217: 
 1218:     my @sortby=();
 1219:     my @sortidx=();
 1220:     for ($row=1;$row<=$maxrow;$row++) {
 1221:        $sortby[$row-1]=$safeeval->reval('$f{"A'.$row.'"}');
 1222:        $sortidx[$row-1]=$row-1;
 1223:     }
 1224:     @sortidx=sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
 1225: 
 1226:         my $what='Student';
 1227:         if (&gettype($safeeval) eq 'assesscalc') {
 1228: 	    $what='Item';
 1229: 	} elsif (&gettype($safeeval) eq 'studentcalc') {
 1230:             $what='Assessment';
 1231:         }
 1232: 
 1233:     my $n=0;
 1234:     for ($row=0;$row<$maxrow;$row++) {
 1235:      my $thisrow=&rown($safeeval,$sortidx[$row]+1);
 1236:      if ($thisrow) {
 1237:        if (($n/25==int($n/25)) && (!$ENV{'form.showcsv'})) {
 1238: 	$r->print("</table>\n<br>\n");
 1239:         $r->rflush();
 1240:         $r->print('<table border=2><tr><td>&nbsp;<td>'.$what.'</td>');
 1241:         foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1242: 		 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 1243: 		 'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1244: 		 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1245:            $r->print('<td>'.$_.'</td>');
 1246:         }
 1247:         $r->print('</tr>');
 1248:        }
 1249:        $n++;
 1250:        $r->print($thisrow);
 1251:       }
 1252:     }
 1253:     $r->print($ENV{'form.showcsv'}?'</pre>':'</table>');
 1254: }
 1255: 
 1256: #
 1257: # ----------------------------------------------- Read list of available sheets
 1258: # 
 1259: sub othersheets {
 1260:     my ($safeeval,$stype)=@_;
 1261:     #
 1262:     my $cnum=&getcnum($safeeval);
 1263:     my $cdom=&getcdom($safeeval);
 1264:     my $chome=&getchome($safeeval);
 1265:     #
 1266:     my @alternatives=();
 1267:     my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
 1268:     my ($tmp) = keys(%results);
 1269:     unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1270:         @alternatives = sort (keys(%results));
 1271:     }
 1272:     return @alternatives; 
 1273: }
 1274: 
 1275: 
 1276: #
 1277: # -------------------------------------- Parse a spreadsheet
 1278: # 
 1279: sub parse_sheet {
 1280:     # $sheetxml is a scalar reference or a scalar
 1281:     my ($sheetxml) = @_;
 1282:     if (! ref($sheetxml)) {
 1283:         my $tmp = $sheetxml;
 1284:         $sheetxml = \$tmp;
 1285:     }
 1286:     my %f;
 1287:     my $parser=HTML::TokeParser->new($sheetxml);
 1288:     my $token;
 1289:     while ($token=$parser->get_token) {
 1290:         if ($token->[0] eq 'S') {
 1291:             if ($token->[1] eq 'field') {
 1292:                 $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
 1293:                     $parser->get_text('/field');
 1294:             }
 1295:             if ($token->[1] eq 'template') {
 1296:                 $f{'template_'.$token->[2]->{'col'}}=
 1297:                     $parser->get_text('/template');
 1298:             }
 1299:         }
 1300:     }
 1301:     return \%f;
 1302: }
 1303: 
 1304: #
 1305: # -------------------------------------- Read spreadsheet formulas for a course
 1306: #
 1307: 
 1308: sub readsheet {
 1309:   my ($safeeval,$fn)=@_;
 1310:   my $stype=&gettype($safeeval);
 1311:   my $cnum=&getcnum($safeeval);
 1312:   my $cdom=&getcdom($safeeval);
 1313:   my $chome=&getchome($safeeval);
 1314: 
 1315:   if (! defined($fn)) {
 1316:       # There is no filename. Look for defaults in course and global, cache
 1317:       unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
 1318:           my %tmphash = &Apache::lonnet::get('environment',
 1319:                                              ['spreadsheet_default_'.$stype],
 1320:                                              $cdom,$cnum);
 1321:           my ($tmp) = keys(%tmphash);
 1322:           if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1323:               $fn = 'default_'.$stype;
 1324:           } else {
 1325:               $fn = $tmphash{'spreadsheet_default_'.$stype};
 1326:           } 
 1327:           unless (($fn) && ($fn!~/^error\:/)) {
 1328:  	     $fn='default_'.$stype;
 1329:           }
 1330:           $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn; 
 1331:       }
 1332:   }
 1333: 
 1334: # ---------------------------------------------------------- fn now has a value
 1335: 
 1336:   &setfilename($safeeval,$fn);
 1337: 
 1338: # ------------------------------------------------------ see if sheet is cached
 1339:   my $fstring='';
 1340:   if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
 1341:       &setformulas($safeeval,split(/\_\_\_\;\_\_\_/,$fstring));
 1342:   } else {
 1343: 
 1344: # ---------------------------------------------------- Not cached, need to read
 1345: 
 1346:      my %f=();
 1347: 
 1348:      if ($fn=~/^default\_/) {
 1349:          my $sheetxml='';
 1350:          my $fh;
 1351:          my $dfn=$fn;
 1352:          $dfn=~s/\_/\./g;
 1353:          if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
 1354:              $sheetxml=join('',<$fh>);
 1355:          } else {
 1356:              $sheetxml='<field row="0" col="A">"Error"</field>';
 1357:          }
 1358:          %f=%{&parse_sheet(\$sheetxml)};
 1359:      } elsif($fn=~/\/*\.spreadsheet$/) {
 1360:          my $sheetxml=&Apache::lonnet::getfile
 1361:              (&Apache::lonnet::filelocation('',$fn));
 1362:          if ($sheetxml == -1) {
 1363:              $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
 1364:                  .$fn.'"</field>';
 1365:          }
 1366:          %f=%{&parse_sheet(\$sheetxml)};
 1367:      } else {
 1368:          my $sheet='';
 1369:          my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
 1370:          my ($tmp) = keys(%tmphash);
 1371:          unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1372:              foreach (keys(%tmphash)) {
 1373:                  $f{$_}=$tmphash{$_};
 1374:              }
 1375:          }
 1376:      }
 1377: # --------------------------------------------------------------- Cache and set
 1378:        $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);  
 1379:        &setformulas($safeeval,%f);
 1380:     }
 1381: }
 1382: 
 1383: # -------------------------------------------------------- Make new spreadsheet
 1384: 
 1385: sub makenewsheet {
 1386:     my ($uname,$udom,$stype,$usymb)=@_;
 1387:     my $safeeval=initsheet($stype);
 1388:     $safeeval->reval(
 1389:        '$uname="'.$uname.
 1390:       '";$udom="'.$udom.
 1391:       '";$uhome="'.&Apache::lonnet::homeserver($uname,$udom).
 1392:       '";$sheettype="'.$stype.
 1393:       '";$usymb="'.$usymb.
 1394:       '";$csec="'.&Apache::lonnet::usection($udom,$uname,
 1395:                                             $ENV{'request.course.id'}).
 1396:       '";$cid="'.$ENV{'request.course.id'}.
 1397:       '";$cfn="'.$ENV{'request.course.fn'}.
 1398:       '";$cnum="'.$ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
 1399:       '";$cdom="'.$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
 1400:       '";$chome="'.$ENV{'course.'.$ENV{'request.course.id'}.'.home'}.'";');
 1401:     return $safeeval;
 1402: }
 1403: 
 1404: # ------------------------------------------------------------ Save spreadsheet
 1405: 
 1406: sub writesheet {
 1407:   my ($safeeval,$makedef)=@_;
 1408:   my $cid=&getcid($safeeval);
 1409:   if (&Apache::lonnet::allowed('opa',$cid)) {
 1410:     my %f=&getformulas($safeeval);
 1411:     my $stype=&gettype($safeeval);
 1412:     my $cnum=&getcnum($safeeval);
 1413:     my $cdom=&getcdom($safeeval);
 1414:     my $chome=&getchome($safeeval);
 1415:     my $fn=&getfilename($safeeval);
 1416: 
 1417: # ------------------------------------------------------------- Cache new sheet
 1418:     $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);    
 1419: # ----------------------------------------------------------------- Write sheet
 1420:     my $sheetdata='';
 1421:     foreach (keys(%f)) {
 1422:      unless ($f{$_} eq 'import') {
 1423:        $sheetdata.=&Apache::lonnet::escape($_).'='.
 1424: 	   &Apache::lonnet::escape($f{$_}).'&';
 1425:      }
 1426:     }
 1427:     $sheetdata=~s/\&$//;
 1428:     my $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.$fn.':'.
 1429:               $sheetdata,$chome);
 1430:     if ($reply eq 'ok') {
 1431:           $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.
 1432:               $stype.'_spreadsheets:'.
 1433:               &Apache::lonnet::escape($fn).'='.$ENV{'user.name'}.'@'.
 1434:                                                $ENV{'user.domain'},
 1435:               $chome);
 1436:           if ($reply eq 'ok') {
 1437:               if ($makedef) { 
 1438:                 return &Apache::lonnet::reply('put:'.$cdom.':'.$cnum.
 1439:                                 ':environment:spreadsheet_default_'.$stype.'='.
 1440:                                 &Apache::lonnet::escape($fn),
 1441:                                 $chome);
 1442: 	      } else {
 1443: 		  return $reply;
 1444:     	      }
 1445: 	   } else {
 1446: 	       return $reply;
 1447:            }
 1448:       } else {
 1449: 	  return $reply;
 1450:       }
 1451:   }
 1452:   return 'unauthorized';
 1453: }
 1454: 
 1455: # ----------------------------------------------- Make a temp copy of the sheet
 1456: # "Modified workcopy" - interactive only
 1457: #
 1458: 
 1459: sub tmpwrite {
 1460:     my $safeeval=shift;
 1461:     my $fn=$ENV{'user.name'}.'_'.
 1462:            $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
 1463:            &getfilename($safeeval);
 1464:     $fn=~s/\W/\_/g;
 1465:     $fn=$tmpdir.$fn.'.tmp';
 1466:     my $fh;
 1467:     if ($fh=Apache::File->new('>'.$fn)) {
 1468: 	print $fh join("\n",&getformulas($safeeval));
 1469:     }
 1470: }
 1471: 
 1472: # ---------------------------------------------------------- Read the temp copy
 1473: 
 1474: sub tmpread {
 1475:     my ($safeeval,$nfield,$nform)=@_;
 1476:     my $fn=$ENV{'user.name'}.'_'.
 1477:            $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
 1478:            &getfilename($safeeval);
 1479:     $fn=~s/\W/\_/g;
 1480:     $fn=$tmpdir.$fn.'.tmp';
 1481:     my $fh;
 1482:     my %fo=();
 1483:     my $countrows=0;
 1484:     if ($fh=Apache::File->new($fn)) {
 1485:         my $name;
 1486:         while ($name=<$fh>) {
 1487: 	    chomp($name);
 1488:             my $value=<$fh>;
 1489:             chomp($value);
 1490:             $fo{$name}=$value;
 1491:             if ($name=~/^A(\d+)$/) {
 1492: 		if ($1>$countrows) {
 1493: 		    $countrows=$1;
 1494:                 }
 1495:             }
 1496:         }
 1497:     }
 1498:     if ($nform eq 'changesheet') {
 1499:         $fo{'A'.$nfield}=(split(/\_\_\&\&\&\_\_/,$fo{'A'.$nfield}))[0];
 1500:         unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
 1501: 	    $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
 1502:         }
 1503:     } elsif ($nfield eq 'insertrow') {
 1504:         $countrows++;
 1505:         my $newrow=substr('000000'.$countrows,-7);
 1506:         if ($nform eq 'top') {
 1507: 	    $fo{'A'.$countrows}='--- '.$newrow;
 1508:         } else {
 1509:             $fo{'A'.$countrows}='~~~ '.$newrow;
 1510:         }
 1511:     } else {
 1512:        if ($nfield) { $fo{$nfield}=$nform; }
 1513:     }
 1514:     &setformulas($safeeval,%fo);
 1515: }
 1516: 
 1517: # ================================================================== Parameters
 1518: # -------------------------------------------- Figure out a cascading parameter
 1519: #
 1520: # For this function to work
 1521: #
 1522: # * parmhash needs to be tied
 1523: # * courseopt and useropt need to be initialized for this user and course
 1524: #
 1525: 
 1526: sub parmval {
 1527:     my ($what,$safeeval)=@_;
 1528:     my $cid=&getcid($safeeval);
 1529:     my $csec=&getcsec($safeeval);
 1530:     my $uname=&getuname($safeeval);
 1531:     my $udom=&getudom($safeeval);
 1532:     my $symb=&getusymb($safeeval);
 1533: 
 1534:     unless ($symb) { return ''; }
 1535:     my $result='';
 1536: 
 1537:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 1538: # ----------------------------------------------------- Cascading lookup scheme
 1539:        my $rwhat=$what;
 1540:        $what=~s/^parameter\_//;
 1541:        $what=~s/\_([^\_]+)$/\.$1/;
 1542: 
 1543:        my $symbparm=$symb.'.'.$what;
 1544:        my $mapparm=$mapname.'___(all).'.$what;
 1545:        my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
 1546: 
 1547:        my $seclevel=
 1548:             $usercourseprefix.'.['.
 1549: 		$csec.'].'.$what;
 1550:        my $seclevelr=
 1551:             $usercourseprefix.'.['.
 1552: 		$csec.'].'.$symbparm;
 1553:        my $seclevelm=
 1554:             $usercourseprefix.'.['.
 1555: 		$csec.'].'.$mapparm;
 1556: 
 1557:        my $courselevel=
 1558:             $usercourseprefix.'.'.$what;
 1559:        my $courselevelr=
 1560:             $usercourseprefix.'.'.$symbparm;
 1561:        my $courselevelm=
 1562:             $usercourseprefix.'.'.$mapparm;
 1563: 
 1564: # ---------------------------------------------------------- fourth, check user
 1565:       
 1566:       if ($uname) { 
 1567: 
 1568:        if ($useropt{$courselevelr}) { return $useropt{$courselevelr}; }
 1569: 
 1570:        if ($useropt{$courselevelm}) { return $useropt{$courselevelm}; }
 1571: 
 1572:        if ($useropt{$courselevel}) { return $useropt{$courselevel}; }
 1573: 
 1574:       }
 1575: 
 1576: # --------------------------------------------------------- third, check course
 1577:      
 1578:        if ($csec) {
 1579:  
 1580:         if ($courseopt{$seclevelr}) { return $courseopt{$seclevelr}; }
 1581: 
 1582:         if ($courseopt{$seclevelm}) { return $courseopt{$seclevelm}; }  
 1583: 
 1584:         if ($courseopt{$seclevel}) { return $courseopt{$seclevel}; }
 1585:   
 1586:       }
 1587: 
 1588:        if ($courseopt{$courselevelr}) { return $courseopt{$courselevelr}; }
 1589: 
 1590:        if ($courseopt{$courselevelm}) { return $courseopt{$courselevelm}; }
 1591: 
 1592:        if ($courseopt{$courselevel}) { return $courseopt{$courselevel}; }
 1593: 
 1594: # ----------------------------------------------------- second, check map parms
 1595: 
 1596:        my $thisparm=$parmhash{$symbparm};
 1597:        if ($thisparm) { return $thisparm; }
 1598: 
 1599: # -------------------------------------------------------- first, check default
 1600: 
 1601:        return &Apache::lonnet::metadata($fn,$rwhat.'.default');
 1602:         
 1603: }
 1604: 
 1605: # ---------------------------------------------- Update rows for course listing
 1606: 
 1607: sub updateclasssheet {
 1608:     my $safeeval=shift;
 1609:     my $cnum=&getcnum($safeeval);
 1610:     my $cdom=&getcdom($safeeval);
 1611:     my $cid=&getcid($safeeval);
 1612:     my $chome=&getchome($safeeval);
 1613: 
 1614: # ---------------------------------------------- Read class list and row labels
 1615: 
 1616:     my $classlst=&Apache::lonnet::reply
 1617:                                  ('dump:'.$cdom.':'.$cnum.':classlist',$chome);
 1618:     my %currentlist=();
 1619:     my $now=time;
 1620:     unless ($classlst=~/^error\:/) {
 1621:         foreach (split(/\&/,$classlst)) {
 1622:             my ($name,$value)=split(/\=/,$_);
 1623:             my ($end,$start)=split(/\:/,&Apache::lonnet::unescape($value));
 1624:             my $active=1;
 1625:             if (($end) && ($now>$end)) { $active=0; }
 1626:             if ($active) {
 1627:                 my $rowlabel='';
 1628:                 $name=&Apache::lonnet::unescape($name);
 1629:                 my ($sname,$sdom)=split(/\:/,$name);
 1630:                 my $ssec=&Apache::lonnet::usection($sdom,$sname,$cid);
 1631:                 if ($ssec==-1) {
 1632: 		   unless ($ENV{'form.showcsv'}) {
 1633:                     $rowlabel='<font color=red>Data not available: '.$name.
 1634: 			      '</font>';
 1635: 		   } else {
 1636: 		       $rowlabel='ERROR","'.$name.
 1637:                                  '","Data not available","","","';
 1638:                    }
 1639:                 } else {
 1640:                     my %reply=&Apache::lonnet::idrget($sdom,$sname);
 1641:                     my $reply=&Apache::lonnet::reply('get:'.$sdom.':'.$sname.
 1642: 		      ':environment:firstname&middlename&lastname&generation',
 1643:                       &Apache::lonnet::homeserver($sname,$sdom));
 1644: 		   unless ($ENV{'form.showcsv'}) {
 1645:                     $rowlabel='<a href="/adm/studentcalc?uname='.$sname.
 1646:                               '&udom='.$sdom.'">'.
 1647:                               $ssec.'&nbsp;'.$reply{$sname}.'<br>';
 1648:                     foreach ( split(/\&/,$reply)) {
 1649:                         $rowlabel.=&Apache::lonnet::unescape($_).' ';
 1650:                     }
 1651:                     $rowlabel.='</a>';
 1652: 		   } else {
 1653: 		    $rowlabel=$ssec.'","'.$reply{$sname}.'"';
 1654:                     my $ncount=0;
 1655:                     foreach (split(/\&/,$reply)) {
 1656:                         $rowlabel.=',"'.&Apache::lonnet::unescape($_).'"';
 1657:                         $ncount++;
 1658:                     }
 1659:                     unless ($ncount==4) { $rowlabel.=',""'; }
 1660:                     $rowlabel=~s/\"$//;
 1661: 		   }
 1662:                 }
 1663: 		$currentlist{&Apache::lonnet::unescape($name)}=$rowlabel;
 1664:             }
 1665:         } # end of foreach (split(/\&/,$classlst))
 1666: #
 1667: # -------------------- Find discrepancies between the course row table and this
 1668: #
 1669:         my %f=&getformulas($safeeval);
 1670:         my $changed=0;
 1671: 
 1672:         my $maxrow=0;
 1673:         my %existing=();
 1674: 
 1675: # ----------------------------------------------------------- Now obsolete rows
 1676: 	foreach (keys(%f)) {
 1677: 	    if ($_=~/^A(\d+)/) {
 1678:                 $maxrow=($1>$maxrow)?$1:$maxrow;
 1679:                 $existing{$f{$_}}=1;
 1680: 		unless ((defined($currentlist{$f{$_}})) || (!$1)) {
 1681: 		   $f{$_}='!!! Obsolete';
 1682:                    $changed=1;
 1683:                 }
 1684:             }
 1685:         }
 1686: 
 1687: # -------------------------------------------------------- New and unknown keys
 1688:      
 1689:         foreach (sort keys(%currentlist)) {
 1690:             unless ($existing{$_}) {
 1691: 		$changed=1;
 1692:                 $maxrow++;
 1693:                 $f{'A'.$maxrow}=$_;
 1694:             }
 1695:         }
 1696:      
 1697:         if ($changed) { &setformulas($safeeval,%f); }
 1698: 
 1699:         &setmaxrow($safeeval,$maxrow);
 1700:         &setrowlabels($safeeval,%currentlist);
 1701: 
 1702:     } else {
 1703:         return 'Could not access course data';
 1704:     }
 1705: }
 1706: 
 1707: # ----------------------------------- Update rows for student and assess sheets
 1708: 
 1709: sub updatestudentassesssheet {
 1710:     my $safeeval=shift;
 1711:     my %bighash;
 1712:     my $stype=&gettype($safeeval);
 1713:     my %current=();
 1714:     unless ($updatedata{$ENV{'request.course.fn'}.'_'.$stype}) {
 1715: # -------------------------------------------------------------------- Tie hash
 1716:       if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 1717:                        &GDBM_READER,0640)) {
 1718: # --------------------------------------------------------- Get all assessments
 1719: 
 1720: 	my %allkeys=('timestamp' => 
 1721:                      'Timestamp of Last Transaction<br>timestamp',
 1722:                      'subnumber' =>
 1723:                      'Number of Submissions<br>subnumber',
 1724:                      'tutornumber' =>
 1725:                      'Number of Tutor Responses<br>tutornumber',
 1726:                      'totalpoints' =>
 1727:                      'Total Points Granted<br>totalpoints');
 1728: 
 1729:         my $adduserstr='';
 1730:         if ((&getuname($safeeval) ne $ENV{'user.name'}) ||
 1731:             (&getudom($safeeval) ne $ENV{'user.domain'})) {
 1732:             $adduserstr='&uname='.&getuname($safeeval).
 1733: 		'&udom='.&getudom($safeeval);
 1734:         }
 1735: 
 1736:         my %allassess=('_feedback' =>
 1737: 	              '<a href="/adm/assesscalc?usymb=_feedback'.$adduserstr.
 1738:                        '">Feedback</a>',
 1739:                        '_evaluation' =>
 1740: 	              '<a href="/adm/assesscalc?usymb=_evaluation'.$adduserstr.
 1741:                        '">Evaluation</a>',
 1742:                        '_tutoring' =>
 1743: 	              '<a href="/adm/assesscalc?usymb=_tutoring'.$adduserstr.
 1744:                        '">Tutoring</a>',
 1745:                        '_discussion' =>
 1746: 	              '<a href="/adm/assesscalc?usymb=_discussion'.$adduserstr.
 1747:                        '">Discussion</a>'
 1748:         );
 1749: 
 1750:         foreach (keys(%bighash)) {
 1751: 	    if ($_=~/^src\_(\d+)\.(\d+)$/) {
 1752: 	       my $mapid=$1;
 1753:                my $resid=$2;
 1754:                my $id=$mapid.'.'.$resid;
 1755:                my $srcf=$bighash{$_};
 1756:                if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
 1757:                  my $symb=
 1758:                      &Apache::lonnet::declutter($bighash{'map_id_'.$mapid}).
 1759: 			    '___'.$resid.'___'.
 1760: 			    &Apache::lonnet::declutter($srcf);
 1761: 		 $allassess{$symb}=
 1762: 	            '<a href="/adm/assesscalc?usymb='.$symb.$adduserstr.'">'.
 1763:                      $bighash{'title_'.$id}.'</a>';
 1764:                  if ($stype eq 'assesscalc') {
 1765: 		     foreach (split(/\,/,
 1766: 				    &Apache::lonnet::metadata($srcf,'keys'))) {
 1767:                        if (($_=~/^stores\_(.*)/) || ($_=~/^parameter\_(.*)/)) {
 1768: 			  my $key=$_;
 1769:                           my $display=
 1770: 			      &Apache::lonnet::metadata($srcf,$key.'.display');
 1771:                           unless ($display) {
 1772:                               $display.=
 1773: 			         &Apache::lonnet::metadata($srcf,$key.'.name');
 1774:                           }
 1775:                           $display.='<br>'.$key;
 1776:                           $allkeys{$key}=$display;
 1777: 		       }
 1778:                    } # end of foreach
 1779: 	         }
 1780: 	      }
 1781: 	   }
 1782:         } # end of foreach (keys(%bighash))
 1783:         untie(%bighash);
 1784:     
 1785: #
 1786: # %allkeys has a list of storage and parameter displays by unikey
 1787: # %allassess has a list of all resource displays by symb
 1788: #
 1789: 
 1790:         if ($stype eq 'assesscalc') {
 1791: 	    %current=%allkeys;
 1792:         } elsif ($stype eq 'studentcalc') {
 1793:             %current=%allassess;
 1794:         }
 1795:         $updatedata{$ENV{'request.course.fn'}.'_'.$stype}=
 1796: 	    join('___;___',%current);
 1797:     } else {
 1798:         return 'Could not access course data';
 1799:     }
 1800: # ------------------------------------------------------ Get current from cache
 1801:     } else {
 1802:         %current=split(/\_\_\_\;\_\_\_/,
 1803: 		       $updatedata{$ENV{'request.course.fn'}.'_'.$stype});
 1804:     }
 1805: # -------------------- Find discrepancies between the course row table and this
 1806: #
 1807:         my %f=&getformulas($safeeval);
 1808:         my $changed=0;
 1809: 
 1810:         my $maxrow=0;
 1811:         my %existing=();
 1812: 
 1813: # ----------------------------------------------------------- Now obsolete rows
 1814: 	foreach (keys(%f)) {
 1815: 	    if ($_=~/^A(\d+)/) {
 1816:                 $maxrow=($1>$maxrow)?$1:$maxrow;
 1817:                 my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
 1818:                 $existing{$usy}=1;
 1819: 		unless ((defined($current{$usy})) || (!$1)) {
 1820: 		   $f{$_}='!!! Obsolete';
 1821:                    $changed=1;
 1822: 	        } elsif ($ufn) {
 1823: 		    $current{$usy}
 1824:                        =~s/assesscalc\?usymb\=/assesscalc\?ufn\=$ufn\&usymb\=/;
 1825:                 }
 1826:             }
 1827:         }
 1828: 
 1829: # -------------------------------------------------------- New and unknown keys
 1830:      
 1831:         foreach (keys(%current)) {
 1832:             unless ($existing{$_}) {
 1833: 		$changed=1;
 1834:                 $maxrow++;
 1835:                 $f{'A'.$maxrow}=$_;
 1836:             }
 1837:         }
 1838:     
 1839:         if ($changed) { &setformulas($safeeval,%f); }
 1840: 
 1841:         &setmaxrow($safeeval,$maxrow);
 1842:         &setrowlabels($safeeval,%current);
 1843:  
 1844:         undef %current;
 1845:         undef %existing;
 1846: }
 1847: 
 1848: # ------------------------------------------------ Load data for one assessment
 1849: 
 1850: sub loadstudent {
 1851:     my $safeeval=shift;
 1852:     my %c=();
 1853:     my %f=&getformulas($safeeval);
 1854:     $cachedassess=&getuname($safeeval).':'.&getudom($safeeval);
 1855:     %cachedstores=();
 1856:     {
 1857:       my $reply=&Apache::lonnet::reply('dump:'.&getudom($safeeval).':'.
 1858:                                                &getuname($safeeval).':'.
 1859:                                                &getcid($safeeval),
 1860:                                                &getuhome($safeeval));
 1861:       unless ($reply=~/^error\:/) {
 1862: 	 foreach ( split(/\&/,$reply)) {
 1863:             my ($name,$value)=split(/\=/,$_);
 1864:             $cachedstores{&Apache::lonnet::unescape($name)}=
 1865: 	                  &Apache::lonnet::unescape($value);
 1866: 	}
 1867:       }
 1868:     }
 1869:     my @assessdata=();
 1870:     foreach (keys(%f)) {
 1871: 	if ($_=~/^A(\d+)/) {
 1872: 	   my $row=$1;
 1873:            unless (($f{$_}=~/^\!/) || ($row==0)) {
 1874: 	      my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
 1875: 	      @assessdata=&exportsheet(&getuname($safeeval),
 1876:                                        &getudom($safeeval),
 1877:                                        'assesscalc',$usy,$ufn);
 1878:               my $index=0;
 1879:               foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1880: 	               'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 1881:                   if ($assessdata[$index]) {
 1882: 		     my $col=$_;
 1883: 		     if ($assessdata[$index]=~/\D/) {
 1884:                          $c{$col.$row}="'".$assessdata[$index]."'";
 1885:  		     } else {
 1886: 		         $c{$col.$row}=$assessdata[$index];
 1887: 		     }
 1888:                      unless ($col eq 'A') { 
 1889: 			 $f{$col.$row}='import';
 1890:                      }
 1891: 		  }
 1892:                   $index++;
 1893:               }
 1894: 	   }
 1895:         }
 1896:     }
 1897:     $cachedassess='';
 1898:     undef %cachedstores;
 1899:     &setformulas($safeeval,%f);
 1900:     &setconstants($safeeval,%c);
 1901: }
 1902: 
 1903: # --------------------------------------------------- Load data for one student
 1904: 
 1905: sub loadcourse {
 1906:     my ($safeeval,$r)=@_;
 1907:     my %c=();
 1908:     my %f=&getformulas($safeeval);
 1909:     my $total=0;
 1910:     foreach (keys(%f)) {
 1911: 	if ($_=~/^A(\d+)/) {
 1912: 	    unless ($f{$_}=~/^\!/) { $total++; }
 1913:         }
 1914:     }
 1915:     my $now=0;
 1916:     my $since=time;
 1917:     $r->print(<<ENDPOP);
 1918: <script>
 1919:     popwin=open('','popwin','width=400,height=100');
 1920:     popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
 1921:       '<h3>Spreadsheet Calculation Progress</h3>'+
 1922:       '<form name=popremain>'+
 1923:       '<input type=text size=35 name=remaining value=Starting></form>'+
 1924:       '</body></html>');
 1925:     popwin.document.close();
 1926: </script>
 1927: ENDPOP
 1928:     $r->rflush();
 1929:     foreach (keys(%f)) {
 1930: 	if ($_=~/^A(\d+)/) {
 1931: 	   my $row=$1;
 1932:            unless (($f{$_}=~/^\!/)  || ($row==0)) {
 1933: 	      my @studentdata=&exportsheet(split(/\:/,$f{$_}),
 1934:                                            'studentcalc');
 1935:               undef %userrdatas;
 1936:               $now++;
 1937:               $r->print('<script>popwin.document.popremain.remaining.value="'.
 1938:                   $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
 1939:                         ' secs remaining";</script>');
 1940:               $r->rflush(); 
 1941: 
 1942:               my $index=0;
 1943:              foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1944: 	              'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 1945:                   if ($studentdata[$index]) {
 1946: 		     my $col=$_;
 1947: 		     if ($studentdata[$index]=~/\D/) {
 1948:                          $c{$col.$row}="'".$studentdata[$index]."'";
 1949:  		     } else {
 1950: 		         $c{$col.$row}=$studentdata[$index];
 1951: 		     }
 1952:                      unless ($col eq 'A') { 
 1953: 			 $f{$col.$row}='import';
 1954:                      }
 1955: 		  }
 1956:                   $index++;
 1957:               }
 1958: 	   }
 1959:         }
 1960:     }
 1961:     &setformulas($safeeval,%f);
 1962:     &setconstants($safeeval,%c);
 1963:     $r->print('<script>popwin.close()</script>');
 1964:     $r->rflush(); 
 1965: }
 1966: 
 1967: # ------------------------------------------------ Load data for one assessment
 1968: 
 1969: sub loadassessment {
 1970:     my $safeeval=shift;
 1971: 
 1972:     my $uhome=&getuhome($safeeval);
 1973:     my $uname=&getuname($safeeval);
 1974:     my $udom=&getudom($safeeval);
 1975:     my $symb=&getusymb($safeeval);
 1976:     my $cid=&getcid($safeeval);
 1977:     my $cnum=&getcnum($safeeval);
 1978:     my $cdom=&getcdom($safeeval);
 1979:     my $chome=&getchome($safeeval);
 1980: 
 1981:     my $namespace;
 1982:     unless ($namespace=$cid) { return ''; }
 1983: 
 1984: # ----------------------------------------------------------- Get stored values
 1985: 
 1986:    my %returnhash=();
 1987: 
 1988:    if ($cachedassess eq $uname.':'.$udom) {
 1989: #
 1990: # get data out of the dumped stores
 1991: # 
 1992: 
 1993:        my $version=$cachedstores{'version:'.$symb};
 1994:        my $scope;
 1995:        for ($scope=1;$scope<=$version;$scope++) {
 1996:            foreach (split(/\:/,$cachedstores{$scope.':keys:'.$symb})) {
 1997:                $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
 1998:            } 
 1999:        }
 2000: 
 2001:    } else {
 2002: #
 2003: # restore individual
 2004: #
 2005: 
 2006:     my $answer=&Apache::lonnet::reply(
 2007:        "restore:$udom:$uname:".
 2008:        &Apache::lonnet::escape($namespace).":".
 2009:        &Apache::lonnet::escape($symb),$uhome);
 2010:     foreach (split(/\&/,$answer)) {
 2011: 	my ($name,$value)=split(/\=/,$_);
 2012:         $returnhash{&Apache::lonnet::unescape($name)}=
 2013:                     &Apache::lonnet::unescape($value);
 2014:     }
 2015:     my $version;
 2016:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2017:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2018:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2019:        } 
 2020:     }
 2021:    }
 2022: # ----------------------------- returnhash now has all stores for this resource
 2023: 
 2024: # --------- convert all "_" to "." to be able to use libraries, multiparts, etc
 2025: 
 2026:     my @oldkeys=keys %returnhash;
 2027: 
 2028:     foreach (@oldkeys) {
 2029:         my $name=$_;
 2030:         my $value=$returnhash{$_};
 2031:         delete $returnhash{$_};
 2032:         $name=~s/\_/\./g;
 2033:         $returnhash{$name}=$value;
 2034:     }
 2035: 
 2036: # ---------------------------- initialize coursedata and userdata for this user
 2037:     undef %courseopt;
 2038:     undef %useropt;
 2039: 
 2040:     my $userprefix=$uname.'_'.$udom.'_';
 2041: 
 2042:     unless ($uhome eq 'no_host') { 
 2043: # -------------------------------------------------------------- Get coursedata
 2044:       unless
 2045:         ((time-$courserdatas{$cid.'.last_cache'})<240) {
 2046:          my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
 2047:               ':resourcedata',$chome);
 2048:          if ($reply!~/^error\:/) {
 2049:             $courserdatas{$cid}=$reply;
 2050:             $courserdatas{$cid.'.last_cache'}=time;
 2051:          }
 2052:       }
 2053:       foreach (split(/\&/,$courserdatas{$cid})) {
 2054:          my ($name,$value)=split(/\=/,$_);
 2055:          $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
 2056:                     &Apache::lonnet::unescape($value);  
 2057:       }
 2058: # --------------------------------------------------- Get userdata (if present)
 2059:       unless
 2060:         ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
 2061:          my $reply=
 2062:        &Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
 2063:          if ($reply!~/^error\:/) {
 2064: 	     $userrdatas{$uname.'___'.$udom}=$reply;
 2065: 	     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
 2066:          }
 2067:       }
 2068:       foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
 2069:          my ($name,$value)=split(/\=/,$_);
 2070:          $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
 2071: 	          &Apache::lonnet::unescape($value);
 2072:       }
 2073:     }
 2074: # ----------------- now courseopt, useropt initialized for this user and course
 2075: # (used by parmval)
 2076: 
 2077: #
 2078: # Load keys for this assessment only
 2079: #
 2080:     my %thisassess=();
 2081:     my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
 2082:     
 2083:     foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
 2084:         $thisassess{$_}=1;
 2085:     } 
 2086: #
 2087: # Load parameters
 2088: #
 2089:    my %c=();
 2090: 
 2091:    if (tie(%parmhash,'GDBM_File',
 2092:            &getcfn($safeeval).'_parms.db',&GDBM_READER,0640)) {
 2093:     my %f=&getformulas($safeeval);
 2094:     foreach (keys(%f))  {
 2095: 	if ($_=~/^A/) {
 2096:             unless ($f{$_}=~/^\!/) {
 2097:   	       if ($f{$_}=~/^parameter/) {
 2098: 		if ($thisassess{$f{$_}}) {
 2099:                   my $val=&parmval($f{$_},$safeeval);
 2100:                   $c{$_}=$val;
 2101:                   $c{$f{$_}}=$val;
 2102: 	        }
 2103: 	       } else {
 2104: 		  my $key=$f{$_};
 2105:                   my $ckey=$key;
 2106:                   $key=~s/^stores\_/resource\./;
 2107:                   $key=~s/\_/\./g;
 2108:  	          $c{$_}=$returnhash{$key};
 2109:                   $c{$ckey}=$returnhash{$key};
 2110: 	       }
 2111: 	   }
 2112:         }
 2113:     }
 2114:     untie(%parmhash);
 2115:    }
 2116:    &setconstants($safeeval,%c);
 2117: }
 2118: 
 2119: # --------------------------------------------------------- Various form fields
 2120: 
 2121: sub textfield {
 2122:     my ($title,$name,$value)=@_;
 2123:     return "\n<p><b>$title:</b><br>".
 2124:            '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
 2125: }
 2126: 
 2127: sub hiddenfield {
 2128:     my ($name,$value)=@_;
 2129:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
 2130: }
 2131: 
 2132: sub selectbox {
 2133:     my ($title,$name,$value,%options)=@_;
 2134:     my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
 2135:     foreach (sort keys(%options)) {
 2136:         $selout.='<option value="'.$_.'"';
 2137:         if ($_ eq $value) { $selout.=' selected'; }
 2138:         $selout.='>'.$options{$_}.'</option>';
 2139:     }
 2140:     return $selout.'</select>';
 2141: }
 2142: 
 2143: # =============================================== Update information in a sheet
 2144: #
 2145: # Add new users or assessments, etc.
 2146: #
 2147: 
 2148: sub updatesheet {
 2149:     my $safeeval=shift;
 2150:     my $stype=&gettype($safeeval);
 2151:     if ($stype eq 'classcalc') {
 2152: 	return &updateclasssheet($safeeval);
 2153:     } else {
 2154:         return &updatestudentassesssheet($safeeval);
 2155:     }
 2156: }
 2157: 
 2158: # =================================================== Load the rows for a sheet
 2159: #
 2160: # Import the data for rows
 2161: #
 2162: 
 2163: sub loadrows {
 2164:     my ($safeeval,$r)=@_;
 2165:     my $stype=&gettype($safeeval);
 2166:     if ($stype eq 'classcalc') {
 2167: 	&loadcourse($safeeval,$r);
 2168:     } elsif ($stype eq 'studentcalc') {
 2169:         &loadstudent($safeeval);
 2170:     } else {
 2171:         &loadassessment($safeeval);
 2172:     }
 2173: }
 2174: 
 2175: # ======================================================= Forced recalculation?
 2176: 
 2177: sub checkthis {
 2178:     my ($keyname,$time)=@_;
 2179:     return ($time<$expiredates{$keyname});
 2180: }
 2181: sub forcedrecalc {
 2182:     my ($uname,$udom,$stype,$usymb)=@_;
 2183:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2184:     my $time=$oldsheets{$key.'.time'};
 2185:     if ($ENV{'form.forcerecalc'}) { return 1; }
 2186:     unless ($time) { return 1; }
 2187:     if ($stype eq 'assesscalc') {
 2188:         my $map=(split(/\_\_\_/,$usymb))[0];
 2189:         if (&checkthis('::assesscalc:',$time) ||
 2190:             &checkthis('::assesscalc:'.$map,$time) ||
 2191:             &checkthis('::assesscalc:'.$usymb,$time) ||
 2192:             &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
 2193:             &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
 2194:             &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
 2195:             return 1;
 2196:         } 
 2197:     } else {
 2198:         if (&checkthis('::studentcalc:',$time) || 
 2199:             &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
 2200: 	    return 1;
 2201:         }
 2202:     }
 2203:     return 0; 
 2204: }
 2205: 
 2206: # ============================================================== Export handler
 2207: #
 2208: # Non-interactive call from with program
 2209: #
 2210: 
 2211: sub exportsheet {
 2212:  my ($uname,$udom,$stype,$usymb,$fn)=@_;
 2213:  my @exportarr=();
 2214: 
 2215:  if (($usymb=~/^\_(\w+)/) && (!$fn)) {
 2216:     $fn='default_'.$1;
 2217:  }
 2218: 
 2219: #
 2220: # Check if cached
 2221: #
 2222: 
 2223:  my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2224:  my $found='';
 2225: 
 2226:  if ($oldsheets{$key}) {
 2227:      foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
 2228:          my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 2229:          if ($name eq $fn) {
 2230: 	     $found=$value;
 2231:          }
 2232:      }
 2233:  }
 2234: 
 2235:  unless ($found) {
 2236:      &cachedssheets($uname,$udom,&Apache::lonnet::homeserver($uname,$udom));
 2237:      if ($oldsheets{$key}) {
 2238: 	foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
 2239:             my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 2240:             if ($name eq $fn) {
 2241: 	        $found=$value;
 2242:             }
 2243:         } 
 2244:      }
 2245:  }
 2246: #
 2247: # Check if still valid
 2248: #
 2249:  if ($found) {
 2250:      if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
 2251: 	 $found='';
 2252:      }
 2253:  }
 2254:  
 2255:  if ($found) {
 2256: #
 2257: # Return what was cached
 2258: #
 2259:      @exportarr=split(/\_\_\_\;\_\_\_/,$found);
 2260: 
 2261:  } else {
 2262: #
 2263: # Not cached
 2264: #        
 2265: 
 2266:     my $thissheet=&makenewsheet($uname,$udom,$stype,$usymb);
 2267:     &readsheet($thissheet,$fn);
 2268:     &updatesheet($thissheet);
 2269:     &loadrows($thissheet);
 2270:     &calcsheet($thissheet); 
 2271:     @exportarr=&exportdata($thissheet);
 2272: #
 2273: # Store now
 2274: #
 2275:     my $cid=$ENV{'request.course.id'}; 
 2276:     my $current='';
 2277:     if ($stype eq 'studentcalc') {
 2278:        $current=&Apache::lonnet::reply('get:'.
 2279:                                      $ENV{'course.'.$cid.'.domain'}.':'.
 2280:                                      $ENV{'course.'.$cid.'.num'}.
 2281: 				     ':nohist_calculatedsheets:'.
 2282:                                      &Apache::lonnet::escape($key),
 2283:                                      $ENV{'course.'.$cid.'.home'});
 2284:     } else {
 2285:        $current=&Apache::lonnet::reply('get:'.
 2286:                                      &getudom($thissheet).':'.
 2287:                                      &getuname($thissheet).
 2288: 				     ':nohist_calculatedsheets_'.
 2289:                                      $ENV{'request.course.id'}.':'.
 2290:                                      &Apache::lonnet::escape($key),
 2291:                                      &getuhome($thissheet));
 2292: 
 2293:     }
 2294:     my %currentlystored=();
 2295:     unless ($current=~/^error\:/) {
 2296:        foreach (split(/\_\_\_\&\_\_\_/,&Apache::lonnet::unescape($current))) {
 2297:            my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 2298:            $currentlystored{$name}=$value;
 2299:        }
 2300:     }
 2301:     $currentlystored{$fn}=join('___;___',@exportarr);
 2302: 
 2303:     my $newstore='';
 2304:     foreach (keys(%currentlystored)) {
 2305:         if ($newstore) { $newstore.='___&___'; }
 2306:         $newstore.=$_.'___=___'.$currentlystored{$_};
 2307:     }
 2308:     my $now=time;
 2309:     if ($stype eq 'studentcalc') {
 2310:        &Apache::lonnet::reply('put:'.
 2311:                          $ENV{'course.'.$cid.'.domain'}.':'.
 2312:                          $ENV{'course.'.$cid.'.num'}.
 2313: 			 ':nohist_calculatedsheets:'.
 2314:                          &Apache::lonnet::escape($key).'='.
 2315: 			 &Apache::lonnet::escape($newstore).'&'.
 2316:                          &Apache::lonnet::escape($key).'.time='.$now,
 2317:                          $ENV{'course.'.$cid.'.home'});
 2318:    } else {
 2319:        &Apache::lonnet::reply('put:'.
 2320:                          &getudom($thissheet).':'.
 2321:                          &getuname($thissheet).
 2322: 			 ':nohist_calculatedsheets_'.
 2323:                          $ENV{'request.course.id'}.':'.
 2324:                          &Apache::lonnet::escape($key).'='.
 2325: 			 &Apache::lonnet::escape($newstore).'&'.
 2326:                          &Apache::lonnet::escape($key).'.time='.$now,
 2327:                          &getuhome($thissheet));
 2328:    }
 2329:  }
 2330:  return @exportarr;
 2331: }
 2332: # ============================================================ Expiration Dates
 2333: #
 2334: # Load previously cached student spreadsheets for this course
 2335: #
 2336: 
 2337: sub expirationdates {
 2338:     undef %expiredates;
 2339:     my $cid=$ENV{'request.course.id'};
 2340:     my $reply=&Apache::lonnet::reply('dump:'.
 2341: 				     $ENV{'course.'.$cid.'.domain'}.':'.
 2342:                                      $ENV{'course.'.$cid.'.num'}.
 2343: 				     ':nohist_expirationdates',
 2344:                                      $ENV{'course.'.$cid.'.home'});
 2345:     unless ($reply=~/^error\:/) {
 2346: 	foreach (split(/\&/,$reply)) {
 2347:             my ($name,$value)=split(/\=/,$_);
 2348:             $expiredates{&Apache::lonnet::unescape($name)}
 2349:                         =&Apache::lonnet::unescape($value);
 2350:         }
 2351:     }
 2352: }
 2353: 
 2354: # ===================================================== Calculated sheets cache
 2355: #
 2356: # Load previously cached student spreadsheets for this course
 2357: #
 2358: 
 2359: sub cachedcsheets {
 2360:     my $cid=$ENV{'request.course.id'};
 2361:     my $reply=&Apache::lonnet::reply('dump:'.
 2362: 				     $ENV{'course.'.$cid.'.domain'}.':'.
 2363:                                      $ENV{'course.'.$cid.'.num'}.
 2364: 				     ':nohist_calculatedsheets',
 2365:                                      $ENV{'course.'.$cid.'.home'});
 2366:     unless ($reply=~/^error\:/) {
 2367: 	foreach ( split(/\&/,$reply)) {
 2368:             my ($name,$value)=split(/\=/,$_);
 2369:             $oldsheets{&Apache::lonnet::unescape($name)}
 2370:                       =&Apache::lonnet::unescape($value);
 2371:         }
 2372:     }
 2373: }
 2374: 
 2375: # ===================================================== Calculated sheets cache
 2376: #
 2377: # Load previously cached assessment spreadsheets for this student
 2378: #
 2379: 
 2380: sub cachedssheets {
 2381:   my ($sname,$sdom,$shome)=@_;
 2382:   unless (($loadedcaches{$sname.'_'.$sdom}) || ($shome eq 'no_host')) {
 2383:     my $cid=$ENV{'request.course.id'};
 2384:     my $reply=&Apache::lonnet::reply('dump:'.$sdom.':'.$sname.
 2385: 			             ':nohist_calculatedsheets_'.
 2386:                                       $ENV{'request.course.id'},
 2387:                                      $shome);
 2388:     unless ($reply=~/^error\:/) {
 2389: 	foreach ( split(/\&/,$reply)) {
 2390:             my ($name,$value)=split(/\=/,$_);
 2391:             $oldsheets{&Apache::lonnet::unescape($name)}
 2392:                       =&Apache::lonnet::unescape($value);
 2393:         }
 2394:     }
 2395:     $loadedcaches{$sname.'_'.$sdom}=1;
 2396:   }
 2397: }
 2398: 
 2399: # ===================================================== Calculated sheets cache
 2400: #
 2401: # Load previously cached assessment spreadsheets for this student
 2402: #
 2403: 
 2404: # ================================================================ Main handler
 2405: #
 2406: # Interactive call to screen
 2407: #
 2408: #
 2409: 
 2410: 
 2411: sub handler {
 2412:     my $r=shift;
 2413: 
 2414:     if ($r->header_only) {
 2415:       $r->content_type('text/html');
 2416:       $r->send_http_header;
 2417:       return OK;
 2418:     }
 2419: 
 2420: # ---------------------------------------------------- Global directory configs
 2421: 
 2422: $includedir=$r->dir_config('lonIncludes');
 2423: $tmpdir=$r->dir_config('lonDaemons').'/tmp/';
 2424: 
 2425: # ----------------------------------------------------- Needs to be in a course
 2426: 
 2427:   if ($ENV{'request.course.fn'}) { 
 2428: 
 2429: # --------------------------- Get query string for limited number of parameters
 2430: 
 2431:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2432:                                             ['uname','udom','usymb','ufn']);
 2433: 
 2434:     if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'})) {
 2435: 	$ENV{'form.ufn'}='default_'.$1;
 2436:     }
 2437: 
 2438: # -------------------------------------- Interactive loading of specific sheet?
 2439:     if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
 2440: 	$ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
 2441:     }
 2442: # ------------------------------------------- Nothing there? Must be login user
 2443: 
 2444:     my $aname;
 2445:     my $adom;
 2446: 
 2447:     unless ($ENV{'form.uname'}) {
 2448: 	$aname=$ENV{'user.name'};
 2449:         $adom=$ENV{'user.domain'};
 2450:     } else {
 2451:         $aname=$ENV{'form.uname'};
 2452:         $adom=$ENV{'form.udom'};
 2453:     }
 2454: 
 2455: # ------------------------------------------------------------------- Open page
 2456: 
 2457:     $r->content_type('text/html');
 2458:     $r->header_out('Cache-control','no-cache');
 2459:     $r->header_out('Pragma','no-cache');
 2460:     $r->send_http_header;
 2461: 
 2462: # --------------------------------------------------------------- Screen output
 2463: 
 2464:     $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
 2465:     $r->print(<<ENDSCRIPT);
 2466: <script language="JavaScript">
 2467: 
 2468:     function celledit(cn,cf) {
 2469:         var cnf=prompt(cn,cf);
 2470:         if (cnf!=null) {
 2471:             document.sheet.unewfield.value=cn;
 2472:             document.sheet.unewformula.value=cnf;
 2473:             document.sheet.submit();
 2474:         }
 2475:     }
 2476: 
 2477:     function changesheet(cn) {
 2478: 	document.sheet.unewfield.value=cn;
 2479:         document.sheet.unewformula.value='changesheet';
 2480:         document.sheet.submit();
 2481:     }
 2482: 
 2483:     function insertrow(cn) {
 2484: 	document.sheet.unewfield.value='insertrow';
 2485:         document.sheet.unewformula.value=cn;
 2486:         document.sheet.submit();
 2487:     }
 2488: 
 2489: </script>
 2490: ENDSCRIPT
 2491:     $r->print('</head><body bgcolor="#FFFFFF">'.
 2492:        '<img align=right src=/adm/lonIcons/lonlogos.gif>'.
 2493:        '<h1>LON-CAPA Spreadsheet</h1>'.
 2494:        '<form action="'.$r->uri.'" name=sheet method=post>'.
 2495:        &hiddenfield('uname',$ENV{'form.uname'}).
 2496:        &hiddenfield('udom',$ENV{'form.udom'}).
 2497:        &hiddenfield('usymb',$ENV{'form.usymb'}).
 2498:        &hiddenfield('unewfield','').
 2499:        &hiddenfield('unewformula',''));
 2500: 
 2501: # ---------------------- Make sure that this gets out, even if user hits "stop"
 2502: 
 2503:     $r->rflush();
 2504: 
 2505: # ---------------------------------------------------------------- Full recalc?
 2506: 
 2507: 
 2508:     if ($ENV{'form.forcerecalc'}) {
 2509: 	$r->print('<h4>Completely Recalculating Sheet ...</h4>');
 2510:         undef %spreadsheets;
 2511:         undef %courserdatas;
 2512:         undef %userrdatas;
 2513:         undef %defaultsheets;
 2514:         undef %updatedata;
 2515:    }
 2516:  
 2517: # ---------------------------------------- Read new sheet or modified worksheet
 2518: 
 2519:     $r->uri=~/\/(\w+)$/;
 2520: 
 2521:     my $asheet=&makenewsheet($aname,$adom,$1,$ENV{'form.usymb'});
 2522: 
 2523: # ------------------------ If a new formula had been entered, go from work copy
 2524: 
 2525:     if ($ENV{'form.unewfield'}) {
 2526:         $r->print('<h2>Modified Workcopy</h2>');
 2527:         $ENV{'form.unewformula'}=~s/\'/\"/g;
 2528:         $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
 2529:                   $ENV{'form.unewformula'}.'<p>');
 2530:         &setfilename($asheet,$ENV{'form.ufn'});
 2531: 	&tmpread($asheet,
 2532:                  $ENV{'form.unewfield'},$ENV{'form.unewformula'});
 2533: 
 2534:      } elsif ($ENV{'form.saveas'}) {
 2535:         &setfilename($asheet,$ENV{'form.ufn'});
 2536: 	&tmpread($asheet);
 2537:     } else {
 2538:         &readsheet($asheet,$ENV{'form.ufn'});
 2539:     }
 2540: 
 2541: # -------------------------------------------------- Print out user information
 2542: 
 2543:     unless (&gettype($asheet) eq 'classcalc') {
 2544:         $r->print('<p><b>User:</b> '.&getuname($asheet).
 2545:                   '<br><b>Domain:</b> '.&getudom($asheet));
 2546:         if (&getcsec($asheet) eq '-1') {
 2547:            $r->print('<h3><font color=red>'.
 2548:                      'Not a student in this course</font></h3>');
 2549:         } else {
 2550:            $r->print('<br><b>Section/Group:</b> '.&getcsec($asheet));
 2551:         }
 2552:         if ($ENV{'form.usymb'}) {
 2553:            $r->print('<br><b>Assessment:</b> <tt>'.$ENV{'form.usymb'}.'</tt>');
 2554:         }
 2555:     }
 2556: 
 2557: # ---------------------------------------------------------------- Course title
 2558: 
 2559:     $r->print('<h1>'.
 2560:             $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.
 2561:              '</h1><h3>'.localtime().'</h3>');
 2562: 
 2563: # ---------------------------------------------------- See if user can see this
 2564: 
 2565:     if ((&gettype($asheet) eq 'classcalc') || 
 2566:         (&getuname($asheet) ne $ENV{'user.name'}) ||
 2567:         (&getudom($asheet) ne $ENV{'user.domain'})) {
 2568:         unless (&Apache::lonnet::allowed('vgr',&getcid($asheet))) {
 2569: 	    $r->print(
 2570:            '<h1>Access Permission Denied</h1></form></body></html>');
 2571:             return OK;
 2572:         }
 2573:     }
 2574: 
 2575: # ---------------------------------------------------------- Additional options
 2576: 
 2577:     $r->print(
 2578:  '<input type=submit name=forcerecalc value="Completely Recalculate Sheet"><p>'
 2579: 		 );
 2580:     if (&gettype($asheet) eq 'assesscalc') {
 2581:        $r->print ('<p><font size=+2><a href="/adm/studentcalc?uname='.
 2582:                                                &getuname($asheet).
 2583:                                                '&udom='.&getudom($asheet).
 2584:                   '">Level up: Student Sheet</a></font><p>');
 2585:     }
 2586:     
 2587:     if ((&gettype($asheet) eq 'studentcalc') && 
 2588:         (&Apache::lonnet::allowed('vgr',&getcid($asheet)))) {
 2589:        $r->print (
 2590:                    '<p><font size=+2><a href="/adm/classcalc">'.
 2591:                    'Level up: Course Sheet</a></font><p>');
 2592:     }
 2593:     
 2594: 
 2595: # ----------------------------------------------------------------- Save dialog
 2596: 
 2597: 
 2598:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2599:         my $fname=$ENV{'form.ufn'};
 2600:         $fname=~s/\_[^\_]+$//;
 2601:         if ($fname eq 'default') { $fname='course_default'; }
 2602:         $r->print('<input type=submit name=saveas value="Save as ...">'.
 2603:               '<input type=text size=20 name=newfn value="'.$fname.
 2604:               '"> (make default: <input type=checkbox name="makedefufn">)<p>');
 2605:     }
 2606: 
 2607:     $r->print(&hiddenfield('ufn',&getfilename($asheet)));
 2608: 
 2609: # ----------------------------------------------------------------- Load dialog
 2610:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2611: 	$r->print('<p><input type=submit name=load value="Load ...">'.
 2612:                   '<select name="loadthissheet">'.
 2613:                   '<option name="default">Default</option>');
 2614:         foreach (&othersheets($asheet,&gettype($asheet))) {
 2615: 	    $r->print('<option name="'.$_.'"');
 2616:             if ($ENV{'form.ufn'} eq $_) {
 2617:                $r->print(' selected');
 2618:             }
 2619:             $r->print('>'.$_.'</option>');
 2620:         } 
 2621:         $r->print('</select><p>');
 2622:         if (&gettype($asheet) eq 'studentcalc') {
 2623: 	    &setothersheets($asheet,&othersheets($asheet,'assesscalc'));
 2624:         }
 2625:     }
 2626: 
 2627: # --------------------------------------------------------------- Cached sheets
 2628: 
 2629:     &expirationdates();
 2630: 
 2631:     undef %oldsheets;
 2632:     undef %loadedcaches;
 2633: 
 2634:     if (&gettype($asheet) eq 'classcalc') {
 2635:         $r->print("Loading previously calculated student sheets ...<br>\n");
 2636:         $r->rflush();
 2637:         &cachedcsheets();
 2638:     } elsif (&gettype($asheet) eq 'studentcalc') {
 2639:         $r->print("Loading previously calculated assessment sheets ...<br>\n");
 2640:         $r->rflush();
 2641:         &cachedssheets(&getuname($asheet),&getudom($asheet),
 2642:                        &getuhome($asheet));
 2643:     }
 2644: 
 2645: # ----------------------------------------------------- Update sheet, load rows
 2646: 
 2647:     $r->print("Loaded sheet(s), updating rows ...<br>\n");
 2648:     $r->rflush();
 2649: 
 2650:     &updatesheet($asheet);
 2651: 
 2652:     $r->print("Updated rows, loading row data ...<br>\n");
 2653:     $r->rflush();
 2654: 
 2655:     &loadrows($asheet,$r);
 2656: 
 2657:     $r->print("Loaded row data, calculating sheet ...<br>\n");
 2658:     $r->rflush();
 2659: 
 2660:     my $calcoutput=&calcsheet($asheet);
 2661:     $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
 2662: 
 2663: # ---------------------------------------------------- See if something to save
 2664: 
 2665:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2666:         my $fname='';
 2667: 	if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
 2668:             $fname=~s/\W/\_/g;
 2669:             if ($fname eq 'default') { $fname='course_default'; }
 2670:             $fname.='_'.&gettype($asheet);
 2671:             &setfilename($asheet,$fname);
 2672:             $ENV{'form.ufn'}=$fname;
 2673: 	    $r->print('<p>Saving spreadsheet: '.
 2674:                          &writesheet($asheet,$ENV{'form.makedefufn'}).'<p>');
 2675: 	}
 2676:     }
 2677: 
 2678: # ------------------------------------------------ Write the modified worksheet
 2679: 
 2680:    $r->print('<b>Current sheet:</b> '.&getfilename($asheet).'<p>');
 2681: 
 2682:    &tmpwrite($asheet);
 2683: 
 2684:     if (&gettype($asheet) eq 'studentcalc') {
 2685: 	$r->print('<br>Show rows with empty A column: ');
 2686:     } else {
 2687:         $r->print('<br>Show empty rows: ');
 2688:     } 
 2689: 
 2690:     $r->print(&hiddenfield('userselhidden','true').
 2691:              '<input type=checkbox name=showall onClick="submit()"');
 2692: 
 2693:     if ($ENV{'form.showall'}) { 
 2694:        $r->print(' checked'); 
 2695:     } else {
 2696: 	unless ($ENV{'form.userselhidden'}) {
 2697:            unless 
 2698: 	($ENV{'course.'.$ENV{'request.course.id'}.'.hideemptyrows'} eq 'yes') {
 2699:           $r->print(' checked');
 2700:           $ENV{'form.showall'}=1;
 2701:            }
 2702:        }
 2703:     }
 2704:     $r->print('>');
 2705: 
 2706:     if (&gettype($asheet) eq 'classcalc') {
 2707:        $r->print(
 2708:    ' Output CSV format: <input type=checkbox name=showcsv onClick="submit()"');
 2709:        if ($ENV{'form.showcsv'}) { $r->print(' checked'); }
 2710:        $r->print('>');
 2711:     }
 2712: 
 2713: # ------------------------------------------------------------------ Insertrows
 2714: 
 2715:    $r->print(<<ENDINSERTBUTTONS);
 2716: <br>
 2717: <input type='button' onClick='insertrow("top");' 
 2718: value='Insert Row Top'>
 2719: <input type='button' onClick='insertrow("bottom");' 
 2720: value='Insert Row Bottom'><br>
 2721: ENDINSERTBUTTONS
 2722: 
 2723: # ------------------------------------------------------------- Print out sheet
 2724: 
 2725:     &outsheet($r,$asheet);
 2726:     $r->print('</form></body></html>');
 2727: 
 2728: # ------------------------------------------------------------------------ Done
 2729:   } else {
 2730: # ----------------------------- Not in a course, or not allowed to modify parms
 2731:       $ENV{'user.error.msg'}=
 2732:         $r->uri.":opa:0:0:Cannot modify spreadsheet";
 2733:       return HTTP_NOT_ACCEPTABLE; 
 2734:   }
 2735:     return OK;
 2736: 
 2737: }
 2738: 
 2739: 1;
 2740: __END__
 2741: 
 2742: 
 2743: 
 2744: 

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