File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.91: download - view: text, annotated - select for diffs
Sat Jun 8 15:27:06 2002 UTC (22 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: version_0_4, stable_2002_july, STABLE, HEAD
removed send_msg safehole wrapping because send_msg routines have been
removed from the spreadsheet.

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

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