File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.114: download - view: text, annotated - select for diffs
Mon Sep 30 18:47:43 2002 UTC (21 years, 9 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
No longer need to ask for 'resourcedata.db' file every assessment sheet.
Now cache the fact that it did not exist.  This reduces the number of
calls to lonnet::dump to 1 instead of 1 per assessment.

    1: #
    2: # $Id: lonspreadsheet.pm,v 1.114 2002/09/30 18:47:43 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: 
 1010: sub setformulas {
 1011:     my ($safeeval,%f)=@_;
 1012:     %{$safeeval->varglob('f')}=%f;
 1013: }
 1014: 
 1015: # ------------------------------------------------ Add or change formula values
 1016: 
 1017: sub setconstants {
 1018:     my ($safeeval,%c)=@_;
 1019:     %{$safeeval->varglob('c')}=%c;
 1020: }
 1021: 
 1022: # --------------------------------------------- Set names of other spreadsheets
 1023: 
 1024: sub setothersheets {
 1025:     my ($safeeval,@os)=@_;
 1026:     @{$safeeval->varglob('os')}=@os;
 1027: }
 1028: 
 1029: # ------------------------------------------------ Add or change formula values
 1030: 
 1031: sub setrowlabels {
 1032:     my ($safeeval,%rowlabel)=@_;
 1033:     %{$safeeval->varglob('rowlabel')}=%rowlabel;
 1034: }
 1035: 
 1036: # ------------------------------------------------------- Calculate spreadsheet
 1037: 
 1038: sub calcsheet {
 1039:     my $safeeval=shift;
 1040:     return $safeeval->reval('&calc();');
 1041: }
 1042: 
 1043: # ------------------------------------------------------------------ Get values
 1044: 
 1045: sub getvalues {
 1046:     my $safeeval=shift;
 1047:     return $safeeval->reval('%sheet_values');
 1048: }
 1049: 
 1050: # ---------------------------------------------------------------- Get formulas
 1051: 
 1052: sub getformulas {
 1053:     my $safeeval=shift;
 1054:     return %{$safeeval->varglob('f')};
 1055: }
 1056: 
 1057: # ----------------------------------------------------- Get value of $f{'A'.$n}
 1058: 
 1059: sub getfa {
 1060:     my ($safeeval,$n)=@_;
 1061:     return $safeeval->reval('$f{"A'.$n.'"}');
 1062: }
 1063: 
 1064: # -------------------------------------------------------------------- Get type
 1065: 
 1066: sub gettype {
 1067:     my $safeeval=shift;
 1068:     return $safeeval->reval('$sheettype');
 1069: }
 1070: 
 1071: # ------------------------------------------------------------------ Set maxrow
 1072: 
 1073: sub setmaxrow {
 1074:     my ($safeeval,$row)=@_;
 1075:     $safeeval->reval('$maxrow='.$row.';');
 1076: }
 1077: 
 1078: # ------------------------------------------------------------------ Get maxrow
 1079: 
 1080: sub getmaxrow {
 1081:     my $safeeval=shift;
 1082:     return $safeeval->reval('$maxrow');
 1083: }
 1084: 
 1085: # ---------------------------------------------------------------- Set filename
 1086: 
 1087: sub setfilename {
 1088:     my ($safeeval,$fn)=@_;
 1089:     $safeeval->reval('$filename="'.$fn.'";');
 1090: }
 1091: 
 1092: # ---------------------------------------------------------------- Get filename
 1093: 
 1094: sub getfilename {
 1095:     my $safeeval=shift;
 1096:     return $safeeval->reval('$filename');
 1097: }
 1098: 
 1099: # --------------------------------------------------------------- Get course ID
 1100: 
 1101: sub getcid {
 1102:     my $safeeval=shift;
 1103:     return $safeeval->reval('$cid');
 1104: }
 1105: 
 1106: # --------------------------------------------------------- Get course filename
 1107: 
 1108: sub getcoursefilename {
 1109:     my $safeeval=shift;
 1110:     return $safeeval->reval('$coursefilename');
 1111: }
 1112: 
 1113: # ----------------------------------------------------------- Get course number
 1114: 
 1115: sub getcnum {
 1116:     my $safeeval=shift;
 1117:     return $safeeval->reval('$cnum');
 1118: }
 1119: 
 1120: # ------------------------------------------------------------- Get course home
 1121: 
 1122: sub getchome {
 1123:     my $safeeval=shift;
 1124:     return $safeeval->reval('$chome');
 1125: }
 1126: 
 1127: # ----------------------------------------------------------- Get course domain
 1128: 
 1129: sub getcdom {
 1130:     my $safeeval=shift;
 1131:     return $safeeval->reval('$cdom');
 1132: }
 1133: 
 1134: # ---------------------------------------------------------- Get course section
 1135: 
 1136: sub getcsec {
 1137:     my $safeeval=shift;
 1138:     return $safeeval->reval('$csec');
 1139: }
 1140: 
 1141: # --------------------------------------------------------------- Get user name
 1142: 
 1143: sub getuname {
 1144:     my $safeeval=shift;
 1145:     return $safeeval->reval('$uname');
 1146: }
 1147: 
 1148: # ------------------------------------------------------------- Get user domain
 1149: 
 1150: sub getudom {
 1151:     my $safeeval=shift;
 1152:     return $safeeval->reval('$udom');
 1153: }
 1154: 
 1155: # --------------------------------------------------------------- Get user home
 1156: 
 1157: sub getuhome {
 1158:     my $safeeval=shift;
 1159:     return $safeeval->reval('$uhome');
 1160: }
 1161: 
 1162: # -------------------------------------------------------------------- Get symb
 1163: 
 1164: sub getusymb {
 1165:     my $safeeval=shift;
 1166:     return $safeeval->reval('$usymb');
 1167: }
 1168: 
 1169: # ------------------------------------------------------------- Export of A-row
 1170: 
 1171: sub exportdata {
 1172:     my $safeeval=shift;
 1173:     return $safeeval->reval('&exportrowa()');
 1174: }
 1175: 
 1176: 
 1177: # ========================================================== End of Spreadsheet
 1178: # =============================================================================
 1179: 
 1180: #
 1181: # Procedures for screen output
 1182: #
 1183: # --------------------------------------------- Produce output row n from sheet
 1184: 
 1185: sub rown {
 1186:     my ($safeeval,$n)=@_;
 1187:     my $defaultbg;
 1188:     my $rowdata='';
 1189:     my $dataflag=0;
 1190:     unless ($n eq '-') {
 1191:         $defaultbg=((($n-1)/5)==int(($n-1)/5))?'#E0E0':'#FFFF';
 1192:     } else {
 1193:         $defaultbg='#E0FF';
 1194:     }
 1195:     unless ($ENV{'form.showcsv'}) {
 1196:         $rowdata.="\n<tr><td><b><font size=+1>$n</font></b></td>";
 1197:     } else {
 1198:         $rowdata.="\n".'"'.$n.'"';
 1199:     }
 1200:     my $showf=0;
 1201:     my $proc;
 1202:     my $maxred=1;
 1203:     my $sheettype=&gettype($safeeval);
 1204:     if ($sheettype eq 'studentcalc') {
 1205:         $proc='&outrowassess';
 1206:         $maxred=26;
 1207:     } else {
 1208:         $proc='&outrow';
 1209:     }
 1210:     if ($sheettype eq 'assesscalc') {
 1211:         $maxred=1;
 1212:     } else {
 1213:         $maxred=26;
 1214:     }
 1215:     if (&getfa($safeeval,$n)=~/^[\~\-]/) { $maxred=1; }
 1216:     if ($n eq '-') { 
 1217:         $proc='&templaterow'; 
 1218:         $n=-1; 
 1219:         $dataflag=1; 
 1220:     }
 1221:     foreach ($safeeval->reval($proc.'('.$n.')')) {
 1222:         my $bgcolor=$defaultbg.((($showf-1)/5==int(($showf-1)/5))?'99':'DD');
 1223:         my ($fm,$vl)=split(/\_\_\_eq\_\_\_/,$_);
 1224:         if ((($vl ne '') || ($vl eq '0')) &&
 1225:             (($showf==1) || ($sheettype ne 'studentcalc'))) { $dataflag=1; }
 1226:         if ($showf==0) { $vl=$_; }
 1227:         unless ($ENV{'form.showcsv'}) {
 1228:             if ($showf<=$maxred) { $bgcolor='#FFDDDD'; }
 1229:             if (($n==0) && ($showf<=26)) { $bgcolor='#CCCCFF'; } 
 1230:             if (($showf>$maxred) || ((!$n) && ($showf>0))) {
 1231:                 if ($vl eq '') {
 1232:                     $vl='<font size=+2 color='.$bgcolor.'>&#35;</font>';
 1233:                 }
 1234:                 $rowdata.='<td bgcolor='.$bgcolor.'>';
 1235:                 if ($ENV{'request.role'} =~ /^st\./) {
 1236:                     $rowdata.=$vl;
 1237:                 } else {
 1238:                     $rowdata.='<a href="javascript:celledit('.$fm.');">'.
 1239:                         $vl.'</a>';
 1240:                 }
 1241:                 $rowdata.='</td>';
 1242:             } else {
 1243:                 $rowdata.='<td bgcolor='.$bgcolor.'>&nbsp;'.$vl.'&nbsp;</td>';
 1244:             }
 1245:         } else {
 1246:             $rowdata.=',"'.$vl.'"';
 1247:         }
 1248:         $showf++;
 1249:     }  # End of foreach($safeval...)
 1250:     if ($ENV{'form.showall'} || ($dataflag)) {
 1251:         return $rowdata.($ENV{'form.showcsv'}?'':'</tr>');
 1252:     } else {
 1253:         return '';
 1254:     }
 1255: }
 1256: 
 1257: # ------------------------------------------------------------- Print out sheet
 1258: 
 1259: sub outsheet {
 1260:     my ($r,$safeeval,$sheetdata)=@_;
 1261:     my $maxred = 26;    # The maximum number of cells to show as 
 1262:                         # red (uneditable) 
 1263:                         # To make student sheets uneditable could we 
 1264:                         # set $maxred = 52?
 1265:                         #
 1266:     my $realm='Course'; # 'assessment', 'user', or 'course' sheet
 1267:     if ($sheetdata->{'sheettype'} eq 'assesscalc') {
 1268:         $maxred=1;
 1269:         $realm='Assessment';
 1270:     } elsif ($sheetdata->{'sheettype'} eq 'studentcalc') {
 1271:         $maxred=26;
 1272:         $realm='User';
 1273:     }
 1274:     #
 1275:     # Column label
 1276:     my $tabledata;
 1277:     if ($ENV{'form.showcsv'}) {
 1278:         $tabledata='<pre>';
 1279:     } else { 
 1280:         $tabledata='<table border=2><tr><th colspan=2 rowspan=2>'.
 1281:             '<font size=+2>'.$realm.'</font></th>'.
 1282:                   '<td bgcolor=#FFDDDD colspan='.$maxred.
 1283:                   '><b><font size=+1>Import</font></b></td>'.
 1284:                   '<td colspan='.(52-$maxred).
 1285: 		  '><b><font size=+1>Calculations</font></b></td></tr><tr>';
 1286:         my $showf=0;
 1287:         foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1288:                  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 1289:                  'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1290:                  'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1291:             $showf++;
 1292:             if ($showf<=$maxred) { 
 1293:                 $tabledata.='<td bgcolor="#FFDDDD">'; 
 1294:             } else {
 1295:                 $tabledata.='<td>';
 1296:             }
 1297:             $tabledata.="<b><font size=+1>$_</font></b></td>";
 1298:         }
 1299:         $tabledata.='</tr>'.&rown($safeeval,'-').&rown($safeeval,0);
 1300:     }
 1301:     $r->print($tabledata);
 1302:     #
 1303:     # Prepare to output rows
 1304:     my $row;
 1305:     my $maxrow=&getmaxrow($safeeval);
 1306:     #
 1307:     my @sortby=();
 1308:     my @sortidx=();
 1309:     for ($row=1;$row<=$maxrow;$row++) {
 1310:         push (@sortby, $safeeval->reval('$f{"A'.$row.'"}'));
 1311:         push (@sortidx, $row-1);
 1312:     }
 1313:     @sortidx=sort { lc($sortby[$a]) cmp lc($sortby[$b]); } @sortidx;
 1314:     #
 1315:     # Determine the type of child spreadsheets
 1316:     my $what='Student';
 1317:     if ($sheetdata->{'sheettype'} eq 'assesscalc') {
 1318:         $what='Item';
 1319:     } elsif ($sheetdata->{'sheettype'} eq 'studentcalc') {
 1320:         $what='Assessment';
 1321:     }
 1322:     #
 1323:     # Loop through the rows and output them one at a time
 1324:     my $n=0;
 1325:     for ($row=0;$row<$maxrow;$row++) {
 1326:         my $thisrow=&rown($safeeval,$sortidx[$row]+1);
 1327:         if ($thisrow) {
 1328:             if (($n/25==int($n/25)) && (!$ENV{'form.showcsv'})) {
 1329:                 $r->print("</table>\n<br>\n");
 1330:                 $r->rflush();
 1331:                 $r->print('<table border=2><tr><td>&nbsp;<td>'.$what.'</td>');
 1332:                 $r->print('<td>'.
 1333:                           join('</td><td>',
 1334:                                (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
 1335:                                       'abcdefghijklmnopqrstuvwxyz'))).
 1336:                           "</td></tr>\n");
 1337:             }
 1338:             $n++;
 1339:             $r->print($thisrow);
 1340:         }
 1341:     }
 1342:     $r->print($ENV{'form.showcsv'}?'</pre>':'</table>');
 1343: }
 1344: 
 1345: #
 1346: # ----------------------------------------------- Read list of available sheets
 1347: # 
 1348: sub othersheets {
 1349:     my ($safeeval,$stype)=@_;
 1350:     #
 1351:     my $cnum  = &getcnum($safeeval);
 1352:     my $cdom  = &getcdom($safeeval);
 1353:     my $chome = &getchome($safeeval);
 1354:     #
 1355:     my @alternatives=();
 1356:     my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
 1357:     my ($tmp) = keys(%results);
 1358:     unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1359:         @alternatives = sort (keys(%results));
 1360:     }
 1361:     return @alternatives; 
 1362: }
 1363: 
 1364: 
 1365: #
 1366: # -------------------------------------- Parse a spreadsheet
 1367: # 
 1368: sub parse_sheet {
 1369:     # $sheetxml is a scalar reference or a scalar
 1370:     my ($sheetxml) = @_;
 1371:     if (! ref($sheetxml)) {
 1372:         my $tmp = $sheetxml;
 1373:         $sheetxml = \$tmp;
 1374:     }
 1375:     my %f;
 1376:     my $parser=HTML::TokeParser->new($sheetxml);
 1377:     my $token;
 1378:     while ($token=$parser->get_token) {
 1379:         if ($token->[0] eq 'S') {
 1380:             if ($token->[1] eq 'field') {
 1381:                 $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
 1382:                     $parser->get_text('/field');
 1383:             }
 1384:             if ($token->[1] eq 'template') {
 1385:                 $f{'template_'.$token->[2]->{'col'}}=
 1386:                     $parser->get_text('/template');
 1387:             }
 1388:         }
 1389:     }
 1390:     return \%f;
 1391: }
 1392: 
 1393: #
 1394: # -------------------------------------- Read spreadsheet formulas for a course
 1395: #
 1396: sub readsheet {
 1397:     my ($safeeval,$sheetdata,$fn)=@_;
 1398:     #
 1399:     my $stype = $sheetdata->{'sheettype'};
 1400:     my $cnum  = $sheetdata->{'cnum'};
 1401:     my $cdom  = $sheetdata->{'cdom'};
 1402:     my $chome = $sheetdata->{'chome'};
 1403:     #
 1404:     if (! defined($fn)) {
 1405:         # There is no filename. Look for defaults in course and global, cache
 1406:         unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
 1407:             my %tmphash = &Apache::lonnet::get('environment',
 1408:                                                ['spreadsheet_default_'.$stype],
 1409:                                                $cdom,$cnum);
 1410:             my ($tmp) = keys(%tmphash);
 1411:             if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1412:                 $fn = 'default_'.$stype;
 1413:             } else {
 1414:                 $fn = $tmphash{'spreadsheet_default_'.$stype};
 1415:             } 
 1416:             unless (($fn) && ($fn!~/^error\:/)) {
 1417:                 $fn='default_'.$stype;
 1418:             }
 1419:             $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn; 
 1420:         }
 1421:     }
 1422:     # $fn now has a value
 1423:     &setfilename($safeeval,$fn);
 1424:     # see if sheet is cached
 1425:     my $fstring='';
 1426:     if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
 1427:         &setformulas($safeeval,split(/\_\_\_\;\_\_\_/,$fstring));
 1428:     } else {
 1429:         # Not cached, need to read
 1430:         my %f=();
 1431:         if ($fn=~/^default\_/) {
 1432:             my $sheetxml='';
 1433:             my $fh;
 1434:             my $dfn=$fn;
 1435:             $dfn=~s/\_/\./g;
 1436:             if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
 1437:                 $sheetxml=join('',<$fh>);
 1438:             } else {
 1439:                 $sheetxml='<field row="0" col="A">"Error"</field>';
 1440:             }
 1441:             %f=%{&parse_sheet(\$sheetxml)};
 1442:         } elsif($fn=~/\/*\.spreadsheet$/) {
 1443:             my $sheetxml=&Apache::lonnet::getfile
 1444:                 (&Apache::lonnet::filelocation('',$fn));
 1445:             if ($sheetxml == -1) {
 1446:                 $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
 1447:                     .$fn.'"</field>';
 1448:             }
 1449:             %f=%{&parse_sheet(\$sheetxml)};
 1450:         } else {
 1451:             my $sheet='';
 1452:             my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
 1453:             my ($tmp) = keys(%tmphash);
 1454:             unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1455:                 foreach (keys(%tmphash)) {
 1456:                     $f{$_}=$tmphash{$_};
 1457:                 }
 1458:             }
 1459:         }
 1460:         # Cache and set
 1461:         $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);  
 1462:         &setformulas($safeeval,%f);
 1463:     }
 1464: }
 1465: 
 1466: # -------------------------------------------------------- Make new spreadsheet
 1467: sub makenewsheet {
 1468:     my ($uname,$udom,$stype,$usymb)=@_;
 1469:     my %sheetdata=();
 1470:     $sheetdata{'uname'} = $uname;
 1471:     $sheetdata{'udom'}  = $udom;
 1472:     $sheetdata{'sheettype'} = $stype;
 1473:     $sheetdata{'usymb'} = $usymb;
 1474:     $sheetdata{'cid'}   = $ENV{'request.course.id'};
 1475:     $sheetdata{'csec'}  = $Section{$uname.':'.$udom};
 1476:     $sheetdata{'coursefilename'}   = $ENV{'request.course.fn'};
 1477:     $sheetdata{'cnum'}  = $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1478:     $sheetdata{'cdom'}  = $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1479:     $sheetdata{'chome'} = $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1480:     $sheetdata{'uhome'} = &Apache::lonnet::homeserver($uname,$udom);
 1481:     
 1482:     my $safeeval=initsheet($stype);
 1483:     my $initstring = '';
 1484:     foreach (keys(%sheetdata)) {
 1485:         $initstring.= qq{\$$_="$sheetdata{$_}";};
 1486:     }
 1487:     $safeeval->reval($initstring);
 1488:     return $safeeval,\%sheetdata;
 1489: }
 1490: 
 1491: # ------------------------------------------------------------ Save spreadsheet
 1492: sub writesheet {
 1493:     my ($safeeval,$makedef)=@_;
 1494:     my $cid=&getcid($safeeval);
 1495:     if (&Apache::lonnet::allowed('opa',$cid)) {
 1496:         my %f=&getformulas($safeeval);
 1497:         my $stype=&gettype($safeeval);
 1498:         my $cnum=&getcnum($safeeval);
 1499:         my $cdom=&getcdom($safeeval);
 1500:         my $chome=&getchome($safeeval);
 1501:         my $fn=&getfilename($safeeval);
 1502:         # Cache new sheet
 1503:         $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
 1504:         # Write sheet
 1505:         my $sheetdata='';
 1506:         foreach (keys(%f)) {
 1507:             unless ($f{$_} eq 'import') {
 1508:                 $sheetdata.=&Apache::lonnet::escape($_).'='.
 1509:                     &Apache::lonnet::escape($f{$_}).'&';
 1510:             }
 1511:         }
 1512:         $sheetdata=~s/\&$//;
 1513:         my $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.$fn.':'.
 1514:                                          $sheetdata,$chome);
 1515:         if ($reply eq 'ok') {
 1516:             $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.
 1517:                                           $stype.'_spreadsheets:'.
 1518:                                           &Apache::lonnet::escape($fn).
 1519:                                           '='.$ENV{'user.name'}.'@'.
 1520:                                           $ENV{'user.domain'},
 1521:                                           $chome);
 1522:             if ($reply eq 'ok') {
 1523:                 if ($makedef) { 
 1524:                     return &Apache::lonnet::reply('put:'.$cdom.':'.$cnum.
 1525:                                                   ':environment:'.
 1526:                                                   'spreadsheet_default_'.
 1527:                                                   $stype.'='.
 1528:                                                   &Apache::lonnet::escape($fn),
 1529:                                                   $chome);
 1530:                 } 
 1531:                 return $reply;
 1532:             } 
 1533:             return $reply;
 1534:         } 
 1535:         return $reply;
 1536:     }
 1537:     return 'unauthorized';
 1538: }
 1539: 
 1540: # ----------------------------------------------- Make a temp copy of the sheet
 1541: # "Modified workcopy" - interactive only
 1542: #
 1543: sub tmpwrite {
 1544:     my $safeeval=shift;
 1545:     my $fn=$ENV{'user.name'}.'_'.
 1546:         $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
 1547:            &getfilename($safeeval);
 1548:     $fn=~s/\W/\_/g;
 1549:     $fn=$tmpdir.$fn.'.tmp';
 1550:     my $fh;
 1551:     if ($fh=Apache::File->new('>'.$fn)) {
 1552: 	print $fh join("\n",&getformulas($safeeval));
 1553:     }
 1554: }
 1555: 
 1556: # ---------------------------------------------------------- Read the temp copy
 1557: sub tmpread {
 1558:     my ($safeeval,$nfield,$nform)=@_;
 1559:     my $fn=$ENV{'user.name'}.'_'.
 1560:            $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
 1561:            &getfilename($safeeval);
 1562:     $fn=~s/\W/\_/g;
 1563:     $fn=$tmpdir.$fn.'.tmp';
 1564:     my $fh;
 1565:     my %fo=();
 1566:     my $countrows=0;
 1567:     if ($fh=Apache::File->new($fn)) {
 1568:         my $name;
 1569:         while ($name=<$fh>) {
 1570: 	    chomp($name);
 1571:             my $value=<$fh>;
 1572:             chomp($value);
 1573:             $fo{$name}=$value;
 1574:             if ($name=~/^A(\d+)$/) {
 1575: 		if ($1>$countrows) {
 1576: 		    $countrows=$1;
 1577:                 }
 1578:             }
 1579:         }
 1580:     }
 1581:     if ($nform eq 'changesheet') {
 1582:         $fo{'A'.$nfield}=(split(/\_\_\&\&\&\_\_/,$fo{'A'.$nfield}))[0];
 1583:         unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
 1584: 	    $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
 1585:         }
 1586:     } elsif ($nfield eq 'insertrow') {
 1587:         $countrows++;
 1588:         my $newrow=substr('000000'.$countrows,-7);
 1589:         if ($nform eq 'top') {
 1590: 	    $fo{'A'.$countrows}='--- '.$newrow;
 1591:         } else {
 1592:             $fo{'A'.$countrows}='~~~ '.$newrow;
 1593:         }
 1594:     } else {
 1595:        if ($nfield) { $fo{$nfield}=$nform; }
 1596:     }
 1597:     &setformulas($safeeval,%fo);
 1598: }
 1599: 
 1600: ##################################################
 1601: ##################################################
 1602: 
 1603: =pod
 1604: 
 1605: =item &parmval()
 1606: 
 1607: Determine the value of a parameter.
 1608: 
 1609: Inputs: $what, the parameter needed, $safeeval, the safe space
 1610: 
 1611: Returns: The value of a parameter, or '' if none.
 1612: 
 1613: This function cascades through the possible levels searching for a value for
 1614: a parameter.  The levels are checked in the following order:
 1615: user, course (at section level and course level), map, and lonnet::metadata.
 1616: This function uses %parmhash, which must be tied prior to calling it.
 1617: This function also requires %courseopt and %useropt to be initialized for
 1618: this user and course.
 1619: 
 1620: =cut
 1621: 
 1622: ##################################################
 1623: ##################################################
 1624: sub parmval {
 1625:     my ($what,$safeeval,$sheetdata)=@_;
 1626:     my $symb  = $sheetdata->{'usymb'};
 1627:     unless ($symb) { return ''; }
 1628:     #
 1629:     my $cid   = $sheetdata->{'cid'};
 1630:     my $csec  = $sheetdata->{'csec'};
 1631:     my $uname = $sheetdata->{'uname'};
 1632:     my $udom  = $sheetdata->{'udom'};
 1633:     my $result='';
 1634:     #
 1635:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 1636:     # Cascading lookup scheme
 1637:     my $rwhat=$what;
 1638:     $what =~ s/^parameter\_//;
 1639:     $what =~ s/\_([^\_]+)$/\.$1/;
 1640:     #
 1641:     my $symbparm = $symb.'.'.$what;
 1642:     my $mapparm  = $mapname.'___(all).'.$what;
 1643:     my $usercourseprefix = $uname.'_'.$udom.'_'.$cid;
 1644:     #
 1645:     my $seclevel  = $usercourseprefix.'.['.$csec.'].'.$what;
 1646:     my $seclevelr = $usercourseprefix.'.['.$csec.'].'.$symbparm;
 1647:     my $seclevelm = $usercourseprefix.'.['.$csec.'].'.$mapparm;
 1648:     #
 1649:     my $courselevel  = $usercourseprefix.'.'.$what;
 1650:     my $courselevelr = $usercourseprefix.'.'.$symbparm;
 1651:     my $courselevelm = $usercourseprefix.'.'.$mapparm;
 1652:     # fourth, check user
 1653:     if ($uname) { 
 1654:         return $useropt{$courselevelr} if ($useropt{$courselevelr});
 1655:         return $useropt{$courselevelm} if ($useropt{$courselevelm});
 1656:         return $useropt{$courselevel}  if ($useropt{$courselevel});
 1657:     }
 1658:     # third, check course
 1659:     if ($csec) {
 1660:         return $courseopt{$seclevelr} if ($courseopt{$seclevelr});
 1661:         return $courseopt{$seclevelm} if ($courseopt{$seclevelm});
 1662:         return $courseopt{$seclevel}  if ($courseopt{$seclevel});
 1663:     }
 1664:     #
 1665:     return $courseopt{$courselevelr} if ($courseopt{$courselevelr});
 1666:     return $courseopt{$courselevelm} if ($courseopt{$courselevelm});
 1667:     return $courseopt{$courselevel}  if ($courseopt{$courselevel});
 1668:     # second, check map parms
 1669:     my $thisparm = $parmhash{$symbparm};
 1670:     return $thisparm if ($thisparm);
 1671:     # first, check default
 1672:     return &Apache::lonnet::metadata($fn,$rwhat.'.default');
 1673: }
 1674: 
 1675: # ---------------------------------------------- Update rows for course listing
 1676: sub updateclasssheet {
 1677:     my ($safeeval,$sheetdata) = @_;
 1678:     my $cnum  =$sheetdata->{'cnum'};
 1679:     my $cdom  =$sheetdata->{'cdom'};
 1680:     my $cid   =$sheetdata->{'cid'};
 1681:     my $chome =$sheetdata->{'chome'};
 1682:     #
 1683:     %Section = ();
 1684: 
 1685:     #
 1686:     # Read class list and row labels
 1687:     my %classlist;
 1688:     my @tmp = &Apache::lonnet::dump('classlist',$cdom,$cnum);
 1689:     if ($tmp[0] !~ /^error/) {
 1690:         %classlist = @tmp;
 1691:     } else {
 1692:         return 'Could not access course data';
 1693:     }
 1694:     undef @tmp;
 1695:     #
 1696:     my %currentlist=();
 1697:     my $now=time;
 1698:     foreach my $student (keys(%classlist)) {
 1699:         my ($end,$start)=split(/\:/,$classlist{$student});
 1700:         my $active=1;
 1701:         $active = 0 if (($end) && ($now>$end));
 1702:         $active = 1 if ($ENV{'form.Status'} eq 'Any');
 1703:         $active = !$active if ($ENV{'form.Status'} eq 'Expired');
 1704:         if ($active) {
 1705:             my $rowlabel='';
 1706:             my ($studentName,$studentDomain)=split(/\:/,$student);
 1707:             my $studentSection=&Apache::lonnet::usection($studentDomain,
 1708:                                                          $studentName,$cid);
 1709:             $Section{$studentName.':'.$studentDomain} = $studentSection;
 1710: #            if ($studentSection==-1) {
 1711: #                unless ($ENV{'form.showcsv'}) {
 1712: #                    $rowlabel='<font color=red>Data not available: '.
 1713: #                        $studentName.'</font>';
 1714: #                } else {
 1715: #                    $rowlabel='ERROR","'.$studentName.
 1716: #                        '","Data not available","","","';
 1717: #                }
 1718: #            } else {
 1719:                 my %reply=&Apache::lonnet::idrget($studentDomain,$studentName);
 1720:                 my %studentInformation=&Apache::lonnet::get
 1721:                     ('environment',
 1722:                      ['lastname','generation','firstname','middlename','id'],
 1723:                      $studentDomain,$studentName);
 1724:                 if (! $ENV{'form.showcsv'}) {
 1725:                     $rowlabel='<a href="/adm/studentcalc?uname='.$studentName.
 1726:                         '&udom='.$studentDomain.'">'.
 1727:                             $studentSection.'&nbsp;';
 1728:                     foreach ('id','firstname','middlename',
 1729:                              'lastname','generation'){
 1730:                         $rowlabel.=$studentInformation{$_}."&nbsp;";
 1731:                     }
 1732:                     $rowlabel.='</a>';
 1733:                 } else {
 1734:                     $rowlabel= '"'.join('","',
 1735:                                         ($studentSection,
 1736:                                          $studentInformation{'id'},
 1737:                                          $studentInformation{'firstname'},
 1738:                                          $studentInformation{'middlename'},
 1739:                                          $studentInformation{'lastname'},
 1740:                                          $studentInformation{'generation'})
 1741:                                         ).'"';
 1742:                 }
 1743:  #           }
 1744:             $currentlist{$student}=$rowlabel;
 1745:         } # end of if ($active)
 1746:     } # end of foreach my $student (keys(%classlist))
 1747:     #
 1748:     # Find discrepancies between the course row table and this
 1749:     #
 1750:     my %f=&getformulas($safeeval);
 1751:     my $changed=0;
 1752:     #
 1753:     my $maxrow=0;
 1754:     my %existing=();
 1755:     #
 1756:     # Now obsolete rows
 1757:     foreach (keys(%f)) {
 1758:         if ($_=~/^A(\d+)/) {
 1759:             $maxrow=($1>$maxrow)?$1:$maxrow;
 1760:             $existing{$f{$_}}=1;
 1761:             unless ((defined($currentlist{$f{$_}})) || (!$1) ||
 1762:                     ($f{$_}=~/^(\~\~\~|\-\-\-)/)) {
 1763:                 $f{$_}='!!! Obsolete';
 1764:                 $changed=1;
 1765:             }
 1766:         }
 1767:     }
 1768:     #
 1769:     # New and unknown keys
 1770:     foreach (sort keys(%currentlist)) {
 1771:         unless ($existing{$_}) {
 1772:             $changed=1;
 1773:             $maxrow++;
 1774:             $f{'A'.$maxrow}=$_;
 1775:         }
 1776:     }
 1777:     if ($changed) { &setformulas($safeeval,%f); }
 1778:     #
 1779:     &setmaxrow($safeeval,$maxrow);
 1780:     &setrowlabels($safeeval,%currentlist);
 1781: }
 1782: 
 1783: # ----------------------------------- Update rows for student and assess sheets
 1784: sub updatestudentassesssheet {
 1785:     my ($safeeval,$sheetdata) = @_;
 1786:     my %bighash;
 1787:     my $stype=$sheetdata->{'sheettype'};
 1788:     my $uname=$sheetdata->{'uname'};
 1789:     my $udom =$sheetdata->{'udom'};
 1790:     my %current=();
 1791:     if  ($updatedata
 1792:          {$ENV{'request.course.fn'}.'_'.$stype.'_'.$uname.'_'.$udom}) {
 1793:         %current=split(/\_\_\_\;\_\_\_/,
 1794:                        $updatedata{$ENV{'request.course.fn'}.
 1795:                                        '_'.$stype.'_'.$uname.'_'.$udom});
 1796:     } else {
 1797:         # Tie hash
 1798:         tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 1799:             &GDBM_READER(),0640);
 1800:         if (! tied(%bighash)) {
 1801:             return 'Could not access course data';
 1802:         }
 1803:         # Get all assessments
 1804:         my %allkeys=('timestamp' => 
 1805:                      'Timestamp of Last Transaction<br>timestamp',
 1806:                      'subnumber' =>
 1807:                      'Number of Submissions<br>subnumber',
 1808:                      'tutornumber' =>
 1809:                      'Number of Tutor Responses<br>tutornumber',
 1810:                      'totalpoints' =>
 1811:                      'Total Points Granted<br>totalpoints');
 1812:         my $adduserstr='';
 1813:         if (($uname ne $ENV{'user.name'}) || ($udom ne $ENV{'user.domain'})){
 1814:             $adduserstr='&uname='.$uname.'&udom='.$udom;
 1815:         }
 1816:         my %allassess =
 1817:             ('_feedback' =>'<a href="/adm/assesscalc?usymb=_feedback'.
 1818:              $adduserstr.'">Feedback</a>',
 1819:              '_evaluation' =>'<a href="/adm/assesscalc?usymb=_evaluation'.
 1820:              $adduserstr.'">Evaluation</a>',
 1821:              '_tutoring' =>'<a href="/adm/assesscalc?usymb=_tutoring'.
 1822:              $adduserstr.'">Tutoring</a>',
 1823:              '_discussion' =>'<a href="/adm/assesscalc?usymb=_discussion'.
 1824:              $adduserstr.'">Discussion</a>'
 1825:              );
 1826:         while (($_,undef) = each(%bighash)) {
 1827:             next if ($_!~/^src\_(\d+)\.(\d+)$/);
 1828:             my $mapid=$1;
 1829:             my $resid=$2;
 1830:             my $id=$mapid.'.'.$resid;
 1831:             my $srcf=$bighash{$_};
 1832:             if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
 1833:                 my $symb=
 1834:                     &Apache::lonnet::declutter($bighash{'map_id_'.$mapid}).
 1835:                         '___'.$resid.'___'.&Apache::lonnet::declutter($srcf);
 1836:                 $allassess{$symb}=
 1837:                     '<a href="/adm/assesscalc?usymb='.$symb.$adduserstr.'">'.
 1838:                         $bighash{'title_'.$id}.'</a>';
 1839:                 next if ($stype ne 'assesscalc');
 1840:                 foreach my $key (split(/\,/,
 1841:                                        &Apache::lonnet::metadata($srcf,'keys')
 1842:                                        )) {
 1843:                     next if ($key !~ /^(stores|parameter)_/);
 1844:                     my $display=
 1845:                         &Apache::lonnet::metadata($srcf,$key.'.display');
 1846:                     unless ($display) {
 1847:                         $display.=
 1848:                             &Apache::lonnet::metadata($srcf,$key.'.name');
 1849:                     }
 1850:                     $display.='<br>'.$key;
 1851:                     $allkeys{$key}=$display;
 1852:                 } # end of foreach
 1853:             }
 1854:         } # end of foreach (keys(%bighash))
 1855:         untie(%bighash);
 1856:         #
 1857:         # %allkeys has a list of storage and parameter displays by unikey
 1858:         # %allassess has a list of all resource displays by symb
 1859:         #
 1860:         if ($stype eq 'assesscalc') {
 1861:             %current=%allkeys;
 1862:         } elsif ($stype eq 'studentcalc') {
 1863:             %current=%allassess;
 1864:         }
 1865:         $updatedata{$ENV{'request.course.fn'}.'_'.$stype.'_'.$uname.'_'.$udom}=
 1866:             join('___;___',%current);
 1867:         # Get current from cache
 1868:     }
 1869:     # Find discrepancies between the course row table and this
 1870:     #
 1871:     my %f=&getformulas($safeeval);
 1872:     my $changed=0;
 1873:     
 1874:     my $maxrow=0;
 1875:     my %existing=();
 1876:     # Now obsolete rows
 1877:     foreach (keys(%f)) {
 1878:         next if ($_!~/^A(\d+)/);
 1879:         $maxrow=($1>$maxrow)?$1:$maxrow;
 1880:         my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
 1881:         $existing{$usy}=1;
 1882:         unless ((defined($current{$usy})) || (!$1) ||
 1883:                 ($f{$_}=~/^(\~\~\~|\-\-\-)/)){
 1884:             $f{$_}='!!! Obsolete';
 1885:             $changed=1;
 1886:         } elsif ($ufn) {
 1887:             $current{$usy}
 1888:             =~s/assesscalc\?usymb\=/assesscalc\?ufn\=$ufn\&usymb\=/;
 1889:         }
 1890:     }
 1891:     # New and unknown keys
 1892:     foreach (keys(%current)) {
 1893:         unless ($existing{$_}) {
 1894:             $changed=1;
 1895:             $maxrow++;
 1896:             $f{'A'.$maxrow}=$_;
 1897:         }
 1898:     }
 1899:     if ($changed) { &setformulas($safeeval,%f); }
 1900:     &setmaxrow($safeeval,$maxrow);
 1901:     &setrowlabels($safeeval,%current);
 1902:     #
 1903:     undef %current;
 1904:     undef %existing;
 1905: }
 1906: 
 1907: # ------------------------------------------------ Load data for one assessment
 1908: 
 1909: sub loadstudent {
 1910:     my ($safeeval,$sheetdata)=@_;
 1911:     my %c=();
 1912:     my %f=&getformulas($safeeval);
 1913:     $cachedassess=$sheetdata->{'uname'}.':'.$sheetdata->{'udom'};
 1914:     # Get ALL the student preformance data
 1915:     my @tmp = &Apache::lonnet::dump($sheetdata->{'cid'},
 1916:                                     $sheetdata->{'udom'},
 1917:                                     $sheetdata->{'uname'},
 1918:                                     undef);
 1919:     if ($tmp[0] !~ /^error:/) {
 1920:         %cachedstores = @tmp;
 1921:     }
 1922:     undef @tmp;
 1923:     # 
 1924:     my @assessdata=();
 1925:     foreach (keys(%f)) {
 1926: 	next if ($_!~/^A(\d+)/);
 1927:         my $row=$1;
 1928:         next if (($f{$_}=~/^[\!\~\-]/) || ($row==0));
 1929:         my ($usy,$ufn)=split(/__&&&\__/,$f{$_});
 1930:         @assessdata=&exportsheet($sheetdata->{'uname'},
 1931:                                  $sheetdata->{'udom'},
 1932:                                  'assesscalc',$usy,$ufn);
 1933:         my $index=0;
 1934:         foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1935:                  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 1936:             if ($assessdata[$index]) {
 1937:                 my $col=$_;
 1938:                 if ($assessdata[$index]=~/\D/) {
 1939:                     $c{$col.$row}="'".$assessdata[$index]."'";
 1940:                 } else {
 1941:                     $c{$col.$row}=$assessdata[$index];
 1942:                 }
 1943:                 unless ($col eq 'A') { 
 1944:                     $f{$col.$row}='import';
 1945:                 }
 1946:             }
 1947:             $index++;
 1948:         }
 1949:     }
 1950:     $cachedassess='';
 1951:     undef %cachedstores;
 1952:     &setformulas($safeeval,%f);
 1953:     &setconstants($safeeval,%c);
 1954: }
 1955: 
 1956: # --------------------------------------------------- Load data for one student
 1957: #
 1958: sub loadcourse {
 1959:     my ($safeeval,$sheetdata,$r)=@_;
 1960:     my %c=();
 1961:     my %f=&getformulas($safeeval);
 1962:     my $total=0;
 1963:     foreach (keys(%f)) {
 1964: 	if ($_=~/^A(\d+)/) {
 1965: 	    unless ($f{$_}=~/^[\!\~\-]/) { $total++; }
 1966:         }
 1967:     }
 1968:     my $now=0;
 1969:     my $since=time;
 1970:     $r->print(<<ENDPOP);
 1971: <script>
 1972:     popwin=open('','popwin','width=400,height=100');
 1973:     popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
 1974:       '<h3>Spreadsheet Calculation Progress</h3>'+
 1975:       '<form name=popremain>'+
 1976:       '<input type=text size=35 name=remaining value=Starting></form>'+
 1977:       '</body></html>');
 1978:     popwin.document.close();
 1979: </script>
 1980: ENDPOP
 1981:     $r->rflush();
 1982:     foreach (keys(%f)) {
 1983: 	next if ($_!~/^A(\d+)/);
 1984:         my $row=$1;
 1985:         next if (($f{$_}=~/^[\!\~\-]/)  || ($row==0));
 1986:         my @studentdata=&exportsheet(split(/\:/,$f{$_}),
 1987:                                      'studentcalc');
 1988:         undef %userrdatas;
 1989:         $now++;
 1990:         $r->print('<script>popwin.document.popremain.remaining.value="'.
 1991:                   $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
 1992:                   ' secs remaining";</script>');
 1993:         $r->rflush(); 
 1994:         #
 1995:         my $index=0;
 1996:         foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1997:                  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 1998:             if ($studentdata[$index]) {
 1999:                 my $col=$_;
 2000:                 if ($studentdata[$index]=~/\D/) {
 2001:                     $c{$col.$row}="'".$studentdata[$index]."'";
 2002:                 } else {
 2003:                     $c{$col.$row}=$studentdata[$index];
 2004:                 }
 2005:                 unless ($col eq 'A') { 
 2006:                     $f{$col.$row}='import';
 2007:                 }
 2008:                 $index++;
 2009:             }
 2010:         }
 2011:     }
 2012:     &setformulas($safeeval,%f);
 2013:     &setconstants($safeeval,%c);
 2014:     $r->print('<script>popwin.close()</script>');
 2015:     $r->rflush(); 
 2016: }
 2017: 
 2018: # ------------------------------------------------ Load data for one assessment
 2019: #
 2020: sub loadassessment {
 2021:     my ($safeeval,$sheetdata)=@_;
 2022: 
 2023:     my $uhome = $sheetdata->{'uhome'};
 2024:     my $uname = $sheetdata->{'uname'};
 2025:     my $udom  = $sheetdata->{'udom'};
 2026:     my $symb  = $sheetdata->{'usymb'};
 2027:     my $cid   = $sheetdata->{'cid'};
 2028:     my $cnum  = $sheetdata->{'cnum'};
 2029:     my $cdom  = $sheetdata->{'cdom'};
 2030:     my $chome = $sheetdata->{'chome'};
 2031: 
 2032:     my $namespace;
 2033:     unless ($namespace=$cid) { return ''; }
 2034:     # Get stored values
 2035:     my %returnhash=();
 2036:     if ($cachedassess eq $uname.':'.$udom) {
 2037:         #
 2038:         # get data out of the dumped stores
 2039:         # 
 2040:         my $version=$cachedstores{'version:'.$symb};
 2041:         my $scope;
 2042:         for ($scope=1;$scope<=$version;$scope++) {
 2043:             foreach (split(/\:/,$cachedstores{$scope.':keys:'.$symb})) {
 2044:                 $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
 2045:             } 
 2046:         }
 2047:     } else {
 2048:         #
 2049:         # restore individual
 2050:         #
 2051:         %returnhash = &Apache::lonnet::restore($symb,$namespace,$udom,$uname);
 2052:         for (my $version=1;$version<=$returnhash{'version'};$version++) {
 2053:             foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2054:                 $returnhash{$_}=$returnhash{$version.':'.$_};
 2055:             } 
 2056:         }
 2057:     }
 2058:     #
 2059:     # returnhash now has all stores for this resource
 2060:     # convert all "_" to "." to be able to use libraries, multiparts, etc
 2061:     #
 2062:     # This is dumb.  It is also necessary :(
 2063:     my @oldkeys=keys %returnhash;
 2064:     #
 2065:     foreach (@oldkeys) {
 2066:         my $name=$_;
 2067:         my $value=$returnhash{$_};
 2068:         delete $returnhash{$_};
 2069:         $name=~s/\_/\./g;
 2070:         $returnhash{$name}=$value;
 2071:     }
 2072:     # initialize coursedata and userdata for this user
 2073:     undef %courseopt;
 2074:     undef %useropt;
 2075: 
 2076:     my $userprefix=$uname.'_'.$udom.'_';
 2077:     
 2078:     unless ($uhome eq 'no_host') { 
 2079:         # Get coursedata
 2080:         unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
 2081:             my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
 2082:                                              ':resourcedata',$chome);
 2083:             if ($reply!~/^error\:/) {
 2084:                 $courserdatas{$cid}=$reply;
 2085:                 $courserdatas{$cid.'.last_cache'}=time;
 2086:             }
 2087:         }
 2088:         foreach (split(/\&/,$courserdatas{$cid})) {
 2089:             my ($name,$value)=split(/\=/,$_);
 2090:             $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
 2091:                 &Apache::lonnet::unescape($value);  
 2092:         }
 2093:         # Get userdata (if present)
 2094:         unless ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
 2095:             my $reply=
 2096:                 &Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
 2097:             if ($reply!~/^error\:/) {
 2098:                 $userrdatas{$uname.'___'.$udom}=$reply;
 2099:             }
 2100:             # Most of the time the user does not have a 'resourcedata.db' 
 2101:             # file.  We need to cache that we got nothing instead of bothering
 2102:             # with requesting it every time.
 2103:             $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
 2104:         }
 2105:         foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
 2106:             my ($name,$value)=split(/\=/,$_);
 2107:             $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
 2108:                 &Apache::lonnet::unescape($value);
 2109:         }
 2110:     }
 2111:     # now courseopt, useropt initialized for this user and course
 2112:     # (used by parmval)
 2113:     #
 2114:     # Load keys for this assessment only
 2115:     #
 2116:     my %thisassess=();
 2117:     my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
 2118:     foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
 2119:         $thisassess{$_}=1;
 2120:     } 
 2121:     #
 2122:     # Load parameters
 2123:     #
 2124:     my %c=();
 2125:     if (tie(%parmhash,'GDBM_File',
 2126:             &getcoursefilename($safeeval).'_parms.db',&GDBM_READER(),0640)) {
 2127:         my %f=&getformulas($safeeval);
 2128:         foreach (keys(%f))  {
 2129:             next if ($_!~/^A/);
 2130:             next if  ($f{$_}=~/^[\!\~\-]/);
 2131:             if ($f{$_}=~/^parameter/) {
 2132:                 if ($thisassess{$f{$_}}) {
 2133:                     my $val=&parmval($f{$_},$safeeval,$sheetdata);
 2134:                     $c{$_}=$val;
 2135:                     $c{$f{$_}}=$val;
 2136:                 }
 2137:             } else {
 2138:                 my $key=$f{$_};
 2139:                 my $ckey=$key;
 2140:                 $key=~s/^stores\_/resource\./;
 2141:                 $key=~s/\_/\./g;
 2142:                 $c{$_}=$returnhash{$key};
 2143:                 $c{$ckey}=$returnhash{$key};
 2144:             }
 2145:         }
 2146:         untie(%parmhash);
 2147:     }
 2148:     &setconstants($safeeval,%c);
 2149: }
 2150: 
 2151: # --------------------------------------------------------- Various form fields
 2152: 
 2153: sub textfield {
 2154:     my ($title,$name,$value)=@_;
 2155:     return "\n<p><b>$title:</b><br>".
 2156:         '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
 2157: }
 2158: 
 2159: sub hiddenfield {
 2160:     my ($name,$value)=@_;
 2161:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
 2162: }
 2163: 
 2164: sub selectbox {
 2165:     my ($title,$name,$value,%options)=@_;
 2166:     my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
 2167:     foreach (sort keys(%options)) {
 2168:         $selout.='<option value="'.$_.'"';
 2169:         if ($_ eq $value) { $selout.=' selected'; }
 2170:         $selout.='>'.$options{$_}.'</option>';
 2171:     }
 2172:     return $selout.'</select>';
 2173: }
 2174: 
 2175: # =============================================== Update information in a sheet
 2176: #
 2177: # Add new users or assessments, etc.
 2178: #
 2179: 
 2180: sub updatesheet {
 2181:     my ($safeeval,$sheetdata)=@_;
 2182:     my $stype=$sheetdata->{'sheettype'};
 2183:     if ($stype eq 'classcalc') {
 2184: 	return &updateclasssheet($safeeval,$sheetdata);
 2185:     } else {
 2186:         return &updatestudentassesssheet($safeeval,$sheetdata);
 2187:     }
 2188: }
 2189: 
 2190: # =================================================== Load the rows for a sheet
 2191: #
 2192: # Import the data for rows
 2193: #
 2194: 
 2195: sub loadrows {
 2196:     my ($safeeval,$sheetdata,$r)=@_;
 2197:     my $stype=$sheetdata->{'sheettype'};
 2198:     if ($stype eq 'classcalc') {
 2199: 	&loadcourse($safeeval,$sheetdata,$r);
 2200:     } elsif ($stype eq 'studentcalc') {
 2201:         &loadstudent($safeeval,$sheetdata);
 2202:     } else {
 2203:         &loadassessment($safeeval,$sheetdata);
 2204:     }
 2205: }
 2206: 
 2207: # ======================================================= Forced recalculation?
 2208: 
 2209: sub checkthis {
 2210:     my ($keyname,$time)=@_;
 2211:     return ($time<$expiredates{$keyname});
 2212: }
 2213: 
 2214: sub forcedrecalc {
 2215:     my ($uname,$udom,$stype,$usymb)=@_;
 2216:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2217:     my $time=$oldsheets{$key.'.time'};
 2218:     if ($ENV{'form.forcerecalc'}) { return 1; }
 2219:     unless ($time) { return 1; }
 2220:     if ($stype eq 'assesscalc') {
 2221:         my $map=(split(/\_\_\_/,$usymb))[0];
 2222:         if (&checkthis('::assesscalc:',$time) ||
 2223:             &checkthis('::assesscalc:'.$map,$time) ||
 2224:             &checkthis('::assesscalc:'.$usymb,$time) ||
 2225:             &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
 2226:             &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
 2227:             &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
 2228:             return 1;
 2229:         } 
 2230:     } else {
 2231:         if (&checkthis('::studentcalc:',$time) || 
 2232:             &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
 2233: 	    return 1;
 2234:         }
 2235:     }
 2236:     return 0; 
 2237: }
 2238: 
 2239: # ============================================================== Export handler
 2240: #
 2241: # Non-interactive call from with program
 2242: #
 2243: 
 2244: sub exportsheet {
 2245:     my ($uname,$udom,$stype,$usymb,$fn)=@_;
 2246:     my @exportarr=();
 2247:     if (($usymb=~/^\_(\w+)/) && (!$fn)) {
 2248:         $fn='default_'.$1;
 2249:     }
 2250:     #
 2251:     # Check if cached
 2252:     #
 2253:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2254:     my $found='';
 2255:     if ($oldsheets{$key}) {
 2256:         foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
 2257:             my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 2258:             if ($name eq $fn) {
 2259:                 $found=$value;
 2260:             }
 2261:         }
 2262:     }
 2263:     unless ($found) {
 2264:         &cachedssheets($uname,$udom,&Apache::lonnet::homeserver($uname,$udom));
 2265:         if ($oldsheets{$key}) {
 2266:             foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
 2267:                 my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 2268:                 if ($name eq $fn) {
 2269:                     $found=$value;
 2270:                 }
 2271:             } 
 2272:         }
 2273:     }
 2274:     #
 2275:     # Check if still valid
 2276:     #
 2277:     if ($found) {
 2278:         if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
 2279:             $found='';
 2280:         }
 2281:     }
 2282:     if ($found) {
 2283:         #
 2284:         # Return what was cached
 2285:         #
 2286:         @exportarr=split(/\_\_\_\;\_\_\_/,$found);
 2287:     } else {
 2288:         #
 2289:         # Not cached
 2290:         #        
 2291:         my ($thissheet,$sheetdata)=&makenewsheet($uname,$udom,$stype,$usymb);
 2292:         &readsheet($thissheet,$sheetdata,$fn);
 2293:         &updatesheet($thissheet,$sheetdata);
 2294:         &loadrows($thissheet,$sheetdata);
 2295:         &calcsheet($thissheet,$sheetdata); 
 2296:         @exportarr=&exportdata($thissheet,$sheetdata);
 2297:         #
 2298:         # Store now
 2299:         #
 2300:         my $cid=$ENV{'request.course.id'}; 
 2301:         my $current='';
 2302:         if ($stype eq 'studentcalc') {
 2303:             $current=&Apache::lonnet::reply('get:'.
 2304:                                             $ENV{'course.'.$cid.'.domain'}.':'.
 2305:                                             $ENV{'course.'.$cid.'.num'}.
 2306:                                             ':nohist_calculatedsheets:'.
 2307:                                             &Apache::lonnet::escape($key),
 2308:                                             $ENV{'course.'.$cid.'.home'});
 2309:         } else {
 2310:             $current=&Apache::lonnet::reply('get:'.$sheetdata->{'udom'}.':'.
 2311:                                             $sheetdata->{'uname'}.
 2312:                                             ':nohist_calculatedsheets_'.
 2313:                                             $ENV{'request.course.id'}.':'.
 2314:                                             &Apache::lonnet::escape($key),
 2315:                                             $sheetdata->{'uhome'});
 2316:         }
 2317:         my %currentlystored=();
 2318:         unless ($current=~/^error\:/) {
 2319:             foreach (split(/___&\___/,&Apache::lonnet::unescape($current))) {
 2320:                 my ($name,$value)=split(/___=___/,$_);
 2321:                 $currentlystored{$name}=$value;
 2322:             }
 2323:         }
 2324:         $currentlystored{$fn}=join('___;___',@exportarr);
 2325:         #
 2326:         my $newstore='';
 2327:         foreach (keys(%currentlystored)) {
 2328:             if ($newstore) { $newstore.='___&___'; }
 2329:             $newstore.=$_.'___=___'.$currentlystored{$_};
 2330:         }
 2331:         my $now=time;
 2332:         if ($stype eq 'studentcalc') {
 2333:             &Apache::lonnet::reply('put:'.
 2334:                                    $ENV{'course.'.$cid.'.domain'}.':'.
 2335:                                    $ENV{'course.'.$cid.'.num'}.
 2336:                                    ':nohist_calculatedsheets:'.
 2337:                                    &Apache::lonnet::escape($key).'='.
 2338:                                    &Apache::lonnet::escape($newstore).'&'.
 2339:                                    &Apache::lonnet::escape($key).'.time='.$now,
 2340:                                    $ENV{'course.'.$cid.'.home'});
 2341:         } else {
 2342:             &Apache::lonnet::reply('put:'.
 2343:                                    $sheetdata->{'udom'}.':'.
 2344:                                    $sheetdata->{'uname'}.
 2345:                                    ':nohist_calculatedsheets_'.
 2346:                                    $ENV{'request.course.id'}.':'.
 2347:                                    &Apache::lonnet::escape($key).'='.
 2348:                                    &Apache::lonnet::escape($newstore).'&'.
 2349:                                    &Apache::lonnet::escape($key).'.time='.$now,
 2350:                                    $sheetdata->{'uhome'});
 2351:         }
 2352:     }
 2353:     return @exportarr;
 2354: }
 2355: 
 2356: # ============================================================ Expiration Dates
 2357: #
 2358: # Load previously cached student spreadsheets for this course
 2359: #
 2360: sub expirationdates {
 2361:     undef %expiredates;
 2362:     my $cid=$ENV{'request.course.id'};
 2363:     my $reply=&Apache::lonnet::reply('dump:'.
 2364: 				     $ENV{'course.'.$cid.'.domain'}.':'.
 2365:                                      $ENV{'course.'.$cid.'.num'}.
 2366: 				     ':nohist_expirationdates',
 2367:                                      $ENV{'course.'.$cid.'.home'});
 2368:     unless ($reply=~/^error\:/) {
 2369: 	foreach (split(/\&/,$reply)) {
 2370:             my ($name,$value)=split(/\=/,$_);
 2371:             $expiredates{&Apache::lonnet::unescape($name)}
 2372:                         =&Apache::lonnet::unescape($value);
 2373:         }
 2374:     }
 2375: }
 2376: 
 2377: # ===================================================== Calculated sheets cache
 2378: #
 2379: # Load previously cached student spreadsheets for this course
 2380: #
 2381: 
 2382: sub cachedcsheets {
 2383:     my $cid=$ENV{'request.course.id'};
 2384:     my $reply=&Apache::lonnet::reply('dump:'.
 2385: 				     $ENV{'course.'.$cid.'.domain'}.':'.
 2386:                                      $ENV{'course.'.$cid.'.num'}.
 2387: 				     ':nohist_calculatedsheets',
 2388:                                      $ENV{'course.'.$cid.'.home'});
 2389:     unless ($reply=~/^error\:/) {
 2390: 	foreach ( split(/\&/,$reply)) {
 2391:             my ($name,$value)=split(/\=/,$_);
 2392:             $oldsheets{&Apache::lonnet::unescape($name)}
 2393:                       =&Apache::lonnet::unescape($value);
 2394:         }
 2395:     }
 2396: }
 2397: 
 2398: # ===================================================== Calculated sheets cache
 2399: #
 2400: # Load previously cached assessment spreadsheets for this student
 2401: #
 2402: 
 2403: sub cachedssheets {
 2404:   my ($sname,$sdom,$shome)=@_;
 2405:   unless (($loadedcaches{$sname.'_'.$sdom}) || ($shome eq 'no_host')) {
 2406:     my $cid=$ENV{'request.course.id'};
 2407:     my $reply=&Apache::lonnet::reply('dump:'.$sdom.':'.$sname.
 2408: 			             ':nohist_calculatedsheets_'.
 2409:                                       $ENV{'request.course.id'},
 2410:                                      $shome);
 2411:     unless ($reply=~/^error\:/) {
 2412: 	foreach ( split(/\&/,$reply)) {
 2413:             my ($name,$value)=split(/\=/,$_);
 2414:             $oldsheets{&Apache::lonnet::unescape($name)}
 2415:                       =&Apache::lonnet::unescape($value);
 2416:         }
 2417:     }
 2418:     $loadedcaches{$sname.'_'.$sdom}=1;
 2419:   }
 2420: }
 2421: 
 2422: # ===================================================== Calculated sheets cache
 2423: #
 2424: # Load previously cached assessment spreadsheets for this student
 2425: #
 2426: 
 2427: # ================================================================ Main handler
 2428: #
 2429: # Interactive call to screen
 2430: #
 2431: #
 2432: sub handler {
 2433:     my $r=shift;
 2434: 
 2435:     my $loaderror=&Apache::lonnet::overloaderror($r);
 2436:     if ($loaderror) { return $loaderror; }
 2437:     $loaderror= &Apache::lonnet::overloaderror($r,
 2438:                       $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
 2439:     if ($loaderror) { return $loaderror; } 
 2440: 
 2441:     if ($r->header_only) {
 2442:         $r->content_type('text/html');
 2443:         $r->send_http_header;
 2444:         return OK;
 2445:     }
 2446:     # Global directory configs
 2447:     $includedir = $r->dir_config('lonIncludes');
 2448:     $tmpdir = $r->dir_config('lonDaemons').'/tmp/';
 2449:     # Needs to be in a course
 2450:     if (! $ENV{'request.course.fn'}) { 
 2451:         # Not in a course, or not allowed to modify parms
 2452:         $ENV{'user.error.msg'}=
 2453:             $r->uri.":opa:0:0:Cannot modify spreadsheet";
 2454:         return HTTP_NOT_ACCEPTABLE; 
 2455:     }
 2456:     # Get query string for limited number of parameters
 2457:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 2458:                                             ['uname','udom','usymb','ufn']);
 2459:     if ($ENV{'request.role'} =~ /^st\./) {
 2460:         delete $ENV{'form.unewfield'}   if (exists($ENV{'form.unewfield'}));
 2461:         delete $ENV{'form.unewformula'} if (exists($ENV{'form.unewformula'}));
 2462:     }
 2463:     if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'})) {
 2464:         $ENV{'form.ufn'}='default_'.$1;
 2465:     }
 2466:     # Interactive loading of specific sheet?
 2467:     if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
 2468:         $ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
 2469:     }
 2470:     #
 2471:     # Determine the user name and domain for the sheet.
 2472:     my $aname;
 2473:     my $adom;
 2474:     unless ($ENV{'form.uname'}) {
 2475:         $aname=$ENV{'user.name'};
 2476:         $adom=$ENV{'user.domain'};
 2477:     } else {
 2478:         $aname=$ENV{'form.uname'};
 2479:         $adom=$ENV{'form.udom'};
 2480:     }
 2481:     #
 2482:     # Open page
 2483:     $r->content_type('text/html');
 2484:     $r->header_out('Cache-control','no-cache');
 2485:     $r->header_out('Pragma','no-cache');
 2486:     $r->send_http_header;
 2487:     # Screen output
 2488:     $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
 2489:     if ($ENV{'request.role'} !~ /^st\./) {
 2490:         $r->print(<<ENDSCRIPT);
 2491: <script language="JavaScript">
 2492: 
 2493:     function celledit(cn,cf) {
 2494:         var cnf=prompt(cn,cf);
 2495:         if (cnf!=null) {
 2496:             document.sheet.unewfield.value=cn;
 2497:             document.sheet.unewformula.value=cnf;
 2498:             document.sheet.submit();
 2499:         }
 2500:     }
 2501: 
 2502:     function changesheet(cn) {
 2503: 	document.sheet.unewfield.value=cn;
 2504:         document.sheet.unewformula.value='changesheet';
 2505:         document.sheet.submit();
 2506:     }
 2507: 
 2508:     function insertrow(cn) {
 2509: 	document.sheet.unewfield.value='insertrow';
 2510:         document.sheet.unewformula.value=cn;
 2511:         document.sheet.submit();
 2512:     }
 2513: 
 2514: </script>
 2515: ENDSCRIPT
 2516:     }
 2517:     $r->print('</head>'.&Apache::loncommon::bodytag('Grades Spreadsheet').
 2518:               '<form action="'.$r->uri.'" name=sheet method=post>');
 2519:     $r->print(&hiddenfield('uname',$ENV{'form.uname'}).
 2520:               &hiddenfield('udom',$ENV{'form.udom'}).
 2521:               &hiddenfield('usymb',$ENV{'form.usymb'}).
 2522:               &hiddenfield('unewfield','').
 2523:               &hiddenfield('unewformula',''));
 2524:     $r->rflush();
 2525:     #
 2526:     # Full recalc?
 2527:     if ($ENV{'form.forcerecalc'}) {
 2528:         $r->print('<h4>Completely Recalculating Sheet ...</h4>');
 2529:         undef %spreadsheets;
 2530:         undef %courserdatas;
 2531:         undef %userrdatas;
 2532:         undef %defaultsheets;
 2533:         undef %updatedata;
 2534:     }
 2535:     # Read new sheet or modified worksheet
 2536:     $r->uri=~/\/(\w+)$/;
 2537:     my ($asheet,$asheetdata)=&makenewsheet($aname,$adom,$1,$ENV{'form.usymb'});
 2538:     #
 2539:     # If a new formula had been entered, go from work copy
 2540:     if ($ENV{'form.unewfield'}) {
 2541:         $r->print('<h2>Modified Workcopy</h2>');
 2542:         $ENV{'form.unewformula'}=~s/\'/\"/g;
 2543:         $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
 2544:                   $ENV{'form.unewformula'}.'<p>');
 2545:         &setfilename($asheet,$ENV{'form.ufn'});
 2546:         &tmpread($asheet,$ENV{'form.unewfield'},$ENV{'form.unewformula'});
 2547:     } elsif ($ENV{'form.saveas'}) {
 2548:         &setfilename($asheet,$ENV{'form.ufn'});
 2549:         &tmpread($asheet);
 2550:     } else {
 2551:         &readsheet($asheet,$asheetdata,$ENV{'form.ufn'});
 2552:     }
 2553:     # Print out user information
 2554:     unless ($asheetdata->{'sheettype'} eq 'classcalc') {
 2555:         $r->print('<p><b>User:</b> '.$asheetdata->{'uname'}.
 2556:                   '<br><b>Domain:</b> '.$asheetdata->{'udom'});
 2557: #        if (&getcsec($asheet) eq '-1') {
 2558: #            $r->print('<h3><font color=red>'.
 2559: #                      'Not a student in this course</font></h3>');
 2560: #        } else {
 2561:             $r->print('<br><b>Section/Group:</b> '.$asheetdata->{'csec'});
 2562: #        }
 2563:         if ($ENV{'form.usymb'}) {
 2564:             $r->print('<br><b>Assessment:</b> <tt>'.
 2565:                       $ENV{'form.usymb'}.'</tt>');
 2566:         }
 2567:     }
 2568:     #
 2569:     # Check user permissions
 2570:     if (($asheetdata->{'sheettype'} eq 'classcalc'       ) || 
 2571:         ($asheetdata->{'uname'}     ne $ENV{'user.name'} ) ||
 2572:         ($asheetdata->{'udom'}      ne $ENV{'user.domain'})) {
 2573:         unless (&Apache::lonnet::allowed('vgr',$asheetdata->{'cid'})) {
 2574:             $r->print('<h1>Access Permission Denied</h1>'.
 2575:                       '</form></body></html>');
 2576:             return OK;
 2577:         }
 2578:     }
 2579:     # Additional options
 2580:     $r->print('<br />'.
 2581:               '<input type="submit" name="forcerecalc" '.
 2582:               'value="Completely Recalculate Sheet"><p>');
 2583:     if ($asheetdata->{'sheettype'} eq 'assesscalc') {
 2584:         $r->print('<p><font size=+2>'.
 2585:                   '<a href="/adm/studentcalc?'.
 2586:                   'uname='.$asheetdata->{'uname'}.
 2587:                   '&udom='.$asheetdata->{'udom'}.'">'.
 2588:                   'Level up: Student Sheet</a></font><p>');
 2589:     }
 2590:     if (($asheetdata->{'sheettype'} eq 'studentcalc') && 
 2591:         (&Apache::lonnet::allowed('vgr',$asheetdata->{'cid'}))) {
 2592:         $r->print ('<p><font size=+2><a href="/adm/classcalc">'.
 2593:                    'Level up: Course Sheet</a></font><p>');
 2594:     }
 2595:     # Save dialog
 2596:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2597:         my $fname=$ENV{'form.ufn'};
 2598:         $fname=~s/\_[^\_]+$//;
 2599:         if ($fname eq 'default') { $fname='course_default'; }
 2600:         $r->print('<input type=submit name=saveas value="Save as ...">'.
 2601:                   '<input type=text size=20 name=newfn value="'.$fname.'">'.
 2602:                   'make default: <input type=checkbox name="makedefufn"><p>');
 2603:     }
 2604:     $r->print(&hiddenfield('ufn',&getfilename($asheet)));
 2605:     # Load dialog
 2606:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2607:         $r->print('<p><input type=submit name=load value="Load ...">'.
 2608:                   '<select name="loadthissheet">'.
 2609:                   '<option name="default">Default</option>');
 2610:         foreach (&othersheets($asheet,$asheetdata->{'sheettype'})) {
 2611:             $r->print('<option name="'.$_.'"');
 2612:             if ($ENV{'form.ufn'} eq $_) {
 2613:                 $r->print(' selected');
 2614:             }
 2615:             $r->print('>'.$_.'</option>');
 2616:         } 
 2617:         $r->print('</select><p>');
 2618:         if ($asheetdata->{'sheettype'} eq 'studentcalc') {
 2619:             &setothersheets($asheet,&othersheets($asheet,'assesscalc'));
 2620:         }
 2621:     }
 2622:     # Cached sheets
 2623:     &expirationdates();
 2624:     undef %oldsheets;
 2625:     undef %loadedcaches;
 2626:     if ($asheetdata->{'sheettype'} eq 'classcalc') {
 2627:         $r->print("Loading previously calculated student sheets ...\n");
 2628:         $r->rflush();
 2629:         &cachedcsheets();
 2630:     } elsif ($asheetdata->{'sheettype'} eq 'studentcalc') {
 2631:         $r->print("Loading previously calculated assessment sheets ...\n");
 2632:         $r->rflush();
 2633:         &cachedssheets($asheetdata->{'uname'},$asheetdata->{'udom'},
 2634:                        $asheetdata->{'uhome'});
 2635:     }
 2636:     # Update sheet, load rows
 2637:     $r->print("Loaded sheet(s), updating rows ...<br>\n");
 2638:     $r->rflush();
 2639:     #
 2640:     &updatesheet($asheet,$asheetdata);
 2641:     $r->print("Updated rows, loading row data ...\n");
 2642:     $r->rflush();
 2643:     #
 2644:     &loadrows($asheet,$asheetdata,$r);
 2645:     $r->print("Loaded row data, calculating sheet ...<br>\n");
 2646:     $r->rflush();
 2647:     #
 2648:     my $calcoutput=&calcsheet($asheet);
 2649:     $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
 2650:     # See if something to save
 2651:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2652:         my $fname='';
 2653:         if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
 2654:             $fname=~s/\W/\_/g;
 2655:             if ($fname eq 'default') { $fname='course_default'; }
 2656:             $fname.='_'.$asheetdata->{'sheettype'};
 2657:             &setfilename($asheet,$fname);
 2658:             $ENV{'form.ufn'}=$fname;
 2659:             $r->print('<p>Saving spreadsheet: '.
 2660:                       &writesheet($asheet,$ENV{'form.makedefufn'}).'<p>');
 2661:         }
 2662:     }
 2663:     #
 2664:     #Write the modified worksheet
 2665:     $r->print('<b>Current sheet:</b> '.&getfilename($asheet).'<p>');
 2666:     &tmpwrite($asheet);
 2667:     if ($asheetdata->{'sheettype'} eq 'studentcalc') {
 2668:         $r->print('<br>Show rows with empty A column: ');
 2669:     } else {
 2670:         $r->print('<br>Show empty rows: ');
 2671:     } 
 2672:     #
 2673:     $r->print(&hiddenfield('userselhidden','true').
 2674:               '<input type="checkbox" name="showall" onClick="submit()"');
 2675:     #
 2676:     if ($ENV{'form.showall'}) { 
 2677:         $r->print(' checked'); 
 2678:     } else {
 2679:         unless ($ENV{'form.userselhidden'}) {
 2680:             unless 
 2681:                 ($ENV{'course.'.$ENV{'request.course.id'}.'.hideemptyrows'} eq 'yes') {
 2682:                     $r->print(' checked');
 2683:                     $ENV{'form.showall'}=1;
 2684:                 }
 2685:         }
 2686:     }
 2687:     $r->print('>');
 2688:     #
 2689:     # CSV format checkbox (classcalc sheets only)
 2690:     if ($asheetdata->{'sheettype'} eq 'classcalc') {
 2691:         $r->print(' Output CSV format: <input type="checkbox" '.
 2692:                   'name="showcsv" onClick="submit()"');
 2693:         if ($ENV{'form.showcsv'}) { $r->print(' checked'); }
 2694:         $r->print('>');
 2695:     }
 2696:     #
 2697:     # Buttons to insert rows
 2698:     $r->print('&nbsp;Student Status: '.
 2699:               &Apache::lonhtmlcommon::StatusOptions
 2700:               ($ENV{'form.Status'},'sheet'));
 2701:     $r->print(<<ENDINSERTBUTTONS);
 2702: <br>
 2703: <input type='button' onClick='insertrow("top");' 
 2704: value='Insert Row Top'>
 2705: <input type='button' onClick='insertrow("bottom");' 
 2706: value='Insert Row Bottom'><br>
 2707: ENDINSERTBUTTONS
 2708:     # Print out sheet
 2709:     &outsheet($r,$asheet,$asheetdata);
 2710:     $r->print('</form></body></html>');
 2711:     #  Done
 2712:     return OK;
 2713: }
 2714: 
 2715: 1;
 2716: __END__
 2717: 
 2718: 
 2719: 
 2720: 

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