File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.127: download - view: text, annotated - select for diffs
Thu Oct 24 15:34:10 2002 UTC (21 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Fixed bug in csv output of parameters (assessment sheet) which caused every
parameter to have the name '1'.  Someone might have complained....

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

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