File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.96: download - view: text, annotated - select for diffs
Fri Jul 5 21:44:50 2002 UTC (22 years ago) by www
Branches: MAIN
CVS tags: HEAD
share('$@') magically activated the eval error checking in a test program
(thanks Matthew!), but apparently still not here.

Test program:

use strict;
use Safe;

my $stuff=(<<'ENDSTUFF');
my $a=5;
my $b=0;

my $c=eval '$a/$b';
return 'Oops '.$@;
ENDSTUFF

my $se=new Safe;
$se->permit("entereval");
$se->share('$@');

print $se->reval($stuff)."\n";
print eval($stuff)."\n";

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

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