File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.109: download - view: text, annotated - select for diffs
Tue Sep 10 19:04:13 2002 UTC (21 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
A few changes.
changed $cfn to $coursefilename
commented out code that thought &Apache::lonnet::usection returned -1 if
the user was not in the course.  It returns -1 if the user has no section
listed or if they are not in the course.
Minor reformatting where we get the user data, no code changes at all (yet).
A little more removing &gettype and other calls into ths safe space.

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

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