File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.131: download - view: text, annotated - select for diffs
Wed Oct 30 15:07:20 2002 UTC (21 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Changes to &exportsheet and &writesheet.
    Changed calls to lonnet::reply to lonnet::get and lonnet::put.
    Fixed a bug introduced in r 1.120 (not distributed to users) which
    passed a course id as a domain.

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

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