File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.83: download - view: text, annotated - select for diffs
Wed Apr 10 15:30:13 2002 UTC (22 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Load spreadsheets from resource space now works properly.

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

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