File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.97: download - view: text, annotated - select for diffs
Mon Jul 15 12:26:51 2002 UTC (21 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #507
Allows to insert extra lines on top and bottom of spreadsheet.

Internally marked "---n" and "~~~n".

Will always open up columns B-Z for calculations (changes to sett).

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

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