File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.132: download - view: text, annotated - select for diffs
Mon Nov 4 22:35:45 2002 UTC (21 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Major changes:
Outputting of the spreadsheet is beginning to be broken up into smaller
pieces.  HTML output works as best as I can test it.  The function
&outsheet was added to handle the calling of the proper output function for
the requested target.  Currently &outsheet_html is the only implemented option.
*** This means CSV output is broken in this commit ***  If this affects you,
you are me.
The function &rown has been removed and given a respectful burial.
&getrow was reworked to call &templaterow, &outrowassess, and &outrow.
Each of the functions &templaterow, &outrowassess, and &outrow have been
modified to return a row label (colon seperated string) and an array of
hash pointers which describe the cells (name,formula, and value).
Sorting of the rows of the spreadsheet has been moved to &sort_indicies.
&format_rowlabel was modified to deal with 'template' and 'export' rows
without incident.

Some debugging code has been added (and commented out).

Bug Fix: &mask had an error introduced in it during a minor change -
doing

($v1,$v2)=($f=~/(regexpA)(regexpB)/);
($v3,$v4)=($g=~/(regexpA)(regexpB)/);

is not the same as doing:

$f=~/(regexpA)(regexpB)/;
($v1,$v2)=($1,$2);
$g=~/(regexpA)(regexpB)/;
($v3,$v4)=($1,$2);

Because in the second case if $g is undefined its pattern match does not
occur and the variables $1 and $2 retain their values from the pattern match
on $f.  Perl is rather devious at times....

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

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