File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.116: download - view: text, annotated - select for diffs
Mon Oct 7 19:11:39 2002 UTC (21 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Note: this version has a lot of changes and has not been thoroughly tested.
Big changes:
    Removed many of the get/set functions.  The variables set are in
	%{$sheetdata}.
    &loadassessment was modified to cache unescaped, hashified data instead
       of caching the results of &reply.
Many functions were changed to use $sheetdata to get/store information about
    the sheets.
&handler was changed to use $sheet and $sheetdata instead of $asheet and
$asheetdata.  Also modified to not call the removed get/set functions.

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

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