File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.160.2.4: download - view: text, annotated - select for diffs
Wed Mar 19 17:16:23 2003 UTC (21 years, 3 months ago) by matthew
Branches: version_0_6
CVS tags: version_0_6_2
Diff to branchpoint 1.160: preferred, unified
Fix two bugs - Bug 1321 (multipart problems don't work with default assess
spreadsheet) and a bug which caused the incorrect spreadsheet to be loaded
at the student level.

    1: #
    2: # $Id: lonspreadsheet.pm,v 1.160.2.4 2003/03/19 17:16:23 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 Apache::Constants qw(:common :http);
   57: use Apache::lonnet;
   58: use Apache::lonhtmlcommon;
   59: use Apache::loncoursedata;
   60: use Apache::File();
   61: use Safe;
   62: use Safe::Hole;
   63: use Opcode;
   64: use GDBM_File;
   65: use HTML::Entities();
   66: use HTML::TokeParser;
   67: use Spreadsheet::WriteExcel;
   68: 
   69: #
   70: # Caches for coursewide information 
   71: #
   72: my %Section;
   73: 
   74: #
   75: # Caches for previously calculated spreadsheets
   76: #
   77: 
   78: my %oldsheets;
   79: my %loadedcaches;
   80: my %expiredates;
   81: 
   82: #
   83: # Cache for stores of an individual user
   84: #
   85: 
   86: my $cachedassess;
   87: my %cachedstores;
   88: 
   89: #
   90: # These cache hashes need to be independent of user, resource and course
   91: # (user and course can/should be in the keys)
   92: #
   93: 
   94: my %spreadsheets;
   95: my %courserdatas;
   96: my %userrdatas;
   97: my %defaultsheets;
   98: my %rowlabel_cache;
   99: 
  100: #
  101: # These global hashes are dependent on user, course and resource, 
  102: # and need to be initialized every time when a sheet is calculated
  103: #
  104: my %courseopt;
  105: my %useropt;
  106: my %parmhash;
  107: 
  108: #
  109: # Some hashes for stats on timing and performance
  110: #
  111: 
  112: my %starttimes;
  113: my %usedtimes;
  114: my %numbertimes;
  115: 
  116: # Stuff that only the screen handler can know
  117: 
  118: my $includedir;
  119: my $tmpdir;
  120: 
  121: # =============================================================================
  122: # ===================================== Implements an instance of a spreadsheet
  123: 
  124: ##
  125: ## mask - used to reside in the safe space.  
  126: ##
  127: sub mask {
  128:     my ($lower,$upper)=@_;
  129:     $upper = $lower if (! defined($upper));
  130:     #
  131:     my ($la,$ld) = ($lower=~/([A-Za-z]|\*)(\d+|\*)/);
  132:     my ($ua,$ud) = ($upper=~/([A-Za-z]|\*)(\d+|\*)/);
  133:     #
  134:     my $alpha='';
  135:     my $num='';
  136:     #
  137:     if (($la eq '*') || ($ua eq '*')) {
  138:         $alpha='[A-Za-z]';
  139:     } else {
  140:        if (($la=~/[A-Z]/) && ($ua=~/[A-Z]/) ||
  141:            ($la=~/[a-z]/) && ($ua=~/[a-z]/)) {
  142:           $alpha='['.$la.'-'.$ua.']';
  143:        } else {
  144:           $alpha='['.$la.'-Za-'.$ua.']';
  145:        }
  146:     }   
  147:     if (($ld eq '*') || ($ud eq '*')) {
  148: 	$num='\d+';
  149:     } else {
  150:         if (length($ld)!=length($ud)) {
  151:            $num.='(';
  152: 	   foreach ($ld=~m/\d/g) {
  153:               $num.='['.$_.'-9]';
  154: 	   }
  155:            if (length($ud)-length($ld)>1) {
  156:               $num.='|\d{'.(length($ld)+1).','.(length($ud)-1).'}';
  157: 	   }
  158:            $num.='|';
  159:            foreach ($ud=~m/\d/g) {
  160:                $num.='[0-'.$_.']';
  161:            }
  162:            $num.=')';
  163:        } else {
  164:            my @lda=($ld=~m/\d/g);
  165:            my @uda=($ud=~m/\d/g);
  166:            my $i; 
  167:            my $j=0; 
  168:            my $notdone=1;
  169:            for ($i=0;($i<=$#lda)&&($notdone);$i++) {
  170:                if ($lda[$i]==$uda[$i]) {
  171: 		   $num.=$lda[$i];
  172:                    $j=$i;
  173:                } else {
  174:                    $notdone=0;
  175:                }
  176:            }
  177:            if ($j<$#lda-1) {
  178: 	       $num.='('.$lda[$j+1];
  179:                for ($i=$j+2;$i<=$#lda;$i++) {
  180:                    $num.='['.$lda[$i].'-9]';
  181:                }
  182:                if ($uda[$j+1]-$lda[$j+1]>1) {
  183: 		   $num.='|['.($lda[$j+1]+1).'-'.($uda[$j+1]-1).']\d{'.
  184:                    ($#lda-$j-1).'}';
  185:                }
  186: 	       $num.='|'.$uda[$j+1];
  187:                for ($i=$j+2;$i<=$#uda;$i++) {
  188:                    $num.='[0-'.$uda[$i].']';
  189:                }
  190:                $num.=')';
  191:            } else {
  192:                if ($lda[-1]!=$uda[-1]) {
  193:                   $num.='['.$lda[-1].'-'.$uda[-1].']';
  194: 	       }
  195:            }
  196:        }
  197:     }
  198:     return '^'.$alpha.$num."\$";
  199: }
  200: 
  201: sub initsheet {
  202:     my $safeeval = new Safe(shift);
  203:     my $safehole = new Safe::Hole;
  204:     $safeeval->permit("entereval");
  205:     $safeeval->permit(":base_math");
  206:     $safeeval->permit("sort");
  207:     $safeeval->deny(":base_io");
  208:     $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
  209:     $safehole->wrap(\&Apache::lonspreadsheet::mask,$safeeval,'&mask');
  210:     $safeeval->share('$@');
  211:     my $code=<<'ENDDEFS';
  212: # ---------------------------------------------------- Inside of the safe space
  213: 
  214: #
  215: # f: formulas
  216: # t: intermediate format (variable references expanded)
  217: # v: output values
  218: # c: preloaded constants (A-column)
  219: # rl: row label
  220: # os: other spreadsheets (for student spreadsheet only)
  221: 
  222: undef %sheet_values;   # Holds the (computed, final) values for the sheet
  223:     # This is only written to by &calc, the spreadsheet computation routine.
  224:     # It is read by many functions
  225: undef %t; # Holds the values of the spreadsheet temporarily. Set in &sett, 
  226:     # which does the translation of strings like C5 into the value in C5.
  227:     # Used in &calc - %t holds the values that are actually eval'd.
  228: undef %f;    # Holds the formulas for each cell.  This is the users
  229:     # (spreadsheet authors) data for each cell.
  230:     # set by &setformulas and returned by &getformulas
  231:     # &setformulas is called by &readsheet, &tmpread, &updateclasssheet,
  232:     # &updatestudentassesssheet, &loadstudent, &loadcourse
  233:     # &getformulas is called by &writesheet, &tmpwrite, &updateclasssheet,
  234:     # &updatestudentassesssheet, &loadstudent, &loadcourse, &loadassessment, 
  235: undef %c; # Holds the constants for a sheet.  In the assessment
  236:     # sheets, this is the A column.  Used in &MINPARM, &MAXPARM, &expandnamed,
  237:     # &sett, and &setconstants.  There is no &getconstants.
  238:     # &setconstants is called by &loadstudent, &loadcourse, &load assessment,
  239: undef @os;  # Holds the names of other spreadsheets - this is used to specify
  240:     # the spreadsheets that are available for the assessment sheet.
  241:     # Set by &setothersheets.  &setothersheets is called by &handler.  A
  242:     # related subroutine is &othersheets.
  243: #$errorlog = '';
  244: 
  245: $maxrow = 0;
  246: $sheettype = '';
  247: 
  248: # filename/reference of the sheet
  249: $filename = '';
  250: 
  251: # user data
  252: $uname = '';
  253: $uhome = '';
  254: $udom  = '';
  255: 
  256: # course data
  257: 
  258: $csec = '';
  259: $chome= '';
  260: $cnum = '';
  261: $cdom = '';
  262: $cid  = '';
  263: $coursefilename  = '';
  264: 
  265: # symb
  266: 
  267: $usymb = '';
  268: 
  269: # error messages
  270: $errormsg = '';
  271: 
  272: 
  273: #-------------------------------------------------------
  274: 
  275: =item UWCALC(hashname,modules,units,date) 
  276: 
  277: returns the proportion of the module 
  278: weights not previously completed by the student.
  279: 
  280: =over 4
  281: 
  282: =item hashname 
  283: 
  284: name of the hash the module dates have been inserted into
  285: 
  286: =item modules 
  287: 
  288: reference to a cell which contains a comma deliminated list of modules 
  289: covered by the assignment.
  290: 
  291: =item units 
  292: 
  293: reference to a cell which contains a comma deliminated list of module 
  294: weights with respect to the assignment
  295: 
  296: =item date 
  297: 
  298: reference to a cell which contains the date the assignment was completed.
  299: 
  300: =back 
  301: 
  302: =cut
  303: 
  304: #-------------------------------------------------------
  305: sub UWCALC {
  306:     my ($hashname,$modules,$units,$date) = @_;
  307:     my @Modules = split(/,/,$modules);
  308:     my @Units   = split(/,/,$units);
  309:     my $total_weight;
  310:     foreach (@Units) {
  311: 	$total_weight += $_;
  312:     }
  313:     my $usum=0;
  314:     for (my $i=0; $i<=$#Modules; $i++) {
  315: 	if (&HASH($hashname,$Modules[$i]) eq $date) {
  316: 	    $usum += $Units[$i];
  317: 	}
  318:     }
  319:     return $usum/$total_weight;
  320: }
  321: 
  322: #-------------------------------------------------------
  323: 
  324: =item CDLSUM(list) 
  325: 
  326: returns the sum of the elements in a cell which contains
  327: a Comma Deliminate List of numerical values.
  328: 'list' is a reference to a cell which contains a comma deliminated list.
  329: 
  330: =cut
  331: 
  332: #-------------------------------------------------------
  333: sub CDLSUM {
  334:     my ($list)=@_;
  335:     my $sum;
  336:     foreach (split/,/,$list) {
  337: 	$sum += $_;
  338:     }
  339:     return $sum;
  340: }
  341: 
  342: #-------------------------------------------------------
  343: 
  344: =item CDLITEM(list,index) 
  345: 
  346: returns the item at 'index' in a Comma Deliminated List.
  347: 
  348: =over 4
  349: 
  350: =item list
  351: 
  352: reference to a cell which contains a comma deliminated list.
  353: 
  354: =item index 
  355: 
  356: the Perl index of the item requested (first element in list has
  357: an index of 0) 
  358: 
  359: =back
  360: 
  361: =cut
  362: 
  363: #-------------------------------------------------------
  364: sub CDLITEM {
  365:     my ($list,$index)=@_;
  366:     my @Temp = split/,/,$list;
  367:     return $Temp[$index];
  368: }
  369: 
  370: #-------------------------------------------------------
  371: 
  372: =item CDLHASH(name,key,value) 
  373: 
  374: loads a comma deliminated list of keys into
  375: the hash 'name', all with a value of 'value'.
  376: 
  377: =over 4
  378: 
  379: =item name  
  380: 
  381: name of the hash.
  382: 
  383: =item key
  384: 
  385: (a pointer to) a comma deliminated list of keys.
  386: 
  387: =item value
  388: 
  389: a single value to be entered for each key.
  390: 
  391: =back
  392: 
  393: =cut
  394: 
  395: #-------------------------------------------------------
  396: sub CDLHASH {
  397:     my ($name,$key,$value)=@_;
  398:     my @Keys;
  399:     my @Values;
  400:     # Check to see if we have multiple $key values
  401:     if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
  402: 	my $keymask = &mask($key);
  403: 	# Assume the keys are addresses
  404: 	my @Temp = grep /$keymask/,keys(%sheet_values);
  405: 	@Keys = $sheet_values{@Temp};
  406:     } else {
  407: 	$Keys[0]= $key;
  408:     }
  409:     my @Temp;
  410:     foreach $key (@Keys) {
  411: 	@Temp = (@Temp, split/,/,$key);
  412:     }
  413:     @Keys = @Temp;
  414:     if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
  415: 	my $valmask = &mask($value);
  416: 	my @Temp = grep /$valmask/,keys(%sheet_values);
  417: 	@Values =$sheet_values{@Temp};
  418:     } else {
  419: 	$Values[0]= $value;
  420:     }
  421:     $value = $Values[0];
  422:     # Add values to hash
  423:     for (my $i = 0; $i<=$#Keys; $i++) {
  424: 	my $key   = $Keys[$i];
  425: 	if (! exists ($hashes{$name}->{$key})) {
  426: 	    $hashes{$name}->{$key}->[0]=$value;
  427: 	} else {
  428: 	    my @Temp = sort(@{$hashes{$name}->{$key}},$value);
  429: 	    $hashes{$name}->{$key} = \@Temp;
  430: 	}
  431:     }
  432:     return "hash '$name' updated";
  433: }
  434: 
  435: #-------------------------------------------------------
  436: 
  437: =item GETHASH(name,key,index) 
  438: 
  439: returns the element in hash 'name' 
  440: reference by the key 'key', at index 'index' in the values list.
  441: 
  442: =cut
  443: 
  444: #-------------------------------------------------------
  445: sub GETHASH {
  446:     my ($name,$key,$index)=@_;
  447:     if (! defined($index)) {
  448: 	$index = 0;
  449:     }
  450:     if ($key =~ /^[A-z]\d+$/) {
  451: 	$key = $sheet_values{$key};
  452:     }
  453:     return $hashes{$name}->{$key}->[$index];
  454: }
  455: 
  456: #-------------------------------------------------------
  457: 
  458: =item CLEARHASH(name) 
  459: 
  460: clears all the values from the hash 'name'
  461: 
  462: =item CLEARHASH(name,key) 
  463: 
  464: clears all the values from the hash 'name' associated with the given key.
  465: 
  466: =cut
  467: 
  468: #-------------------------------------------------------
  469: sub CLEARHASH {
  470:     my ($name,$key)=@_;
  471:     if (defined($key)) {
  472: 	if (exists($hashes{$name}->{$key})) {
  473: 	    $hashes{$name}->{$key}=undef;
  474: 	    return "hash '$name' key '$key' cleared";
  475: 	}
  476:     } else {
  477: 	if (exists($hashes{$name})) {
  478: 	    $hashes{$name}=undef;
  479: 	    return "hash '$name' cleared";
  480: 	}
  481:     }
  482:     return "Error in clearing hash";
  483: }
  484: 
  485: #-------------------------------------------------------
  486: 
  487: =item HASH(name,key,value) 
  488: 
  489: loads values into an internal hash.  If a key 
  490: already has a value associated with it, the values are sorted numerically.  
  491: 
  492: =item HASH(name,key) 
  493: 
  494: returns the 0th value in the hash 'name' associated with 'key'.
  495: 
  496: =cut
  497: 
  498: #-------------------------------------------------------
  499: sub HASH {
  500:     my ($name,$key,$value)=@_;
  501:     my @Keys;
  502:     undef @Keys;
  503:     my @Values;
  504:     # Check to see if we have multiple $key values
  505:     if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
  506: 	my $keymask = &mask($key);
  507: 	# Assume the keys are addresses
  508: 	my @Temp = grep /$keymask/,keys(%sheet_values);
  509: 	@Keys = $sheet_values{@Temp};
  510:     } else {
  511: 	$Keys[0]= $key;
  512:     }
  513:     # If $value is empty, return the first value associated 
  514:     # with the first key.
  515:     if (! $value) {
  516: 	return $hashes{$name}->{$Keys[0]}->[0];
  517:     }
  518:     # Check to see if we have multiple $value(s) 
  519:     if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
  520: 	my $valmask = &mask($value);
  521: 	my @Temp = grep /$valmask/,keys(%sheet_values);
  522: 	@Values =$sheet_values{@Temp};
  523:     } else {
  524: 	$Values[0]= $value;
  525:     }
  526:     # Add values to hash
  527:     for (my $i = 0; $i<=$#Keys; $i++) {
  528: 	my $key   = $Keys[$i];
  529: 	my $value = ($i<=$#Values ? $Values[$i] : $Values[0]);
  530: 	if (! exists ($hashes{$name}->{$key})) {
  531: 	    $hashes{$name}->{$key}->[0]=$value;
  532: 	} else {
  533: 	    my @Temp = sort(@{$hashes{$name}->{$key}},$value);
  534: 	    $hashes{$name}->{$key} = \@Temp;
  535: 	}
  536:     }
  537:     return $Values[-1];
  538: }
  539: 
  540: #-------------------------------------------------------
  541: 
  542: =item NUM(range)
  543: 
  544: returns the number of items in the range.
  545: 
  546: =cut
  547: 
  548: #-------------------------------------------------------
  549: sub NUM {
  550:     my $mask=mask(@_);
  551:     my $num= $#{@{grep(/$mask/,keys(%sheet_values))}}+1;
  552:     return $num;   
  553: }
  554: 
  555: sub BIN {
  556:     my ($low,$high,$lower,$upper)=@_;
  557:     my $mask=mask($lower,$upper);
  558:     my $num=0;
  559:     foreach (grep /$mask/,keys(%sheet_values)) {
  560:         if (($sheet_values{$_}>=$low) && ($sheet_values{$_}<=$high)) {
  561:             $num++;
  562:         }
  563:     }
  564:     return $num;   
  565: }
  566: 
  567: 
  568: #-------------------------------------------------------
  569: 
  570: =item SUM(range)
  571: 
  572: returns the sum of items in the range.
  573: 
  574: =cut
  575: 
  576: #-------------------------------------------------------
  577: sub SUM {
  578:     my $mask=mask(@_);
  579:     my $sum=0;
  580:     foreach (grep /$mask/,keys(%sheet_values)) {
  581:         $sum+=$sheet_values{$_};
  582:     }
  583:     return $sum;   
  584: }
  585: 
  586: #-------------------------------------------------------
  587: 
  588: =item MEAN(range)
  589: 
  590: compute the average of the items in the range.
  591: 
  592: =cut
  593: 
  594: #-------------------------------------------------------
  595: sub MEAN {
  596:     my $mask=mask(@_);
  597:     my $sum=0; 
  598:     my $num=0;
  599:     foreach (grep /$mask/,keys(%sheet_values)) {
  600:         $sum+=$sheet_values{$_};
  601:         $num++;
  602:     }
  603:     if ($num) {
  604:        return $sum/$num;
  605:     } else {
  606:        return undef;
  607:     }   
  608: }
  609: 
  610: #-------------------------------------------------------
  611: 
  612: =item STDDEV(range)
  613: 
  614: compute the standard deviation of the items in the range.
  615: 
  616: =cut
  617: 
  618: #-------------------------------------------------------
  619: sub STDDEV {
  620:     my $mask=mask(@_);
  621:     my $sum=0; my $num=0;
  622:     foreach (grep /$mask/,keys(%sheet_values)) {
  623:         $sum+=$sheet_values{$_};
  624:         $num++;
  625:     }
  626:     unless ($num>1) { return undef; }
  627:     my $mean=$sum/$num;
  628:     $sum=0;
  629:     foreach (grep /$mask/,keys(%sheet_values)) {
  630:         $sum+=($sheet_values{$_}-$mean)**2;
  631:     }
  632:     return sqrt($sum/($num-1));    
  633: }
  634: 
  635: #-------------------------------------------------------
  636: 
  637: =item PROD(range)
  638: 
  639: compute the product of the items in the range.
  640: 
  641: =cut
  642: 
  643: #-------------------------------------------------------
  644: sub PROD {
  645:     my $mask=mask(@_);
  646:     my $prod=1;
  647:     foreach (grep /$mask/,keys(%sheet_values)) {
  648:         $prod*=$sheet_values{$_};
  649:     }
  650:     return $prod;   
  651: }
  652: 
  653: #-------------------------------------------------------
  654: 
  655: =item MAX(range)
  656: 
  657: compute the maximum of the items in the range.
  658: 
  659: =cut
  660: 
  661: #-------------------------------------------------------
  662: sub MAX {
  663:     my $mask=mask(@_);
  664:     my $max='-';
  665:     foreach (grep /$mask/,keys(%sheet_values)) {
  666:         unless ($max) { $max=$sheet_values{$_}; }
  667:         if (($sheet_values{$_}>$max) || ($max eq '-')) { $max=$sheet_values{$_}; }
  668:     } 
  669:     return $max;   
  670: }
  671: 
  672: #-------------------------------------------------------
  673: 
  674: =item MIN(range)
  675: 
  676: compute the minimum of the items in the range.
  677: 
  678: =cut
  679: 
  680: #-------------------------------------------------------
  681: sub MIN {
  682:     my $mask=mask(@_);
  683:     my $min='-';
  684:     foreach (grep /$mask/,keys(%sheet_values)) {
  685:         unless ($max) { $max=$sheet_values{$_}; }
  686:         if (($sheet_values{$_}<$min) || ($min eq '-')) { 
  687:             $min=$sheet_values{$_}; 
  688:         }
  689:     }
  690:     return $min;   
  691: }
  692: 
  693: #-------------------------------------------------------
  694: 
  695: =item SUMMAX(num,lower,upper)
  696: 
  697: compute the sum of the largest 'num' items in the range from
  698: 'lower' to 'upper'
  699: 
  700: =cut
  701: 
  702: #-------------------------------------------------------
  703: sub SUMMAX {
  704:     my ($num,$lower,$upper)=@_;
  705:     my $mask=mask($lower,$upper);
  706:     my @inside=();
  707:     foreach (grep /$mask/,keys(%sheet_values)) {
  708: 	push (@inside,$sheet_values{$_});
  709:     }
  710:     @inside=sort(@inside);
  711:     my $sum=0; my $i;
  712:     for ($i=$#inside;(($i>$#inside-$num) && ($i>=0));$i--) { 
  713:         $sum+=$inside[$i];
  714:     }
  715:     return $sum;   
  716: }
  717: 
  718: #-------------------------------------------------------
  719: 
  720: =item SUMMIN(num,lower,upper)
  721: 
  722: compute the sum of the smallest 'num' items in the range from
  723: 'lower' to 'upper'
  724: 
  725: =cut
  726: 
  727: #-------------------------------------------------------
  728: sub SUMMIN {
  729:     my ($num,$lower,$upper)=@_;
  730:     my $mask=mask($lower,$upper);
  731:     my @inside=();
  732:     foreach (grep /$mask/,keys(%sheet_values)) {
  733: 	$inside[$#inside+1]=$sheet_values{$_};
  734:     }
  735:     @inside=sort(@inside);
  736:     my $sum=0; my $i;
  737:     for ($i=0;(($i<$num) && ($i<=$#inside));$i++) { 
  738:         $sum+=$inside[$i];
  739:     }
  740:     return $sum;   
  741: }
  742: 
  743: #-------------------------------------------------------
  744: 
  745: =item MINPARM(parametername)
  746: 
  747: Returns the minimum value of the parameters matching the parametername.
  748: parametername should be a string such as 'duedate'.
  749: 
  750: =cut
  751: 
  752: #-------------------------------------------------------
  753: sub MINPARM {
  754:     my ($expression) = @_;
  755:     my $min = undef;
  756:     study($expression);
  757:     foreach $parameter (keys(%c)) {
  758:         next if ($parameter !~ /$expression/);
  759:         if ((! defined($min)) || ($min > $c{$parameter})) {
  760:             $min = $c{$parameter} 
  761:         }
  762:     }
  763:     return $min;
  764: }
  765: 
  766: #-------------------------------------------------------
  767: 
  768: =item MAXPARM(parametername)
  769: 
  770: Returns the maximum value of the parameters matching the input parameter name.
  771: parametername should be a string such as 'duedate'.
  772: 
  773: =cut
  774: 
  775: #-------------------------------------------------------
  776: sub MAXPARM {
  777:     my ($expression) = @_;
  778:     my $max = undef;
  779:     study($expression);
  780:     foreach $parameter (keys(%c)) {
  781:         next if ($parameter !~ /$expression/);
  782:         if ((! defined($min)) || ($max < $c{$parameter})) {
  783:             $max = $c{$parameter} 
  784:         }
  785:     }
  786:     return $max;
  787: }
  788: 
  789: #--------------------------------------------------------
  790: sub expandnamed {
  791:     my $expression=shift;
  792:     if ($expression=~/^\&/) {
  793: 	my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/);
  794: 	my @vars=split(/\W+/,$formula);
  795:         my %values=();
  796:         undef %values;
  797: 	foreach ( @vars ) {
  798:             my $varname=$_;
  799:             if ($varname=~/\D/) {
  800:                $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
  801:                $varname=~s/$var/\(\\w\+\)/g;
  802: 	       foreach (keys(%c)) {
  803: 		  if ($_=~/$varname/) {
  804: 		      $values{$1}=1;
  805:                   }
  806:                }
  807: 	    }
  808:         }
  809:         if ($func eq 'EXPANDSUM') {
  810:             my $result='';
  811: 	    foreach (keys(%values)) {
  812:                 my $thissum=$formula;
  813:                 $thissum=~s/$var/$_/g;
  814:                 $result.=$thissum.'+';
  815:             } 
  816:             $result=~s/\+$//;
  817:             return $result;
  818:         } else {
  819: 	    return 0;
  820:         }
  821:     } else {
  822:         # it is not a function, so it is a parameter name
  823:         # We should do the following:
  824:         #    1. Take the list of parameter names
  825:         #    2. look through the list for ones that match the parameter we want
  826:         #    3. If there are no collisions, return the one that matches
  827:         #    4. If there is a collision, return 'bad parameter name error'
  828:         my $returnvalue = '';
  829:         my @matches = ();
  830:         $#matches = -1;
  831:         study $expression;
  832:         foreach $parameter (keys(%c)) {
  833:             push @matches,$parameter if ($parameter =~ /$expression/);
  834:         }
  835:         if (scalar(@matches) == 0) {
  836:             $returnvalue = undef; #'unmatched parameter: '.$parameter;
  837:         } elsif (scalar(@matches) == 1) {
  838:             $returnvalue = '$c{\''.$matches[0].'\'}';
  839:         } elsif (scalar(@matches) > 0) {
  840:             # more than one match.  Look for a concise one
  841:             $returnvalue =  "'non-unique parameter name : $expression'";
  842:             foreach (@matches) {
  843:                 if (/^$expression$/) {
  844:                     $returnvalue = '$c{\''.$_.'\'}';
  845:                 }
  846:             }
  847:         } else {
  848:             # There was a negative number of matches, which indicates 
  849:             # something is wrong with reality.  Better warn the user.
  850:             $returnvalue = 'bizzare parameter: '.$parameter;
  851:         }
  852:         return $returnvalue;
  853:     }
  854: }
  855: 
  856: sub sett {
  857:     %t=();
  858:     my $pattern='';
  859:     if ($sheettype eq 'assesscalc') {
  860: 	$pattern='A';
  861:     } else {
  862:         $pattern='[A-Z]';
  863:     }
  864:     # Deal with the template row
  865:     foreach (keys(%f)) {
  866: 	next if ($_!~/template\_(\w)/);
  867:         my $col=$1;
  868:         next if ($col=~/^$pattern/);
  869:         foreach (keys(%f)) {
  870:             next if ($_!~/A(\d+)/);
  871:             my $trow=$1;
  872:             next if (! $trow);
  873:             # Get the name of this cell
  874:             my $lb=$col.$trow;
  875:             # Grab the template declaration
  876:             $t{$lb}=$f{'template_'.$col};
  877:             # Replace '#' with the row number
  878:             $t{$lb}=~s/\#/$trow/g;
  879:             # Replace '....' with ','
  880:             $t{$lb}=~s/\.\.+/\,/g;
  881:             # Replace 'A0' with the value from 'A0'
  882:             $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
  883:             # Replace parameters
  884:             $t{$lb}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  885:         }
  886:     }
  887:     # Deal with the normal cells
  888:     foreach (keys(%f)) {
  889: 	if (exists($f{$_}) && ($_!~/template\_/)) {
  890:             my $matches=($_=~/^$pattern(\d+)/);
  891:             if  (($matches) && ($1)) {
  892: 	        unless ($f{$_}=~/^\!/) {
  893: 		    $t{$_}=$c{$_};
  894:                 }
  895:             } else {
  896: 	       $t{$_}=$f{$_};
  897:                $t{$_}=~s/\.\.+/\,/g;
  898:                $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
  899:                $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  900:             }
  901:         }
  902:     }
  903:     # For inserted lines, [B-Z] is also valid
  904:     unless ($sheettype eq 'assesscalc') {
  905:        foreach (keys(%f)) {
  906: 	   if ($_=~/[B-Z](\d+)/) {
  907: 	       if ($f{'A'.$1}=~/^[\~\-]/) {
  908:   	          $t{$_}=$f{$_};
  909:                   $t{$_}=~s/\.\.+/\,/g;
  910:                   $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
  911:                   $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  912:                }
  913:            }
  914:        }
  915:     }
  916:     # For some reason 'A0' gets special treatment...  This seems superfluous
  917:     # but I imagine it is here for a reason.
  918:     $t{'A0'}=$f{'A0'};
  919:     $t{'A0'}=~s/\.\.+/\,/g;
  920:     $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
  921:     $t{'A0'}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  922: }
  923: 
  924: sub calc {
  925:     undef %sheet_values;
  926:     &sett();
  927:     my $notfinished=1;
  928:     my $lastcalc='';
  929:     my $depth=0;
  930:     while ($notfinished) {
  931: 	$notfinished=0;
  932:         foreach (keys(%t)) {
  933:             #$errorlog .= "$_:".$t{$_};
  934:             my $old=$sheet_values{$_};
  935:             $sheet_values{$_}=eval $t{$_};
  936: 	    if ($@) {
  937: 		undef %sheet_values;
  938:                 return $_.': '.$@;
  939:             }
  940: 	    if ($sheet_values{$_} ne $old) { $notfinished=1; $lastcalc=$_; }
  941:             #$errorlog .= ":".$sheet_values{$_}."\n";
  942:         }
  943:         $depth++;
  944:         if ($depth>100) {
  945: 	    undef %sheet_values;
  946:             return $lastcalc.': Maximum calculation depth exceeded';
  947:         }
  948:     }
  949:     return '';
  950: }
  951: 
  952: # ------------------------------------------- End of "Inside of the safe space"
  953: ENDDEFS
  954:     $safeeval->reval($code);
  955:     return $safeeval;
  956: }
  957: 
  958: #
  959: # 
  960: #
  961: sub templaterow {
  962:     my $sheet = shift;
  963:     my @cols=();
  964:     my $rowlabel = 'Template</td><td>&nbsp;';
  965:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  966: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  967: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
  968: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
  969:         push(@cols,{ name    => 'template_'.$_,
  970:                      formula => $sheet->{'f'}->{'template_'.$_},
  971:                      value   => $sheet->{'f'}->{'template_'.$_} });
  972:     }
  973:     return ($rowlabel,@cols);
  974: }
  975: 
  976: sub outrowassess {
  977:     # $n is the current row number
  978:     my ($sheet,$n) = @_;
  979:     my @cols=();
  980:     my $rowlabel='';
  981:     if ($n) {
  982:         my ($usy,$ufn)=split(/__&&&\__/,$sheet->{'f'}->{'A'.$n});
  983:         if (exists($sheet->{'rowlabel'}->{$usy})) {
  984:             # This is dumb, but we need the information when we output
  985:             # the html version of the studentcalc spreadsheet for the
  986:             # links to the assesscalc sheets.
  987:             $rowlabel = $sheet->{'rowlabel'}->{$usy}.':'.
  988:                 &Apache::lonnet::escape($ufn);
  989:         } else { 
  990:             $rowlabel = '';
  991:         }
  992:     } elsif ($ENV{'request.role'} =~ /^st\./) {
  993:         $rowlabel = 'Summary</td><td>0';
  994:     } else {
  995:         $rowlabel = 'Export</td><td>0';
  996:     }
  997:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  998: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  999: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1000: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1001:         push(@cols,{ name    => $_.$n,
 1002:                      formula => $sheet->{'f'}->{$_.$n},
 1003:                      value   => $sheet->{'values'}->{$_.$n}});
 1004:     }
 1005:     return ($rowlabel,@cols);
 1006: }
 1007: 
 1008: sub outrow {
 1009:     my ($sheet,$n)=@_;
 1010:     my @cols=();
 1011:     my $rowlabel;
 1012:     if ($n) {
 1013:         $rowlabel = $sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$n}};
 1014:     } else {
 1015:         if ($sheet->{'sheettype'} eq 'classcalc') {
 1016:             $rowlabel = 'Summary</td><td>0';
 1017:         } else {
 1018:             $rowlabel = 'Export</td><td>0';
 1019:         }
 1020:     }
 1021:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1022: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 1023: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1024: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1025:         push(@cols,{ name    => $_.$n,
 1026:                      formula => $sheet->{'f'}->{$_.$n},
 1027:                      value   => $sheet->{'values'}->{$_.$n}});
 1028:     }
 1029:     return ($rowlabel,@cols);
 1030: }
 1031: 
 1032: # ------------------------------------------------ Add or change formula values
 1033: sub setformulas {
 1034:     my ($sheet)=shift;
 1035:     %{$sheet->{'safe'}->varglob('f')}=%{$sheet->{'f'}};
 1036: }
 1037: 
 1038: # ------------------------------------------------ Add or change formula values
 1039: sub setconstants {
 1040:     my ($sheet)=shift;
 1041:     my ($constants) = @_;
 1042:     if (! ref($constants)) {
 1043:         my %tmp = @_;
 1044:         $constants = \%tmp;
 1045:     }
 1046:     $sheet->{'constants'} = $constants;
 1047:     return %{$sheet->{'safe'}->varglob('c')}=%{$sheet->{'constants'}};
 1048: }
 1049: 
 1050: # --------------------------------------------- Set names of other spreadsheets
 1051: sub setothersheets {
 1052:     my $sheet = shift;
 1053:     my @othersheets = @_;
 1054:     $sheet->{'othersheets'} = \@othersheets;
 1055:     @{$sheet->{'safe'}->varglob('os')}=@othersheets;
 1056:     return;
 1057: }
 1058: 
 1059: # ------------------------------------------------ Add or change formula values
 1060: sub setrowlabels {
 1061:     my $sheet=shift;
 1062:     my ($rowlabel) = @_;
 1063:     if (! ref($rowlabel)) {
 1064:         my %tmp = @_;
 1065:         $rowlabel = \%tmp;
 1066:     }
 1067:     $sheet->{'rowlabel'}=$rowlabel;
 1068: }
 1069: 
 1070: # ------------------------------------------------------- Calculate spreadsheet
 1071: sub calcsheet {
 1072:     my $sheet=shift;
 1073:     my $result =  $sheet->{'safe'}->reval('&calc();');
 1074:     %{$sheet->{'values'}} = %{$sheet->{'safe'}->varglob('sheet_values')};
 1075:     return $result;
 1076: }
 1077: 
 1078: # ---------------------------------------------------------------- Get formulas
 1079: # Return a copy of the formulas
 1080: sub getformulas {
 1081:     my $sheet = shift;
 1082:     return %{$sheet->{'safe'}->varglob('f')};
 1083: }
 1084: 
 1085: sub geterrorlog {
 1086:     my $sheet = shift;
 1087:     return ${$sheet->{'safe'}->varglob('errorlog')};    
 1088: }
 1089: 
 1090: sub gettitle {
 1091:     my $sheet = shift;
 1092:     if ($sheet->{'sheettype'} eq 'classcalc') {
 1093:         return $sheet->{'coursedesc'};
 1094:     } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
 1095:         return 'Grades for '.$sheet->{'uname'}.'@'.$sheet->{'udom'};
 1096:     } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
 1097:         if (($sheet->{'usymb'} eq '_feedback') ||
 1098:             ($sheet->{'usymb'} eq '_evaluation') ||
 1099:             ($sheet->{'usymb'} eq '_discussion') ||
 1100:             ($sheet->{'usymb'} eq '_tutoring')) {
 1101:             my $title = $sheet->{'usymb'};
 1102:             $title =~ s/^_//;
 1103:             $title = ucfirst($title);
 1104:             return $title;
 1105:         }
 1106:         return if (! defined($sheet->{'mapid'}) || 
 1107:                    $sheet->{'mapid'} !~ /^\d+$/);
 1108:         my $mapid = $sheet->{'mapid'};
 1109:         return if (! defined($sheet->{'resid'}) || 
 1110:                    $sheet->{'resid'} !~ /^\d+$/);
 1111:         my $resid = $sheet->{'resid'};
 1112:         my %course_db;
 1113:         tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
 1114:             &GDBM_READER(),0640);
 1115:         return if (! tied(%course_db));
 1116:         my $key = 'title_'.$mapid.'.'.$resid;
 1117:         my $title = '';
 1118:         if (exists($course_db{$key})) {
 1119:             $title = $course_db{$key};
 1120:         } else {
 1121:             $title = $sheet->{'usymb'};
 1122:         }
 1123:         untie (%course_db);
 1124:         return $title;
 1125:     }
 1126: }
 1127: 
 1128: # ----------------------------------------------------- Get value of $f{'A'.$n}
 1129: sub getfa {
 1130:     my $sheet = shift;
 1131:     my ($n)=@_;
 1132:     return $sheet->{'safe'}->reval('$f{"A'.$n.'"}');
 1133: }
 1134: 
 1135: # ------------------------------------------------------------- Export of A-row
 1136: sub exportdata {
 1137:     my $sheet=shift;
 1138:     my @exportarray=();
 1139:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1140: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 1141:         if (exists($sheet->{'values'}->{$_.'0'})) {
 1142:             push(@exportarray,$sheet->{'values'}->{$_.'0'});
 1143:         } else {
 1144:             push(@exportarray,'');
 1145:         }
 1146:     } 
 1147:     return @exportarray;
 1148: }
 1149: 
 1150: 
 1151: 
 1152: sub update_student_sheet{
 1153:     my ($sheet,$r,$c) = @_;
 1154:     # Load in the studentcalc sheet
 1155:     &readsheet($sheet,'default_studentcalc');
 1156:     # Determine the structure (contained assessments, etc) of the sheet
 1157:     &updatesheet($sheet);
 1158:     # Load in the cached sheets for this student
 1159:     &cachedssheets($sheet);
 1160:     # Load in the (possibly cached) data from the assessment sheets        
 1161:     &loadstudent($sheet,$r,$c);
 1162:     # Compute the sheet
 1163:     &calcsheet($sheet);
 1164: }
 1165: 
 1166: # ========================================================== End of Spreadsheet
 1167: # =============================================================================
 1168: #
 1169: # Procedures for spreadsheet output
 1170: #
 1171: # --------------------------------------------- Produce output row n from sheet
 1172: 
 1173: sub get_row {
 1174:     my ($sheet,$n) = @_;
 1175:     my ($rowlabel,@rowdata);
 1176:     if ($n eq '-') { 
 1177:         ($rowlabel,@rowdata) = &templaterow($sheet);
 1178:     } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
 1179:         ($rowlabel,@rowdata) = &outrowassess($sheet,$n);
 1180:     } else {
 1181:         ($rowlabel,@rowdata) = &outrow($sheet,$n);
 1182:     }
 1183:     return ($rowlabel,@rowdata);
 1184: }
 1185: 
 1186: ########################################################################
 1187: ########################################################################
 1188: sub sort_indicies {
 1189:     my $sheet = shift;
 1190:     my @sortidx=();
 1191:     #
 1192:     if ($sheet->{'sheettype'} eq 'classcalc') {
 1193:         my @sortby=(undef);
 1194:         # Skip row 0
 1195:         for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
 1196:             my (undef,$sname,$sdom,$fullname,$section,$id) = 
 1197:                 split(':',$sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$row}});
 1198:             push (@sortby, lc($fullname));
 1199:             push (@sortidx, $row);
 1200:         }
 1201:         @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
 1202:     } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
 1203:         my @sortby1=(undef);
 1204:         my @sortby2=(undef);
 1205:         # Skip row 0
 1206:         for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
 1207:             my ($key,undef) = split(/__&&&\__/,$sheet->{'f'}->{'A'.$row});
 1208:             my $rowlabel = $sheet->{'rowlabel'}->{$key};
 1209:             my (undef,$symb,$mapid,$resid,$title,$ufn) = 
 1210:                 split(':',$rowlabel);
 1211:             $ufn   = &Apache::lonnet::unescape($ufn);
 1212:             $symb  = &Apache::lonnet::unescape($symb);
 1213:             $title = &Apache::lonnet::unescape($title);
 1214:             my ($sequence) = ($symb =~ /\/([^\/]*\.sequence)/);
 1215:             if ($sequence eq '') {
 1216:                 $sequence = $symb;
 1217:             }
 1218:             push (@sortby1, $sequence);
 1219:             push (@sortby2, $title);
 1220:             push (@sortidx, $row);
 1221:         }
 1222:         @sortidx = sort { $sortby1[$a] cmp $sortby1[$b] || 
 1223:                               $sortby2[$a] cmp $sortby2[$b] } @sortidx;
 1224:     } else {
 1225:         my @sortby=(undef);
 1226:         # Skip row 0
 1227:         for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
 1228:             push (@sortby, $sheet->{'safe'}->reval('$f{"A'.$row.'"}'));
 1229:             push (@sortidx, $row);
 1230:         }
 1231:         @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
 1232:     }
 1233:     return @sortidx;
 1234: }
 1235: 
 1236: #############################################################
 1237: ###                                                       ###
 1238: ###              Spreadsheet Output Routines              ###
 1239: ###                                                       ###
 1240: #############################################################
 1241: 
 1242: ############################################
 1243: ##         HTML output routines           ##
 1244: ############################################
 1245: sub html_editable_cell {
 1246:     my ($cell,$bgcolor) = @_;
 1247:     my $result;
 1248:     my ($name,$formula,$value);
 1249:     if (defined($cell)) {
 1250:         $name    = $cell->{'name'};
 1251:         $formula = $cell->{'formula'};
 1252:         $value   = $cell->{'value'};
 1253:     }
 1254:     $name    = '' if (! defined($name));
 1255:     $formula = '' if (! defined($formula));
 1256:     if (! defined($value)) {
 1257:         $value = '<font color="'.$bgcolor.'">#</font>';
 1258:         if ($formula ne '') {
 1259:             $value = '<i>undefined value</i>';
 1260:         }
 1261:     } elsif ($value =~ /^\s*$/ ) {
 1262:         $value = '<font color="'.$bgcolor.'">#</font>';
 1263:     } else {
 1264:         $value = &HTML::Entities::encode($value) if ($value !~/&nbsp;/);
 1265:     }
 1266:     # Make the formula safe for outputting
 1267:     $formula =~ s/\'/\"/g;
 1268:     # The formula will be parsed by the browser *twice* before being 
 1269:     # displayed to the user for editing.
 1270:     $formula = &HTML::Entities::encode(&HTML::Entities::encode($formula));
 1271:     # Escape newlines so they make it into the edit window
 1272:     $formula =~ s/\n/\\n/gs;
 1273:     # Glue everything together
 1274:     $result .= "<a href=\"javascript:celledit(\'".
 1275:         $name."','".$formula."');\">".$value."</a>";
 1276:     return $result;
 1277: }
 1278: 
 1279: sub html_uneditable_cell {
 1280:     my ($cell,$bgcolor) = @_;
 1281:     my $value = (defined($cell) ? $cell->{'value'} : '');
 1282:     $value = &HTML::Entities::encode($value) if ($value !~/&nbsp;/);
 1283:     return '&nbsp;'.$value.'&nbsp;';
 1284: }
 1285: 
 1286: sub outsheet_html  {
 1287:     my ($sheet,$r) = @_;
 1288:     my ($num_uneditable,$realm,$row_type);
 1289:     my $requester_is_student = ($ENV{'request.role'} =~ /^st\./);
 1290:     if ($sheet->{'sheettype'} eq 'assesscalc') {
 1291:         $num_uneditable = 1;
 1292:         $realm = 'Assessment';
 1293:         $row_type = 'Item';
 1294:     } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
 1295:         $num_uneditable = 26;
 1296:         $realm = 'User';
 1297:         $row_type = 'Assessment';
 1298:     } elsif ($sheet->{'sheettype'} eq 'classcalc') {
 1299:         $num_uneditable = 26;
 1300:         $realm = 'Course';
 1301:         $row_type = 'Student';
 1302:     } else {
 1303:         return;  # error
 1304:     }
 1305:     ####################################
 1306:     # Print out header table
 1307:     ####################################
 1308:     my $num_left = 52-$num_uneditable;
 1309:     my $tabledata =<<"END";
 1310: <table border="2">
 1311: <tr>
 1312:   <th colspan="2" rowspan="2"><font size="+2">$realm</font></th>
 1313:   <td bgcolor="#FFDDDD" colspan="$num_uneditable">
 1314:       <b><font size="+1">Import</font></b></td>
 1315:   <td colspan="$num_left">
 1316:       <b><font size="+1">Calculations</font></b></td>
 1317: </tr><tr>
 1318: END
 1319:     my $label_num = 0;
 1320:     foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
 1321:         if ($label_num<$num_uneditable) { 
 1322:             $tabledata.='<td bgcolor="#FFDDDD">';
 1323:         } else {
 1324:             $tabledata.='<td>';
 1325:         }
 1326:         $tabledata.="<b><font size=+1>$_</font></b></td>";
 1327:         $label_num++;
 1328:     }
 1329:     $tabledata.="</tr>\n";
 1330:     $r->print($tabledata);
 1331:     ####################################
 1332:     # Print out template row
 1333:     ####################################
 1334:     my ($num_cols_output,$row_html,$rowlabel,@rowdata);
 1335:     
 1336:     if (! $requester_is_student) {
 1337:         ($rowlabel,@rowdata) = &get_row($sheet,'-');
 1338:         $row_html = '<tr><td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
 1339:         $num_cols_output = 0;
 1340:         foreach my $cell (@rowdata) {
 1341:             if ($requester_is_student || 
 1342:                 $num_cols_output++ < $num_uneditable) {
 1343:                 $row_html .= '<td bgcolor="#FFDDDD">';
 1344:                 $row_html .= &html_uneditable_cell($cell,'#FFDDDD');
 1345:             } else {
 1346:                 $row_html .= '<td bgcolor="#EOFFDD">';
 1347:                 $row_html .= &html_editable_cell($cell,'#E0FFDD');
 1348:             }
 1349:             $row_html .= '</td>';
 1350:         }
 1351:         $row_html.= "</tr>\n";
 1352:         $r->print($row_html);
 1353:     }
 1354:     ####################################
 1355:     # Print out summary/export row
 1356:     ####################################
 1357:     ($rowlabel,@rowdata) = &get_row($sheet,'0');
 1358:     $row_html = '<tr><td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
 1359:     $num_cols_output = 0;
 1360:     foreach my $cell (@rowdata) {
 1361:         if ($num_cols_output++ < 26 && ! $requester_is_student) {
 1362:             $row_html .= '<td bgcolor="#CCCCFF">';
 1363:             $row_html .= &html_editable_cell($cell,'#CCCCFF');
 1364:         } else {
 1365:             $row_html .= '<td bgcolor="#DDCCFF">';
 1366:             $row_html .= &html_uneditable_cell($cell,'#CCCCFF');
 1367:         }
 1368:         $row_html .= '</td>';
 1369:     }
 1370:     $row_html.= "</tr>\n";
 1371:     $r->print($row_html);
 1372:     $r->print('</table>');
 1373:     ####################################
 1374:     # Prepare to output rows
 1375:     ####################################
 1376:     my @Rows = &sort_indicies($sheet);
 1377:     #
 1378:     # Loop through the rows and output them one at a time
 1379:     my $rows_output=0;
 1380:     foreach my $rownum (@Rows) {
 1381:         my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
 1382:         next if ($rowlabel =~ /^\s*$/);
 1383:         next if (($sheet->{'sheettype'} eq 'assesscalc') && 
 1384:                  (! $ENV{'form.showall'})                &&
 1385:                  ($rowdata[0]->{'value'} =~ /^\s*$/));
 1386:         if (! $ENV{'form.showall'} &&
 1387:             $sheet->{'sheettype'} =~ /^(studentcalc|classcalc)$/) {
 1388:             my $row_is_empty = 1;
 1389:             foreach my $cell (@rowdata) {
 1390:                 if ($cell->{'value'} !~  /^\s*$/) {
 1391:                     $row_is_empty = 0;
 1392:                     last;
 1393:                 }
 1394:             }
 1395:             next if ($row_is_empty);
 1396:         }
 1397:         #
 1398:         my $defaultbg='#E0FF';
 1399:         #
 1400:         my $row_html ="\n".'<tr><td><b><font size=+1>'.$rownum.
 1401:             '</font></b></td>';
 1402:         #
 1403:         if ($sheet->{'sheettype'} eq 'classcalc') {
 1404:             $row_html.='<td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
 1405:             # Output links for each student?
 1406:             # Nope, that is already done for us in format_html_rowlabel 
 1407:             # (for now)
 1408:         } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
 1409:             my $ufn = (split(/:/,$rowlabel))[5];
 1410:             $row_html.='<td>'.&format_html_rowlabel($sheet,$rowlabel);
 1411:             $row_html.= '<br>'.
 1412:                 '<select name="sel_'.$rownum.'" '.
 1413:                     'onChange="changesheet('.$rownum.')">'.
 1414:                         '<option name="default">Default</option>';
 1415: 
 1416:             foreach (@{$sheet->{'othersheets'}}) {
 1417:                 $row_html.='<option name="'.$_.'"';
 1418:                 if ($ufn eq $_) {
 1419:                     $row_html.=' selected';
 1420:                 }
 1421:                 $row_html.='>'.$_.'</option>';
 1422:             }
 1423:             $row_html.='</select></td>';
 1424:         } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
 1425:             $row_html.='<td>'.&format_html_rowlabel($sheet,$rowlabel).'</td>';
 1426:         }
 1427:         #
 1428:         my $shown_cells = 0;
 1429:         foreach my $cell (@rowdata) {
 1430:             my $value    = $cell->{'value'};
 1431:             my $formula  = $cell->{'formula'};
 1432:             my $cellname = $cell->{'name'};
 1433:             #
 1434:             my $bgcolor;
 1435:             if ($shown_cells && ($shown_cells/5 == int($shown_cells/5))) {
 1436:                 $bgcolor = $defaultbg.'99';
 1437:             } else {
 1438:                 $bgcolor = $defaultbg.'DD';
 1439:             }
 1440:             $bgcolor='#FFDDDD' if ($shown_cells < $num_uneditable);
 1441:             #
 1442:             $row_html.='<td bgcolor='.$bgcolor.'>';
 1443:             if ($requester_is_student || $shown_cells < $num_uneditable) {
 1444:                 $row_html .= &html_uneditable_cell($cell,$bgcolor);
 1445:             } else {
 1446:                 $row_html .= &html_editable_cell($cell,$bgcolor);
 1447:             }
 1448:             $row_html.='</td>';
 1449:             $shown_cells++;
 1450:         }
 1451:         if ($row_html) {
 1452:             if ($rows_output % 25 == 0) {
 1453:                 $r->print("</table>\n<br>\n");
 1454:                 $r->rflush();
 1455:                 $r->print('<table border=2>'.
 1456:                           '<tr><td>&nbsp;<td>'.$row_type.'</td>'.
 1457:                           '<td>'.
 1458:                           join('</td><td>',
 1459:                                (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
 1460:                                       'abcdefghijklmnopqrstuvwxyz'))).
 1461:                           "</td></tr>\n");
 1462:             }
 1463:             $rows_output++;
 1464:             $r->print($row_html);
 1465:         }
 1466:     }
 1467:     #
 1468:     $r->print('</table>');
 1469:     #
 1470:     # Debugging code (be sure to uncomment errorlog code in safe space):
 1471:     #
 1472:     # $r->print("\n<pre>");
 1473:     # $r->print(&geterrorlog($sheet));
 1474:     # $r->print("\n</pre>");
 1475:     return 1;
 1476: }
 1477: 
 1478: ############################################
 1479: ##         csv output routines            ##
 1480: ############################################
 1481: sub outsheet_csv   {
 1482:     my ($sheet,$r) = @_;
 1483:     my $csvdata = '';
 1484:     my @Values;
 1485:     ####################################
 1486:     # Prepare to output rows
 1487:     ####################################
 1488:     my @Rows = &sort_indicies($sheet);
 1489:     #
 1490:     # Loop through the rows and output them one at a time
 1491:     my $rows_output=0;
 1492:     foreach my $rownum (@Rows) {
 1493:         my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
 1494:         next if ($rowlabel =~ /^\s*$/);
 1495:         push (@Values,&format_csv_rowlabel($sheet,$rowlabel));
 1496:         foreach my $cell (@rowdata) {
 1497:             push (@Values,'"'.$cell->{'value'}.'"');
 1498:         }
 1499:         $csvdata.= join(',',@Values)."\n";
 1500:         @Values = ();
 1501:     }
 1502:     #
 1503:     # Write the CSV data to a file and serve up a link
 1504:     #
 1505:     my $filename = '/prtspool/'.
 1506:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
 1507:         time.'_'.rand(1000000000).'.csv';
 1508:     my $file;
 1509:     unless ($file = Apache::File->new('>'.'/home/httpd'.$filename)) {
 1510:         $r->log_error("Couldn't open $filename for output $!");
 1511:         $r->print("Problems occured in writing the csv file.  ".
 1512:                   "This error has been logged.  ".
 1513:                   "Please alert your LON-CAPA administrator.");
 1514:         $r->print("<pre>\n".$csvdata."</pre>\n");
 1515:         return 0;
 1516:     }
 1517:     print $file $csvdata;
 1518:     close($file);
 1519:     $r->print('<br /><br />'.
 1520:               '<a href="'.$filename.'">Your CSV spreadsheet.</a>'."\n");
 1521:     #
 1522:     return 1;
 1523: }
 1524: 
 1525: ############################################
 1526: ##        Excel output routines           ##
 1527: ############################################
 1528: sub outsheet_recursive_excel {
 1529:     my ($sheet,$r) = @_;
 1530:     my $c = $r->connection;
 1531:     return undef if ($sheet->{'sheettype'} ne 'classcalc');
 1532:     my ($workbook,$filename) = &create_excel_spreadsheet($sheet,$r);
 1533:     return undef if (! defined($workbook));
 1534:     #
 1535:     # Create main worksheet
 1536:     my $main_worksheet = $workbook->addworksheet('main');
 1537:     #
 1538:     # Figure out who the students are
 1539:     my %f=&getformulas($sheet);
 1540:     my $count = 0;
 1541:     $r->print(<<END);
 1542: <p>
 1543: Compiling Excel Workbook with a worksheet for each student.
 1544: </p><p>
 1545: This operation may take longer than a complete recalculation of the
 1546: spreadsheet. 
 1547: </p><p>
 1548: To abort this operation, hit the stop button on your browser.
 1549: </p><p>
 1550: A link to the spreadsheet will be available at the end of this process.
 1551: </p>
 1552: <p>
 1553: END
 1554:     $r->rflush();
 1555:     my $starttime = time;
 1556:     foreach my $rownum (&sort_indicies($sheet)) {
 1557:         $count++;
 1558:         my ($sname,$sdom) = split(':',$f{'A'.$rownum});
 1559:         my $student_excel_worksheet=$workbook->addworksheet($sname.'@'.$sdom);
 1560:         # Create a new spreadsheet
 1561:         my $studentsheet = &makenewsheet($sname,$sdom,'studentcalc',undef);
 1562:         # Read in the spreadsheet definition
 1563:         &update_student_sheet($studentsheet,$r,$c);
 1564:         # Stuff the sheet into excel
 1565:         &export_sheet_as_excel($studentsheet,$student_excel_worksheet);
 1566:         my $totaltime = int((time - $starttime) / $count * $sheet->{'maxrow'});
 1567:         my $timeleft = int((time - $starttime) / $count * ($sheet->{'maxrow'} - $count));
 1568:         if ($count % 5 == 0) {
 1569:             $r->print($count.' students completed.'.
 1570:                       '  Time remaining: '.$timeleft.' sec. '.
 1571:                       '  Estimated total time: '.$totaltime." sec <br />\n");
 1572:             $r->rflush();
 1573:         }
 1574:         if(defined($c) && ($c->aborted())) {
 1575:             last;
 1576:         }
 1577:     }
 1578:     #
 1579:     if(! $c->aborted() ) {
 1580:         $r->print('All students spreadsheets completed!<br />');
 1581:         $r->rflush();
 1582:         #
 1583:         # &export_sheet_as_excel fills $worksheet with the data from $sheet
 1584:         &export_sheet_as_excel($sheet,$main_worksheet);
 1585:         #
 1586:         $workbook->close();
 1587:         # Okay, the spreadsheet is taken care of, so give the user a link.
 1588:         $r->print('<br /><br />'.
 1589:                   '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
 1590:     } else {
 1591:         $workbook->close();  # Not sure how necessary this is.
 1592:         #unlink('/home/httpd'.$filename); # No need to keep this around?
 1593:     }
 1594:     return 1;
 1595: }
 1596: 
 1597: sub outsheet_excel {
 1598:     my ($sheet,$r) = @_;
 1599:     my ($workbook,$filename) = &create_excel_spreadsheet($sheet,$r);
 1600:     return undef if (! defined($workbook));
 1601:     my $sheetname;
 1602:     if ($sheet->{'sheettype'} eq 'classcalc') {
 1603:         $sheetname = 'Main';
 1604:     } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
 1605:         $sheetname = $sheet->{'uname'}.'@'.$sheet->{'udom'};
 1606:     } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
 1607:         $sheetname = $sheet->{'uname'}.'@'.$sheet->{'udom'}.' assessment';
 1608:     }
 1609:     my $worksheet = $workbook->addworksheet($sheetname);
 1610:     #
 1611:     # &export_sheet_as_excel fills $worksheet with the data from $sheet
 1612:     &export_sheet_as_excel($sheet,$worksheet);
 1613:     #
 1614:     $workbook->close();
 1615:     # Okay, the spreadsheet is taken care of, so give the user a link.
 1616:     $r->print('<br /><br />'.
 1617:               '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
 1618:     return 1;
 1619: }
 1620: 
 1621: sub create_excel_spreadsheet {
 1622:     my ($sheet,$r) = @_;
 1623:     my $filename = '/prtspool/'.
 1624:         $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
 1625:         time.'_'.rand(1000000000).'.xls';
 1626:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
 1627:     if (! defined($workbook)) {
 1628:         $r->log_error("Error creating excel spreadsheet $filename: $!");
 1629:         $r->print("Problems creating new Excel file.  ".
 1630:                   "This error has been logged.  ".
 1631:                   "Please alert your LON-CAPA administrator");
 1632:         return undef;
 1633:     }
 1634:     #
 1635:     # The spreadsheet stores temporary data in files, then put them
 1636:     # together.  If needed we should be able to disable this (memory only).
 1637:     # The temporary directory must be specified before calling 'addworksheet'.
 1638:     # File::Temp is used to determine the temporary directory.
 1639:     $workbook->set_tempdir('/home/httpd/perl/tmp');
 1640:     #
 1641:     # Determine the name to give the worksheet
 1642:     return ($workbook,$filename);
 1643: }
 1644: 
 1645: sub export_sheet_as_excel {
 1646:     my $sheet = shift;
 1647:     my $worksheet = shift;
 1648:     #
 1649:     my $rows_output = 0;
 1650:     my $cols_output = 0;
 1651:     ####################################
 1652:     #    Write an identifying row      #
 1653:     ####################################
 1654:     my @Headerinfo = ($sheet->{'coursedesc'});
 1655:     my $title = &gettitle($sheet);
 1656:     $cols_output = 0;    
 1657:     if (defined($title)) {
 1658:         $worksheet->write($rows_output++,$cols_output++,$title);
 1659:     }
 1660:     ####################################
 1661:     #   Write the summary/export row   #
 1662:     ####################################
 1663:     my ($rowlabel,@rowdata) = &get_row($sheet,'0');
 1664:     my $label = &format_excel_rowlabel($sheet,$rowlabel);
 1665:     $cols_output = 0;
 1666:     $worksheet->write($rows_output,$cols_output++,$label);
 1667:     foreach my $cell (@rowdata) {
 1668:         $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
 1669:     }
 1670:     $rows_output+= 2;   # Skip a row, just for fun
 1671:     ####################################
 1672:     # Prepare to output rows
 1673:     ####################################
 1674:     my @Rows = &sort_indicies($sheet);
 1675:     #
 1676:     # Loop through the rows and output them one at a time
 1677:     foreach my $rownum (@Rows) {
 1678:         my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
 1679:         next if ($rowlabel =~ /^[\s]*$/);
 1680:         $cols_output = 0;
 1681:         my $label = &format_excel_rowlabel($sheet,$rowlabel);
 1682:         if ( ! $ENV{'form.showall'} &&
 1683:              $sheet->{'sheettype'} =~ /^(studentcalc|classcalc)$/) {
 1684:             my $row_is_empty = 1;
 1685:             foreach my $cell (@rowdata) {
 1686:                 if ($cell->{'value'} !~  /^\s*$/) {
 1687:                     $row_is_empty = 0;
 1688:                     last;
 1689:                 }
 1690:             }
 1691:             next if ($row_is_empty);
 1692:         }
 1693:         $worksheet->write($rows_output,$cols_output++,$label);
 1694:         if (ref($label)) {
 1695:             $cols_output = (scalar(@$label));
 1696:         }
 1697:         foreach my $cell (@rowdata) {
 1698:             $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
 1699:         }
 1700:         $rows_output++;
 1701:     }
 1702:     return;
 1703: }
 1704: 
 1705: ############################################
 1706: ##          XML output routines           ##
 1707: ############################################
 1708: sub outsheet_xml   {
 1709:     my ($sheet,$r) = @_;
 1710:     ## Someday XML
 1711:     ## Will be rendered for the user
 1712:     ## But not on this day
 1713: }
 1714: 
 1715: ##
 1716: ## Outsheet - calls other outsheet_* functions
 1717: ##
 1718: sub outsheet {
 1719:     my ($sheet,$r)=@_;
 1720:     if (! exists($ENV{'form.output'})) {
 1721:         $ENV{'form.output'} = 'HTML';
 1722:     }
 1723:     if (lc($ENV{'form.output'}) eq 'csv') {
 1724:         &outsheet_csv($sheet,$r);
 1725:     } elsif (lc($ENV{'form.output'}) eq 'excel') {
 1726:         &outsheet_excel($sheet,$r);
 1727:     } elsif (lc($ENV{'form.output'}) eq 'recursive excel') {
 1728:         &outsheet_recursive_excel($sheet,$r);
 1729: #    } elsif (lc($ENV{'form.output'}) eq 'xml' ) {
 1730: #        &outsheet_xml($sheet,$r);
 1731:     } else {
 1732:         &outsheet_html($sheet,$r);
 1733:     }
 1734: }
 1735: 
 1736: ########################################################################
 1737: ########################################################################
 1738: sub othersheets {
 1739:     my ($sheet,$stype)=@_;
 1740:     $stype = $sheet->{'sheettype'} if (! defined($stype));
 1741:     #
 1742:     my $cnum  = $sheet->{'cnum'};
 1743:     my $cdom  = $sheet->{'cdom'};
 1744:     my $chome = $sheet->{'chome'};
 1745:     #
 1746:     my @alternatives=();
 1747:     my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
 1748:     my ($tmp) = keys(%results);
 1749:     unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1750:         @alternatives = sort (keys(%results));
 1751:     }
 1752:     return @alternatives; 
 1753: }
 1754: 
 1755: #
 1756: # -------------------------------------- Parse a spreadsheet
 1757: # 
 1758: sub parse_sheet {
 1759:     # $sheetxml is a scalar reference or a scalar
 1760:     my ($sheetxml) = @_;
 1761:     if (! ref($sheetxml)) {
 1762:         my $tmp = $sheetxml;
 1763:         $sheetxml = \$tmp;
 1764:     }
 1765:     my %f;
 1766:     my $parser=HTML::TokeParser->new($sheetxml);
 1767:     my $token;
 1768:     while ($token=$parser->get_token) {
 1769:         if ($token->[0] eq 'S') {
 1770:             if ($token->[1] eq 'field') {
 1771:                 $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
 1772:                     $parser->get_text('/field');
 1773:             }
 1774:             if ($token->[1] eq 'template') {
 1775:                 $f{'template_'.$token->[2]->{'col'}}=
 1776:                     $parser->get_text('/template');
 1777:             }
 1778:         }
 1779:     }
 1780:     return \%f;
 1781: }
 1782: 
 1783: #
 1784: # -------------------------------------- Read spreadsheet formulas for a course
 1785: #
 1786: sub readsheet {
 1787:     my ($sheet,$fn)=@_;
 1788:     #
 1789:     my $stype = $sheet->{'sheettype'};
 1790:     my $cnum  = $sheet->{'cnum'};
 1791:     my $cdom  = $sheet->{'cdom'};
 1792:     my $chome = $sheet->{'chome'};
 1793:     #
 1794:     if (! defined($fn)) {
 1795:         # There is no filename. Look for defaults in course and global, cache
 1796:         unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
 1797:             my %tmphash = &Apache::lonnet::get('environment',
 1798:                                                ['spreadsheet_default_'.$stype],
 1799:                                                $cdom,$cnum);
 1800:             my ($tmp) = keys(%tmphash);
 1801:             if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1802:                 $fn = 'default_'.$stype;
 1803:             } else {
 1804:                 $fn = $tmphash{'spreadsheet_default_'.$stype};
 1805:             } 
 1806:             unless (($fn) && ($fn!~/^error\:/)) {
 1807:                 $fn='default_'.$stype;
 1808:             }
 1809:             $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn; 
 1810:         }
 1811:     }
 1812:     # $fn now has a value
 1813:     $sheet->{'filename'} = $fn;
 1814:     # see if sheet is cached
 1815:     my $fstring='';
 1816:     if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
 1817:         my %tmp = split(/___;___/,$fstring);
 1818:         $sheet->{'f'} = \%tmp;
 1819:         &setformulas($sheet);
 1820:     } else {
 1821:         # Not cached, need to read
 1822:         my %f=();
 1823:         if ($fn=~/^default\_/) {
 1824:             my $sheetxml='';
 1825:             my $fh;
 1826:             my $dfn=$fn;
 1827:             $dfn=~s/\_/\./g;
 1828:             if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
 1829:                 $sheetxml=join('',<$fh>);
 1830:             } else {
 1831:                 # $sheetxml='<field row="0" col="A">"Error"</field>';
 1832:                 $sheetxml='<field row="0" col="A"></field>';
 1833:             }
 1834:             %f=%{&parse_sheet(\$sheetxml)};
 1835:         } elsif($fn=~/\/*\.spreadsheet$/) {
 1836:             my $sheetxml=&Apache::lonnet::getfile
 1837:                 (&Apache::lonnet::filelocation('',$fn));
 1838:             if ($sheetxml == -1) {
 1839:                 $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
 1840:                     .$fn.'"</field>';
 1841:             }
 1842:             %f=%{&parse_sheet(\$sheetxml)};
 1843:         } else {
 1844:             my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
 1845:             my ($tmp) = keys(%tmphash);
 1846:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 1847:                 foreach (keys(%tmphash)) {
 1848:                     $f{$_}=$tmphash{$_};
 1849:                 }
 1850:             } else {
 1851:                 # Unable to grab the specified spreadsheet,
 1852:                 # so we get the default ones instead.
 1853:                 $fn = 'default_'.$stype;
 1854:                 $sheet->{'filename'} = $fn;
 1855:                 my $dfn = $fn;
 1856:                 $dfn =~ s/\_/\./g;
 1857:                 my $sheetxml;
 1858:                 if (my $fh=Apache::File->new($includedir.'/'.$dfn)) {
 1859:                     $sheetxml = join('',<$fh>);
 1860:                 } else {
 1861:                     $sheetxml='<field row="0" col="A">'.
 1862:                         '"Unable to load spreadsheet"</field>';
 1863:                 }
 1864:                 %f=%{&parse_sheet(\$sheetxml)};
 1865:             }
 1866:         }
 1867:         # Cache and set
 1868:         $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);  
 1869:         $sheet->{'f'}=\%f;
 1870:         &setformulas($sheet);
 1871:     }
 1872: }
 1873: 
 1874: # -------------------------------------------------------- Make new spreadsheet
 1875: sub makenewsheet {
 1876:     my ($uname,$udom,$stype,$usymb)=@_;
 1877:     my $sheet={};
 1878:     $sheet->{'uname'} = $uname;
 1879:     $sheet->{'udom'}  = $udom;
 1880:     $sheet->{'sheettype'} = $stype;
 1881:     $sheet->{'usymb'} = $usymb;
 1882:     $sheet->{'mapid'} = $ENV{'form.mapid'};
 1883:     $sheet->{'resid'} = $ENV{'form.resid'};
 1884:     $sheet->{'cid'}   = $ENV{'request.course.id'};
 1885:     if (! exists($Section{$uname.':'.$udom})) {
 1886:         my $classlist = &Apache::loncoursedata::get_classlist();
 1887:         foreach my $student (keys(%$classlist)) {
 1888:             my ($studentDomain,$studentName,undef,undef,undef,$studentSection,
 1889:                 undef,undef)   =   @{$classlist->{$student}};
 1890:             $Section{$studentName.':'.$studentDomain} = $studentSection;
 1891:         }
 1892:     }
 1893:     $sheet->{'csec'}  = $Section{$uname.':'.$udom};
 1894:     $sheet->{'coursefilename'}   = $ENV{'request.course.fn'};
 1895:     $sheet->{'cnum'}  = $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1896:     $sheet->{'cdom'}  = $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1897:     $sheet->{'chome'} = $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1898:     $sheet->{'coursedesc'} = $ENV{'course.'.$ENV{'request.course.id'}.
 1899:                                       '.description'};
 1900:     $sheet->{'uhome'} = &Apache::lonnet::homeserver($uname,$udom);
 1901:     #
 1902:     #
 1903:     $sheet->{'f'} = {};
 1904:     $sheet->{'constants'} = {};
 1905:     $sheet->{'othersheets'} = [];
 1906:     $sheet->{'rowlabel'} = {};
 1907:     #
 1908:     #
 1909:     $sheet->{'safe'}=&initsheet($sheet->{'sheettype'});
 1910:     #
 1911:     # Place all the %$sheet items into the safe space except the safe space
 1912:     # itself
 1913:     my $initstring = '';
 1914:     foreach (qw/uname udom sheettype usymb cid csec coursefilename
 1915:              cnum cdom chome uhome/) {
 1916:         $initstring.= qq{\$$_="$sheet->{$_}";};
 1917:     }
 1918:     $sheet->{'safe'}->reval($initstring);
 1919:     return $sheet;
 1920: }
 1921: 
 1922: # ------------------------------------------------------------ Save spreadsheet
 1923: sub writesheet {
 1924:     my ($sheet,$makedef)=@_;
 1925:     my $cid=$sheet->{'cid'};
 1926:     if (&Apache::lonnet::allowed('opa',$cid)) {
 1927:         my %f=&getformulas($sheet);
 1928:         my $stype= $sheet->{'sheettype'};
 1929:         my $cnum = $sheet->{'cnum'};
 1930:         my $cdom = $sheet->{'cdom'};
 1931:         my $chome= $sheet->{'chome'};
 1932:         my $fn   = $sheet->{'filename'};
 1933:         # Cache new sheet
 1934:         $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
 1935:         # Write sheet
 1936:         foreach (keys(%f)) {
 1937:             delete($f{$_}) if ($f{$_} eq 'import');
 1938:         }
 1939:         my $reply = &Apache::lonnet::put($fn,\%f,$cdom,$cnum);
 1940:         if ($reply eq 'ok') {
 1941:             $reply = &Apache::lonnet::put($stype.'_spreadsheets',
 1942:                             {$fn => $ENV{'user.name'}.'@'.$ENV{'user.domain'}},
 1943:                                           $cdom,$cnum);
 1944:             if ($reply eq 'ok') {
 1945:                 if ($makedef) { 
 1946:                     $reply = &Apache::lonnet::put('environment',
 1947:                                     {'spreadsheet_default_'.$stype => $fn },
 1948:                                                   $cdom,$cnum);
 1949:                     if ($reply eq 'ok' && 
 1950:                         ($sheet->{'sheettype'} eq 'studentcalc' ||
 1951:                          $sheet->{'sheettype'} eq 'assesscalc')) {
 1952:                         # Expire the spreadsheets of the other students.
 1953:                         &Apache::lonnet::expirespread('','','studentcalc','');
 1954:                     }
 1955:                     return $reply;
 1956:                 } 
 1957:                 return $reply;
 1958:             } 
 1959:             return $reply;
 1960:         } 
 1961:         return $reply;
 1962:     }
 1963:     return 'unauthorized';
 1964: }
 1965: 
 1966: # ----------------------------------------------- Make a temp copy of the sheet
 1967: # "Modified workcopy" - interactive only
 1968: #
 1969: sub tmpwrite {
 1970:     my ($sheet) = @_;
 1971:     my $fn=$ENV{'user.name'}.'_'.
 1972:         $ENV{'user.domain'}.'_spreadsheet_'.$sheet->{'usymb'}.'_'.
 1973:            $sheet->{'filename'};
 1974:     $fn=~s/\W/\_/g;
 1975:     $fn=$tmpdir.$fn.'.tmp';
 1976:     my $fh;
 1977:     if ($fh=Apache::File->new('>'.$fn)) {
 1978:         my %f = &getformulas($sheet);
 1979:         while( my ($cell,$formula) = each(%f)) {
 1980:             print $fh &Apache::lonnet::escape($cell)."=".&Apache::lonnet::escape($formula)."\n";
 1981:         }
 1982:     }
 1983: }
 1984: 
 1985: # ---------------------------------------------------------- Read the temp copy
 1986: sub tmpread {
 1987:     my ($sheet,$nfield,$nform)=@_;
 1988:     my $fn=$ENV{'user.name'}.'_'.
 1989:            $ENV{'user.domain'}.'_spreadsheet_'.$sheet->{'usymb'}.'_'.
 1990:            $sheet->{'filename'};
 1991:     $fn=~s/\W/\_/g;
 1992:     $fn=$tmpdir.$fn.'.tmp';
 1993:     my $fh;
 1994:     my %fo=();
 1995:     my $countrows=0;
 1996:     if ($fh=Apache::File->new($fn)) {
 1997:         while (<$fh>) {
 1998: 	    chomp;
 1999:             my ($cell,$formula) = split(/=/);
 2000:             $cell    = &Apache::lonnet::unescape($cell);
 2001:             $formula = &Apache::lonnet::unescape($formula);
 2002:             $fo{$cell} = $formula;
 2003:         }
 2004:     }
 2005: #            chomp($value);
 2006: #            $fo{$name}=$value;
 2007: #            if ($name=~/^A(\d+)$/) {
 2008: #		if ($1>$countrows) {
 2009: #		    $countrows=$1;
 2010: #                }
 2011: #            }
 2012: #        }
 2013: #    }
 2014:     if ($nform eq 'changesheet') {
 2015:         $fo{'A'.$nfield}=(split(/__&&&\__/,$fo{'A'.$nfield}))[0];
 2016:         unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
 2017: 	    $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
 2018:         }
 2019: #    } elsif ($nfield eq 'insertrow') {
 2020: #        $countrows++;
 2021: #        my $newrow=substr('000000'.$countrows,-7);
 2022: #        if ($nform eq 'top') {
 2023: #	    $fo{'A'.$countrows}='--- '.$newrow;
 2024: #        } else {
 2025: #            $fo{'A'.$countrows}='~~~ '.$newrow;
 2026: #        }
 2027:     } else {
 2028:        if ($nfield) { $fo{$nfield}=$nform; }
 2029:     }
 2030:     $sheet->{'f'}=\%fo;
 2031:     &setformulas($sheet);
 2032: }
 2033: 
 2034: ##################################################
 2035: ##################################################
 2036: 
 2037: =pod
 2038: 
 2039: =item &parmval()
 2040: 
 2041: Determine the value of a parameter.
 2042: 
 2043: Inputs: $what, the parameter needed, $sheet, the safe space
 2044: 
 2045: Returns: The value of a parameter, or '' if none.
 2046: 
 2047: This function cascades through the possible levels searching for a value for
 2048: a parameter.  The levels are checked in the following order:
 2049: user, course (at section level and course level), map, and lonnet::metadata.
 2050: This function uses %parmhash, which must be tied prior to calling it.
 2051: This function also requires %courseopt and %useropt to be initialized for
 2052: this user and course.
 2053: 
 2054: =cut
 2055: 
 2056: ##################################################
 2057: ##################################################
 2058: sub parmval {
 2059:     my ($what,$sheet)=@_;
 2060:     my $symb  = $sheet->{'usymb'};
 2061:     unless ($symb) { return ''; }
 2062:     #
 2063:     my $cid   = $sheet->{'cid'};
 2064:     my $csec  = $sheet->{'csec'};
 2065:     my $uname = $sheet->{'uname'};
 2066:     my $udom  = $sheet->{'udom'};
 2067:     my $result='';
 2068:     #
 2069:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 2070:     # Cascading lookup scheme
 2071:     my $rwhat=$what;
 2072:     $what =~ s/^parameter\_//;
 2073:     $what =~ s/\_([^\_]+)$/\.$1/;
 2074:     #
 2075:     my $symbparm = $symb.'.'.$what;
 2076:     my $mapparm  = $mapname.'___(all).'.$what;
 2077:     my $usercourseprefix = $uname.'_'.$udom.'_'.$cid;
 2078:     #
 2079:     my $seclevel  = $usercourseprefix.'.['.$csec.'].'.$what;
 2080:     my $seclevelr = $usercourseprefix.'.['.$csec.'].'.$symbparm;
 2081:     my $seclevelm = $usercourseprefix.'.['.$csec.'].'.$mapparm;
 2082:     #
 2083:     my $courselevel  = $usercourseprefix.'.'.$what;
 2084:     my $courselevelr = $usercourseprefix.'.'.$symbparm;
 2085:     my $courselevelm = $usercourseprefix.'.'.$mapparm;
 2086:     # fourth, check user
 2087:     if (defined($uname)) {
 2088:         return $useropt{$courselevelr} if (defined($useropt{$courselevelr}));
 2089:         return $useropt{$courselevelm} if (defined($useropt{$courselevelm}));
 2090:         return $useropt{$courselevel}  if (defined($useropt{$courselevel}));
 2091:     }
 2092:     # third, check course
 2093:     if (defined($csec)) {
 2094:         return $courseopt{$seclevelr} if (defined($courseopt{$seclevelr}));
 2095:         return $courseopt{$seclevelm} if (defined($courseopt{$seclevelm}));
 2096:         return $courseopt{$seclevel}  if (defined($courseopt{$seclevel}));
 2097:     }
 2098:     #
 2099:     return $courseopt{$courselevelr} if (defined($courseopt{$courselevelr}));
 2100:     return $courseopt{$courselevelm} if (defined($courseopt{$courselevelm}));
 2101:     return $courseopt{$courselevel}  if (defined($courseopt{$courselevel}));
 2102:     # second, check map parms
 2103:     my $thisparm = $parmhash{$symbparm};
 2104:     return $thisparm if (defined($thisparm));
 2105: 
 2106:     # first, check default
 2107:     $thisparm = &Apache::lonnet::metadata($fn,$rwhat.'.default');
 2108:     return $thisparm if (defined($thisparm));
 2109: 
 2110:     #Cascade Up
 2111:     my $space=$what;
 2112:     $space=~s/\.\w+$//;
 2113:     if ($space ne '0') {
 2114: 	my @parts=split(/_/,$space);
 2115: 	my $id=pop(@parts);
 2116: 	my $part=join('_',@parts);
 2117: 	if ($part eq '') { $part='0'; }
 2118: 	my $newwhat=$rwhat;
 2119: 	$newwhat=~s/\Q$space\E/$part/;
 2120: 	my $partgeneral=&parmval($newwhat,$sheet);
 2121: 	if (defined($partgeneral)) { return $partgeneral; }
 2122:     }
 2123: 
 2124:     #nothing defined
 2125:     return '';
 2126: }
 2127: 
 2128: 
 2129: ##################################################################
 2130: ##                  Row label formatting routines               ##
 2131: ##################################################################
 2132: sub format_html_rowlabel {
 2133:     my $sheet = shift;
 2134:     my $rowlabel = shift;
 2135:     return '' if ($rowlabel eq '');
 2136:     my ($type,$labeldata) = split(':',$rowlabel,2);
 2137:     my $result = '';
 2138:     if ($type eq 'symb') {
 2139:         my ($symb,$mapid,$resid,$title,$ufn) = split(':',$labeldata);
 2140:         $ufn   = 'default' if (!defined($ufn) || $ufn eq '');
 2141:         $ufn   = &Apache::lonnet::unescape($ufn);
 2142:         $symb  = &Apache::lonnet::unescape($symb);
 2143:         $title = &Apache::lonnet::unescape($title);
 2144:         $result = '<a href="/adm/assesscalc?usymb='.$symb.
 2145:             '&uname='.$sheet->{'uname'}.'&udom='.$sheet->{'udom'}.
 2146:                 '&ufn='.$ufn.
 2147:                     '&mapid='.$mapid.'&resid='.$resid.'">'.$title.'</a>';
 2148:     } elsif ($type eq 'student') {
 2149:         my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
 2150:         if ($fullname =~ /^\s*$/) {
 2151:             $fullname = $sname.'@'.$sdom;
 2152:         }
 2153:         $result ='<a href="/adm/studentcalc?uname='.$sname.
 2154:             '&udom='.$sdom.'">';
 2155:         $result.=$section.'&nbsp;'.$id."&nbsp;".$fullname.'</a>';
 2156:     } elsif ($type eq 'parameter') {
 2157:         $result = $labeldata;
 2158:     } else {
 2159:         $result = '<b><font size=+1>'.$rowlabel.'</font></b>';
 2160:     }
 2161:     return $result;
 2162: }
 2163: 
 2164: sub format_csv_rowlabel {
 2165:     my $sheet = shift;
 2166:     my $rowlabel = shift;
 2167:     return '' if ($rowlabel eq '');
 2168:     my ($type,$labeldata) = split(':',$rowlabel,2);
 2169:     my $result = '';
 2170:     if ($type eq 'symb') {
 2171:         my ($symb,$mapid,$resid,$title,$ufn) = split(':',$labeldata);
 2172:         $ufn   = &Apache::lonnet::unescape($ufn);
 2173:         $symb  = &Apache::lonnet::unescape($symb);
 2174:         $title = &Apache::lonnet::unescape($title);
 2175:         $result = $title;
 2176:     } elsif ($type eq 'student') {
 2177:         my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
 2178:         $result = join('","',($sname,$sdom,$fullname,$section,$id));
 2179:     } elsif ($type eq 'parameter') {
 2180:         $labeldata =~ s/<br>/ /g;
 2181:         $result = $labeldata;
 2182:     } else {
 2183:         $result = $rowlabel;
 2184:     }
 2185:     return '"'.$result.'"';
 2186: }
 2187: 
 2188: sub format_excel_rowlabel {
 2189:     my $sheet = shift;
 2190:     my $rowlabel = shift;
 2191:     return '' if ($rowlabel eq '');
 2192:     my ($type,$labeldata) = split(':',$rowlabel,2);
 2193:     my $result = '';
 2194:     if ($type eq 'symb') {
 2195:         my ($symb,$mapid,$resid,$title,$ufn) = split(':',$labeldata);
 2196:         $ufn   = &Apache::lonnet::unescape($ufn);
 2197:         $symb  = &Apache::lonnet::unescape($symb);
 2198:         $title = &Apache::lonnet::unescape($title);
 2199:         $result = $title;
 2200:     } elsif ($type eq 'student') {
 2201:         my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
 2202:         $section = '' if (! defined($section));
 2203:         $id      = '' if (! defined($id));
 2204:         my @Data = ($sname,$sdom,$fullname,$section,$id);
 2205:         $result = \@Data;
 2206:     } elsif ($type eq 'parameter') {
 2207:         $labeldata =~ s/<br>/ /g;
 2208:         $result = $labeldata;
 2209:     } else {
 2210:         $result = $rowlabel;
 2211:     }
 2212:     return $result;
 2213: }
 2214: 
 2215: # ---------------------------------------------- Update rows for course listing
 2216: sub updateclasssheet {
 2217:     my ($sheet) = @_;
 2218:     my $cnum  =$sheet->{'cnum'};
 2219:     my $cdom  =$sheet->{'cdom'};
 2220:     my $cid   =$sheet->{'cid'};
 2221:     my $chome =$sheet->{'chome'};
 2222:     #
 2223:     %Section = ();
 2224:     #
 2225:     # Read class list and row labels
 2226:     my $classlist = &Apache::loncoursedata::get_classlist();
 2227:     if (! defined($classlist)) {
 2228:         return 'Could not access course classlist';
 2229:     } 
 2230:     #
 2231:     my %currentlist=();
 2232:     foreach my $student (keys(%$classlist)) {
 2233:         my ($studentDomain,$studentName,$end,$start,$id,$studentSection,
 2234:             $fullname,$status)   =   @{$classlist->{$student}};
 2235:         $Section{$studentName.':'.$studentDomain} = $studentSection;
 2236:         if ($ENV{'form.Status'} eq $status || $ENV{'form.Status'} eq 'Any') {
 2237:             $currentlist{$student}=join(':',('student',$studentName,
 2238:                                              $studentDomain,$fullname,
 2239:                                              $studentSection,$id));
 2240:         }
 2241:     }
 2242:     #
 2243:     # Find discrepancies between the course row table and this
 2244:     #
 2245:     my %f=&getformulas($sheet);
 2246:     my $changed=0;
 2247:     #
 2248:     $sheet->{'maxrow'}=0;
 2249:     my %existing=();
 2250:     #
 2251:     # Now obsolete rows
 2252:     foreach (keys(%f)) {
 2253:         if ($_=~/^A(\d+)/) {
 2254:             if ($1 > $sheet->{'maxrow'}) {
 2255:                 $sheet->{'maxrow'}= $1;
 2256:             }
 2257:             $existing{$f{$_}}=1;
 2258:             unless ((defined($currentlist{$f{$_}})) || (!$1) ||
 2259:                     ($f{$_}=~/^(~~~|---)/)) {
 2260:                 $f{$_}='!!! Obsolete';
 2261:                 $changed=1;
 2262:             }
 2263:         }
 2264:     }
 2265:     #
 2266:     # New and unknown keys
 2267:     foreach my $student (sort keys(%currentlist)) {
 2268:         unless ($existing{$student}) {
 2269:             $changed=1;
 2270:             $sheet->{'maxrow'}++;
 2271:             $f{'A'.$sheet->{'maxrow'}}=$student;
 2272:         }
 2273:     }
 2274:     if ($changed) { 
 2275:         $sheet->{'f'} = \%f;
 2276:         &setformulas($sheet,%f); 
 2277:     }
 2278:     #
 2279:     &setrowlabels($sheet,\%currentlist);
 2280: }
 2281: 
 2282: # ----------------------------------- Update rows for student and assess sheets
 2283: sub get_student_rowlabels {
 2284:     my ($sheet) = @_;
 2285:     #
 2286:     my %course_db;
 2287:     #
 2288:     my $stype = $sheet->{'sheettype'};
 2289:     my $uname = $sheet->{'uname'};
 2290:     my $udom  = $sheet->{'udom'};
 2291:     #
 2292:     $sheet->{'rowlabel'} = {};
 2293:     #
 2294:     my $identifier =$sheet->{'coursefilename'}.'_'.$stype;
 2295:     if  ($rowlabel_cache{$identifier}) {
 2296:         %{$sheet->{'rowlabel'}}=split(/___;___/,$rowlabel_cache{$identifier});
 2297:     } else {
 2298:         # Get the data and store it in the cache
 2299:         # Tie hash
 2300:         tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
 2301:             &GDBM_READER(),0640);
 2302:         if (! tied(%course_db)) {
 2303:             return 'Could not access course data';
 2304:         }
 2305:         #
 2306:         my %assesslist = ();
 2307:         foreach ('Feedback','Evaluation','Tutoring','Discussion') {
 2308:             my $symb = '_'.lc($_);
 2309:             $assesslist{$symb} = join(':',('symb',$symb,0,0,
 2310:                                            &Apache::lonnet::escape($_)));
 2311:         }
 2312:         #
 2313:         while (my ($key,$srcf) = each(%course_db)) {
 2314:             next if ($key !~ /^src_(\d+)\.(\d+)$/);
 2315:             my $mapid = $1;
 2316:             my $resid = $2;
 2317:             my $id   = $mapid.'.'.$resid;
 2318:             if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
 2319:                 my $symb=
 2320:                     &Apache::lonnet::declutter($course_db{'map_id_'.$mapid}).
 2321:                         '___'.$resid.'___'.&Apache::lonnet::declutter($srcf);
 2322:                 $assesslist{$symb} ='symb:'.&Apache::lonnet::escape($symb).':'
 2323:                     .$mapid.':'.$resid.':'.
 2324:                         &Apache::lonnet::escape($course_db{'title_'.$id});
 2325:             }
 2326:         }
 2327:         untie(%course_db);
 2328:         # Store away the data
 2329:         $sheet->{'rowlabel'} = \%assesslist;
 2330:         $rowlabel_cache{$identifier}=join('___;___',%{$sheet->{'rowlabel'}});
 2331:     }
 2332: 
 2333: }
 2334: 
 2335: sub get_assess_rowlabels {
 2336:     my ($sheet) = @_;
 2337:     #
 2338:     my %course_db;
 2339:     #
 2340:     my $stype = $sheet->{'sheettype'};
 2341:     my $uname = $sheet->{'uname'};
 2342:     my $udom  = $sheet->{'udom'};
 2343:     my $usymb = $sheet->{'usymb'};
 2344:     #
 2345:     $sheet->{'rowlabel'} = {};
 2346:     my $identifier =$sheet->{'coursefilename'}.'_'.$stype.'_'.$usymb;
 2347:     #
 2348:     if  ($rowlabel_cache{$identifier}) {
 2349:         %{$sheet->{'rowlabel'}}=split(/___;___/,$rowlabel_cache{$identifier});
 2350:     } else {
 2351:         # Get the data and store it in the cache
 2352:         # Tie hash
 2353:         tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
 2354:             &GDBM_READER(),0640);
 2355:         if (! tied(%course_db)) {
 2356:             return 'Could not access course data';
 2357:         }
 2358:         #
 2359:         my %parameter_labels=
 2360:             ('timestamp' => 
 2361:                  'parameter:Timestamp of Last Transaction<br>timestamp',
 2362:              'subnumber' =>
 2363:                  'parameter:Number of Submissions<br>subnumber',
 2364:              'tutornumber' =>
 2365:                  'parameter:Number of Tutor Responses<br>tutornumber',
 2366:              'totalpoints' =>
 2367:                  'parameter:Total Points Granted<br>totalpoints');
 2368:         while (my ($key,$srcf) = each(%course_db)) {
 2369:             next if ($key !~ /^src_(\d+)\.(\d+)$/);
 2370:             my $mapid = $1;
 2371:             my $resid = $2;
 2372:             my $id   = $mapid.'.'.$resid;
 2373:             if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
 2374:                 # Loop through the metadata for this key
 2375:                 my @Metadata = split(/,/,
 2376:                                      &Apache::lonnet::metadata($srcf,'keys'));
 2377:                 foreach my $key (@Metadata) {
 2378:                     next if ($key !~ /^(stores|parameter)_/);
 2379:                     my $display=
 2380:                         &Apache::lonnet::metadata($srcf,$key.'.display');
 2381:                     unless ($display) {
 2382:                         $display.=
 2383:                             &Apache::lonnet::metadata($srcf,$key.'.name');
 2384:                     }
 2385:                     $display.='<br>'.$key;
 2386:                     $parameter_labels{$key}='parameter:'.$display;
 2387:                 } # end of foreach
 2388:             }
 2389:         }
 2390:         untie(%course_db);
 2391:         # Store away the results
 2392:         $sheet->{'rowlabel'} = \%parameter_labels;
 2393:         $rowlabel_cache{$identifier}=join('___;___',%{$sheet->{'rowlabel'}});
 2394:     }
 2395:         
 2396: }
 2397: 
 2398: sub updatestudentassesssheet {
 2399:     my $sheet = shift;
 2400:     if ($sheet->{'sheettype'} eq 'studentcalc') {
 2401:         &get_student_rowlabels($sheet);
 2402:     } else {
 2403:         &get_assess_rowlabels($sheet);
 2404:     }
 2405:     # Determine if any of the information has changed
 2406:     my %f=&getformulas($sheet);
 2407:     my $changed=0;
 2408:     
 2409:     $sheet->{'maxrow'} = 0;
 2410:     my %existing=();
 2411:     # Now obsolete rows
 2412:     foreach my $cell (keys(%f)) {
 2413:         my $formula = $f{$cell};
 2414:         next if ($cell !~ /^A(\d+)/);
 2415:         $sheet->{'maxrow'} = $1 if ($1 > $sheet->{'maxrow'});
 2416:         my ($usy,$ufn)=split(/__&&&\__/,$formula);
 2417:         $existing{$usy}=1;
 2418:         unless ((exists($sheet->{'rowlabel'}->{$usy}) && 
 2419:                  (defined($sheet->{'rowlabel'}->{$usy})) || (!$1) ||
 2420:                  ($formula =~ /^(~~~|---)/) )) {
 2421:             $f{$cell}='!!! Obsolete';
 2422:             $changed=1;
 2423:         }
 2424:     }
 2425:     # New and unknown keys
 2426:     foreach (keys(%{$sheet->{'rowlabel'}})) {
 2427:         unless ($existing{$_}) {
 2428:             $changed=1;
 2429:             $sheet->{'maxrow'}++;
 2430:             $f{'A'.$sheet->{'maxrow'}}=$_;
 2431:         }
 2432:     }
 2433:     if ($changed) { 
 2434:         $sheet->{'f'} = \%f;
 2435:         &setformulas($sheet); 
 2436:     }
 2437: }
 2438: 
 2439: # ------------------------------------------------ Load data for one assessment
 2440: 
 2441: sub loadstudent{
 2442:     my ($sheet,$r,$c)=@_;
 2443:     my %constants=();
 2444:     my %formulas=&getformulas($sheet);
 2445:     $cachedassess=$sheet->{'uname'}.':'.$sheet->{'udom'};
 2446:     # Get ALL the student preformance data
 2447:     my @tmp = &Apache::lonnet::dump($sheet->{'cid'},
 2448:                                     $sheet->{'udom'},
 2449:                                     $sheet->{'uname'},
 2450:                                     undef);
 2451:     if ($tmp[0] !~ /^error:/) {
 2452:         %cachedstores = @tmp;
 2453:     }
 2454:     undef @tmp;
 2455:     # 
 2456:     my @assessdata=();
 2457:     foreach my $cell (keys(%formulas)) {
 2458:         my $value = $formulas{$cell};
 2459:         if(defined($c) && ($c->aborted())) {
 2460:             last;
 2461:         }
 2462: 	next if ($cell !~ /^A(\d+)/);
 2463:         my $row=$1;
 2464:         next if (($value =~ /^[!~-]/) || ($row==0));
 2465:         my ($usy,$ufn)=split(/__&&&\__/,$value);
 2466:         @assessdata=&exportsheet($sheet,$sheet->{'uname'},
 2467:                                  $sheet->{'udom'},
 2468:                                  'assesscalc',$usy,$ufn,$r);
 2469:         my $index=0;
 2470:         foreach my $col ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 2471:                          'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 2472:             if (defined($assessdata[$index])) {
 2473:                 if ($assessdata[$index]=~/\D/) {
 2474:                     $constants{$col.$row}="'".$assessdata[$index]."'";
 2475:                 } else {
 2476:                     $constants{$col.$row}=$assessdata[$index];
 2477:                 }
 2478:                 $formulas{$col.$row}='import' if ($col ne 'A');
 2479:             }
 2480:             $index++;
 2481:         }
 2482:     }
 2483:     $cachedassess='';
 2484:     undef %cachedstores;
 2485:     $sheet->{'f'} = \%formulas;
 2486:     &setformulas($sheet);
 2487:     &setconstants($sheet,\%constants);
 2488: }
 2489: 
 2490: # --------------------------------------------------- Load data for one student
 2491: #
 2492: sub loadcourse {
 2493:     my ($sheet,$r,$c)=@_;
 2494:     #
 2495:     my %constants=();
 2496:     my %formulas=&getformulas($sheet);
 2497:     #
 2498:     my $total=0;
 2499:     foreach (keys(%formulas)) {
 2500: 	if ($_=~/^A(\d+)/) {
 2501: 	    unless ($formulas{$_}=~/^[\!\~\-]/) { $total++; }
 2502:         }
 2503:     }
 2504:     my $now=0;
 2505:     my $since=time;
 2506:     $r->print(<<ENDPOP);
 2507: <script>
 2508:     popwin=open('','popwin','width=400,height=100');
 2509:     popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
 2510:       '<h3>Spreadsheet Calculation Progress</h3>'+
 2511:       '<form name=popremain>'+
 2512:       '<input type=text size=35 name=remaining value=Starting></form>'+
 2513:       '</body></html>');
 2514:     popwin.document.close();
 2515: </script>
 2516: ENDPOP
 2517:     $r->rflush();
 2518:     foreach (keys(%formulas)) {
 2519:         if(defined($c) && ($c->aborted())) {
 2520:             last;
 2521:         }
 2522: 	next if ($_!~/^A(\d+)/);
 2523:         my $row=$1;
 2524:         next if (($formulas{$_}=~/^[\!\~\-]/)  || ($row==0));
 2525:         my ($sname,$sdom) = split(':',$formulas{$_});
 2526:         my @studentdata=&exportsheet($sheet,$sname,$sdom,'studentcalc',
 2527:                                      undef,undef,$r);
 2528:         undef %userrdatas;
 2529:         $now++;
 2530:         $r->print('<script>popwin.document.popremain.remaining.value="'.
 2531:                   $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
 2532:                   ' secs remaining";</script>');
 2533:         $r->rflush(); 
 2534:         #
 2535:         my $index=0;
 2536:         foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 2537:                  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 2538:             if (defined($studentdata[$index])) {
 2539:                 my $col=$_;
 2540:                 if ($studentdata[$index]=~/\D/) {
 2541:                     $constants{$col.$row}="'".$studentdata[$index]."'";
 2542:                 } else {
 2543:                     $constants{$col.$row}=$studentdata[$index];
 2544:                 }
 2545:                 unless ($col eq 'A') { 
 2546:                     $formulas{$col.$row}='import';
 2547:                 }
 2548:             } 
 2549:             $index++;
 2550:         }
 2551:     }
 2552:     $sheet->{'f'}=\%formulas;
 2553:     &setformulas($sheet);
 2554:     &setconstants($sheet,\%constants);
 2555:     $r->print('<script>popwin.close()</script>');
 2556:     $r->rflush(); 
 2557: }
 2558: 
 2559: # ------------------------------------------------ Load data for one assessment
 2560: #
 2561: sub loadassessment {
 2562:     my ($sheet,$r,$c)=@_;
 2563: 
 2564:     my $uhome = $sheet->{'uhome'};
 2565:     my $uname = $sheet->{'uname'};
 2566:     my $udom  = $sheet->{'udom'};
 2567:     my $symb  = $sheet->{'usymb'};
 2568:     my $cid   = $sheet->{'cid'};
 2569:     my $cnum  = $sheet->{'cnum'};
 2570:     my $cdom  = $sheet->{'cdom'};
 2571:     my $chome = $sheet->{'chome'};
 2572: 
 2573:     my $namespace;
 2574:     unless ($namespace=$cid) { return ''; }
 2575:     # Get stored values
 2576:     my %returnhash=();
 2577:     if ($cachedassess eq $uname.':'.$udom) {
 2578:         #
 2579:         # get data out of the dumped stores
 2580:         # 
 2581:         my $version=$cachedstores{'version:'.$symb};
 2582:         my $scope;
 2583:         for ($scope=1;$scope<=$version;$scope++) {
 2584:             foreach (split(/\:/,$cachedstores{$scope.':keys:'.$symb})) {
 2585:                 $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
 2586:             } 
 2587:         }
 2588:     } else {
 2589:         #
 2590:         # restore individual
 2591:         #
 2592:         %returnhash = &Apache::lonnet::restore($symb,$namespace,$udom,$uname);
 2593:         for (my $version=1;$version<=$returnhash{'version'};$version++) {
 2594:             foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2595:                 $returnhash{$_}=$returnhash{$version.':'.$_};
 2596:             } 
 2597:         }
 2598:     }
 2599:     #
 2600:     # returnhash now has all stores for this resource
 2601:     # convert all "_" to "." to be able to use libraries, multiparts, etc
 2602:     #
 2603:     # This is dumb.  It is also necessary :(
 2604:     my @oldkeys=keys %returnhash;
 2605:     #
 2606:     foreach my $name (@oldkeys) {
 2607:         my $value=$returnhash{$name};
 2608:         delete $returnhash{$name};
 2609:         $name=~s/\_/\./g;
 2610:         $returnhash{$name}=$value;
 2611:     }
 2612:     # initialize coursedata and userdata for this user
 2613:     undef %courseopt;
 2614:     undef %useropt;
 2615: 
 2616:     my $userprefix=$uname.'_'.$udom.'_';
 2617: 
 2618:     unless ($uhome eq 'no_host') { 
 2619:         # Get coursedata
 2620:         unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
 2621:             my %Tmp = &Apache::lonnet::dump('resourcedata',$cdom,$cnum);
 2622:             $courserdatas{$cid}=\%Tmp;
 2623:             $courserdatas{$cid.'.last_cache'}=time;
 2624:         }
 2625:         while (my ($name,$value) = each(%{$courserdatas{$cid}})) {
 2626:             $courseopt{$userprefix.$name}=$value;
 2627:         }
 2628:         # Get userdata (if present)
 2629:         unless ((time-$userrdatas{$uname.'@'.$udom.'.last_cache'})<240) {
 2630:             my %Tmp = &Apache::lonnet::dump('resourcedata',$udom,$uname);
 2631:             $userrdatas{$cid} = \%Tmp;
 2632:             # Most of the time the user does not have a 'resourcedata.db' 
 2633:             # file.  We need to cache that we got nothing instead of bothering
 2634:             # with requesting it every time.
 2635:             $userrdatas{$uname.'@'.$udom.'.last_cache'}=time;
 2636:         }
 2637:         while (my ($name,$value) = each(%{$userrdatas{$cid}})) {
 2638:             $useropt{$userprefix.$name}=$value;
 2639:         }
 2640:     }
 2641:     # now courseopt, useropt initialized for this user and course
 2642:     # (used by parmval)
 2643:     #
 2644:     # Load keys for this assessment only
 2645:     #
 2646:     my %thisassess=();
 2647:     my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
 2648:     foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
 2649:         $thisassess{$_}=1;
 2650:     } 
 2651:     #
 2652:     # Load parameters
 2653:     #
 2654:     my %c=();
 2655:     if (tie(%parmhash,'GDBM_File',
 2656:             $sheet->{'coursefilename'}.'_parms.db',&GDBM_READER(),0640)) {
 2657:         my %f=&getformulas($sheet);
 2658:         foreach my $cell (keys(%f))  {
 2659:             next if ($cell !~ /^A/);
 2660:             next if  ($f{$cell} =~/^[\!\~\-]/);
 2661:             if ($f{$cell}=~/^parameter/) {
 2662:                 if (defined($thisassess{$f{$cell}})) {
 2663:                     my $val       = &parmval($f{$cell},$sheet);
 2664:                     $c{$cell}     = $val;
 2665:                     $c{$f{$cell}} = $val;
 2666:                 }
 2667:             } else {
 2668:                 my $key=$f{$cell};
 2669:                 my $ckey=$key;
 2670:                 $key=~s/^stores\_/resource\./;
 2671:                 $key=~s/\_/\./g;
 2672:                 $c{$cell}=$returnhash{$key};
 2673:                 $c{$ckey}=$returnhash{$key};
 2674:             }
 2675:         }
 2676:         untie(%parmhash);
 2677:     }
 2678:     &setconstants($sheet,\%c);
 2679: }
 2680: 
 2681: # --------------------------------------------------------- Various form fields
 2682: 
 2683: sub textfield {
 2684:     my ($title,$name,$value)=@_;
 2685:     return "\n<p><b>$title:</b><br>".
 2686:         '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
 2687: }
 2688: 
 2689: sub hiddenfield {
 2690:     my ($name,$value)=@_;
 2691:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
 2692: }
 2693: 
 2694: sub selectbox {
 2695:     my ($title,$name,$value,%options)=@_;
 2696:     my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
 2697:     foreach (sort keys(%options)) {
 2698:         $selout.='<option value="'.$_.'"';
 2699:         if ($_ eq $value) { $selout.=' selected'; }
 2700:         $selout.='>'.$options{$_}.'</option>';
 2701:     }
 2702:     return $selout.'</select>';
 2703: }
 2704: 
 2705: # =============================================== Update information in a sheet
 2706: #
 2707: # Add new users or assessments, etc.
 2708: #
 2709: 
 2710: sub updatesheet {
 2711:     my ($sheet)=@_;
 2712:     if ($sheet->{'sheettype'} eq 'classcalc') {
 2713: 	return &updateclasssheet($sheet);
 2714:     } else {
 2715:         return &updatestudentassesssheet($sheet);
 2716:     }
 2717: }
 2718: 
 2719: # =================================================== Load the rows for a sheet
 2720: #
 2721: # Import the data for rows
 2722: #
 2723: 
 2724: sub loadrows {
 2725:     my ($sheet,$r)=@_;
 2726:     my $c = $r->connection;
 2727:     my $stype=$sheet->{'sheettype'};
 2728:     if ($stype eq 'classcalc') {
 2729: 	&loadcourse($sheet,$r,$c);
 2730:     } elsif ($stype eq 'studentcalc') {
 2731:         &loadstudent($sheet,$r,$c);
 2732:     } else {
 2733:         &loadassessment($sheet,$r,$c);
 2734:     }
 2735: }
 2736: 
 2737: # ======================================================= Forced recalculation?
 2738: 
 2739: sub checkthis {
 2740:     my ($keyname,$time)=@_;
 2741:     if (! exists($expiredates{$keyname})) {
 2742:         return 0;
 2743:     } else {
 2744:         return ($time<$expiredates{$keyname});
 2745:     }
 2746: }
 2747: 
 2748: sub forcedrecalc {
 2749:     my ($uname,$udom,$stype,$usymb)=@_;
 2750:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2751:     my $time=$oldsheets{$key.'.time'};
 2752:     if ($ENV{'form.forcerecalc'}) { return 1; }
 2753:     unless ($time) { return 1; }
 2754:     if ($stype eq 'assesscalc') {
 2755:         my $map=(split(/___/,$usymb))[0];
 2756:         if (&checkthis('::assesscalc:',$time) ||
 2757:             &checkthis('::assesscalc:'.$map,$time) ||
 2758:             &checkthis('::assesscalc:'.$usymb,$time) ||
 2759:             &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
 2760:             &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
 2761:             &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
 2762:             return 1;
 2763:         }
 2764:     } else {
 2765:         if (&checkthis('::studentcalc:',$time) || 
 2766:             &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
 2767: 	    return 1;
 2768:         }
 2769:     }
 2770:     return 0; 
 2771: }
 2772: 
 2773: # ============================================================== Export handler
 2774: # exportsheet
 2775: # returns the export row for a spreadsheet.
 2776: #
 2777: sub exportsheet {
 2778:     my ($sheet,$uname,$udom,$stype,$usymb,$fn,$r)=@_;
 2779:     my $flag = 0;
 2780:     $uname = $uname || $sheet->{'uname'};
 2781:     $udom  = $udom  || $sheet->{'udom'};
 2782:     $stype = $stype || $sheet->{'sheettype'};
 2783:     my @exportarr=();
 2784:     # This handles the assessment sheets for '_feedback', etc
 2785:     if (defined($usymb) && ($usymb=~/^\_(\w+)/) && 
 2786:         (!defined($fn) || $fn eq '')) {
 2787:         $fn='default_'.$1;
 2788:     }
 2789:     #
 2790:     # Check if cached
 2791:     #
 2792:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2793:     my $found='';
 2794:     if ($oldsheets{$key}) {
 2795:         foreach (split(/___&\___/,$oldsheets{$key})) {
 2796:             my ($name,$value)=split(/___=___/,$_);
 2797:             if ($name eq $fn) {
 2798:                 $found=$value;
 2799:             }
 2800:         }
 2801:     }
 2802:     unless ($found) {
 2803:         &cachedssheets($sheet,$uname,$udom);
 2804:         if ($oldsheets{$key}) {
 2805:             foreach (split(/___&\___/,$oldsheets{$key})) {
 2806:                 my ($name,$value)=split(/___=___/,$_);
 2807:                 if ($name eq $fn) {
 2808:                     $found=$value;
 2809:                 }
 2810:             } 
 2811:         }
 2812:     }
 2813:     #
 2814:     # Check if still valid
 2815:     #
 2816:     if ($found) {
 2817:         if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
 2818:             $found='';
 2819:         }
 2820:     }
 2821:     if ($found) {
 2822:         #
 2823:         # Return what was cached
 2824:         #
 2825:         @exportarr=split(/___;___/,$found);
 2826:         return @exportarr;
 2827:     }
 2828:     #
 2829:     # Not cached
 2830:     #
 2831:     my ($newsheet)=&makenewsheet($uname,$udom,$stype,$usymb);
 2832:     &readsheet($newsheet,$fn);
 2833:     &updatesheet($newsheet);
 2834:     &loadrows($newsheet,$r);
 2835:     &calcsheet($newsheet); 
 2836:     @exportarr=&exportdata($newsheet);
 2837:     ##
 2838:     ## Store now
 2839:     ##
 2840:     #
 2841:     # load in the old value
 2842:     #
 2843:     my %currentlystored=();
 2844:     if ($stype eq 'studentcalc') {
 2845:         my @tmp = &Apache::lonnet::get('nohist_calculatedsheets',
 2846:                                        [$key],
 2847:                                        $sheet->{'cdom'},$sheet->{'cnum'});
 2848:         if ($tmp[0]!~/^error/) {
 2849:             # We only got one key, so we will access it directly.
 2850:             foreach (split('___&___',$tmp[1])) {
 2851:                 my ($key,$value) = split('___=___',$_);
 2852:                 $key = '' if (! defined($key));
 2853:                 $currentlystored{$key} = $value;
 2854:             }
 2855:         }
 2856:     } else {
 2857:         my @tmp = &Apache::lonnet::get('nohist_calculatedsheets_'.
 2858:                                        $sheet->{'cid'},[$key],
 2859:                                        $sheet->{'udom'},$sheet->{'uname'});
 2860:         if ($tmp[0]!~/^error/) {
 2861:             # We only got one key, so we will access it directly.
 2862:             foreach (split('___&___',$tmp[1])) {
 2863:                 my ($key,$value) = split('___=___',$_);
 2864:                 $key = '' if (! defined($key));
 2865:                 $currentlystored{$key} = $value;
 2866:             }
 2867:         }
 2868:     }
 2869:     #
 2870:     # Add the new line
 2871:     #
 2872:     $currentlystored{$fn}=join('___;___',@exportarr);
 2873:     #
 2874:     # Stick everything back together
 2875:     #
 2876:     my $newstore='';
 2877:     foreach (keys(%currentlystored)) {
 2878:         if ($newstore) { $newstore.='___&___'; }
 2879:         $newstore.=$_.'___=___'.$currentlystored{$_};
 2880:     }
 2881:     my $now=time;
 2882:     #
 2883:     # Store away the new value
 2884:     #
 2885:     my $timekey = $key.'.time';
 2886:     if ($stype eq 'studentcalc') {
 2887:         my $result = &Apache::lonnet::put('nohist_calculatedsheets',
 2888:                                           { $key     => $newstore,
 2889:                                             $timekey => $now },
 2890:                                           $sheet->{'cdom'},
 2891:                                           $sheet->{'cnum'});
 2892:     } else {
 2893:         my $result = &Apache::lonnet::put('nohist_calculatedsheets_'.$sheet->{'cid'},
 2894:                                           { $key     => $newstore,
 2895:                                             $timekey => $now },
 2896:                                           $sheet->{'udom'},
 2897:                                           $sheet->{'uname'});
 2898:     }
 2899:     return @exportarr;
 2900: }
 2901: 
 2902: # ============================================================ Expiration Dates
 2903: #
 2904: # Load previously cached student spreadsheets for this course
 2905: #
 2906: sub load_spreadsheet_expirationdates {
 2907:     undef %expiredates;
 2908:     my $cid=$ENV{'request.course.id'};
 2909:     my @tmp = &Apache::lonnet::dump('nohist_expirationdates',
 2910:                                     $ENV{'course.'.$cid.'.domain'},
 2911:                                     $ENV{'course.'.$cid.'.num'});
 2912:     if (lc($tmp[0]) !~ /^error/){
 2913:         %expiredates = @tmp;
 2914:     }
 2915: }
 2916: 
 2917: # ===================================================== Calculated sheets cache
 2918: #
 2919: # Load previously cached student spreadsheets for this course
 2920: #
 2921: 
 2922: sub cachedcsheets {
 2923:     my $cid=$ENV{'request.course.id'};
 2924:     my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets',
 2925:                                     $ENV{'course.'.$cid.'.domain'},
 2926:                                     $ENV{'course.'.$cid.'.num'});
 2927:     if ($tmp[0] !~ /^error/) {
 2928:         my %StupidTempHash = @tmp;
 2929:         while (my ($key,$value) = each %StupidTempHash) {
 2930:             $oldsheets{$key} = $value;
 2931:         }
 2932:     }
 2933: }
 2934: 
 2935: # ===================================================== Calculated sheets cache
 2936: #
 2937: # Load previously cached assessment spreadsheets for this student
 2938: #
 2939: 
 2940: sub cachedssheets {
 2941:     my ($sheet,$uname,$udom) = @_;
 2942:     $uname = $uname || $sheet->{'uname'};
 2943:     $udom  = $udom  || $sheet->{'udom'};
 2944:     if (! $loadedcaches{$uname.'_'.$udom}) {
 2945:         my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets_'.
 2946:                                         $ENV{'request.course.id'},
 2947:                                         $sheet->{'udom'},
 2948:                                         $sheet->{'uname'});
 2949:         if ($tmp[0] !~ /^error/) {
 2950:             my %TempHash = @tmp;
 2951:             my $count = 0;
 2952:             while (my ($key,$value) = each %TempHash) {
 2953:                 $oldsheets{$key} = $value;
 2954:                 $count++;
 2955:             }
 2956:             $loadedcaches{$sheet->{'uname'}.'_'.$sheet->{'udom'}}=1;
 2957:         }
 2958:     }
 2959:     
 2960: }
 2961: 
 2962: # ===================================================== Calculated sheets cache
 2963: #
 2964: # Load previously cached assessment spreadsheets for this student
 2965: #
 2966: 
 2967: # ================================================================ Main handler
 2968: #
 2969: # Interactive call to screen
 2970: #
 2971: #
 2972: sub handler {
 2973:     my $r=shift;
 2974: 
 2975:     my ($sheettype) = ($r->uri=~/\/(\w+)$/);
 2976: 
 2977:     if (! exists($ENV{'form.Status'})) {
 2978:         $ENV{'form.Status'} = 'Active';
 2979:     }
 2980:     if ( ! exists($ENV{'form.output'}) || 
 2981:              ($sheettype ne 'classcalc' && 
 2982:               lc($ENV{'form.output'}) eq 'recursive excel')) {
 2983:         $ENV{'form.output'} = 'HTML';
 2984:     }
 2985:     #
 2986:     # Overload checking
 2987:     #
 2988:     # Check this server
 2989:     my $loaderror=&Apache::lonnet::overloaderror($r);
 2990:     if ($loaderror) { return $loaderror; }
 2991:     # Check the course homeserver
 2992:     $loaderror= &Apache::lonnet::overloaderror($r,
 2993:                       $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
 2994:     if ($loaderror) { return $loaderror; } 
 2995:     #
 2996:     # HTML Header
 2997:     #
 2998:     if ($r->header_only) {
 2999:         $r->content_type('text/html');
 3000:         $r->send_http_header;
 3001:         return OK;
 3002:     }
 3003:     #
 3004:     # Global directory configs
 3005:     #
 3006:     $includedir = $r->dir_config('lonIncludes');
 3007:     $tmpdir = $r->dir_config('lonDaemons').'/tmp/';
 3008:     #
 3009:     # Roles Checking
 3010:     #
 3011:     # Needs to be in a course
 3012:     if (! $ENV{'request.course.fn'}) { 
 3013:         # Not in a course, or not allowed to modify parms
 3014:         $ENV{'user.error.msg'}=
 3015:             $r->uri.":opa:0:0:Cannot modify spreadsheet";
 3016:         return HTTP_NOT_ACCEPTABLE; 
 3017:     }
 3018:     #
 3019:     # Get query string for limited number of parameters
 3020:     #
 3021:     &Apache::loncommon::get_unprocessed_cgi
 3022:         ($ENV{'QUERY_STRING'},['uname','udom','usymb','ufn','mapid','resid']);
 3023:     #
 3024:     # Deal with restricted student permissions 
 3025:     #
 3026:     if ($ENV{'request.role'} =~ /^st\./) {
 3027:         delete $ENV{'form.unewfield'}   if (exists($ENV{'form.unewfield'}));
 3028:         delete $ENV{'form.unewformula'} if (exists($ENV{'form.unewformula'}));
 3029:     }
 3030:     #
 3031:     # Look for special assessment spreadsheets - '_feedback', etc.
 3032:     #
 3033:     if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'} || 
 3034:                                              $ENV{'form.ufn'} eq '' || 
 3035:                                              $ENV{'form.ufn'} eq 'default')) {
 3036:         $ENV{'form.ufn'}='default_'.$1;
 3037:     }
 3038: #    if (!$ENV{'form.ufn'} || $ENV{'form.ufn'} eq 'default') {
 3039: #        $ENV{'form.ufn'}='course_default_'.$sheettype;
 3040: #    }
 3041:     #
 3042:     # Interactive loading of specific sheet?
 3043:     #
 3044:     if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
 3045:         $ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
 3046:     }
 3047:     #
 3048:     # Determine the user name and domain for the sheet.
 3049:     my $aname;
 3050:     my $adom;
 3051:     unless ($ENV{'form.uname'}) {
 3052:         $aname=$ENV{'user.name'};
 3053:         $adom=$ENV{'user.domain'};
 3054:     } else {
 3055:         $aname=$ENV{'form.uname'};
 3056:         $adom=$ENV{'form.udom'};
 3057:     }
 3058:     #
 3059:     # Open page, try to prevent browser cache.
 3060:     #
 3061:     $r->content_type('text/html');
 3062:     $r->header_out('Cache-control','no-cache');
 3063:     $r->header_out('Pragma','no-cache');
 3064:     $r->send_http_header;
 3065:     #
 3066:     # Header....
 3067:     #
 3068:     $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
 3069:     my $nothing = "''";
 3070:     if ($ENV{'browser.type'} eq 'explorer') {
 3071:         $nothing = "'javascript:void(0);'";
 3072:     }
 3073: 
 3074:     if ($ENV{'request.role'} !~ /^st\./) {
 3075:         $r->print(<<ENDSCRIPT);
 3076: <script language="JavaScript">
 3077: 
 3078:     var editwin;
 3079: 
 3080:     function celledit(cellname,cellformula) {
 3081:         var edit_text = '';
 3082:         // cellformula may contain less-than and greater-than symbols, so
 3083:         // we need to escape them?  
 3084:         edit_text +='<html><head><title>Cell Edit Window</title></head><body>';
 3085:         edit_text += '<form name="editwinform">';
 3086:         edit_text += '<center><h3>Cell '+cellname+'</h3>';
 3087:         edit_text += '<textarea name="newformula" cols="40" rows="6"';
 3088:         edit_text += ' wrap="off" >'+cellformula+'</textarea>';
 3089:         edit_text += '</br>';
 3090:         edit_text += '<input type="button" name="accept" value="Accept"';
 3091:         edit_text += ' onClick=\\\'javascript:';
 3092:         edit_text += 'opener.document.sheet.unewfield.value=';
 3093:         edit_text +=     '"'+cellname+'";';
 3094:         edit_text += 'opener.document.sheet.unewformula.value=';
 3095:         edit_text +=     'document.editwinform.newformula.value;';
 3096:         edit_text += 'opener.document.sheet.submit();';
 3097:         edit_text += 'self.close()\\\' />';
 3098:         edit_text += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
 3099:         edit_text += '<input type="button" name="abort" ';
 3100:         edit_text +=     'value="Discard Changes"';
 3101:         edit_text += ' onClick="javascript:self.close()" />';
 3102:         edit_text += '</center></body></html>';
 3103: 
 3104:         if (editwin != null && !(editwin.closed) ) {
 3105:             editwin.close();
 3106:         }
 3107: 
 3108:         editwin = window.open($nothing,'CellEditWin','height=200,width=350,scrollbars=no,resizeable=yes,alwaysRaised=yes,dependent=yes',true);
 3109:         editwin.document.write(edit_text);
 3110:     }
 3111: 
 3112:     function changesheet(cn) {
 3113: 	document.sheet.unewfield.value=cn;
 3114:         document.sheet.unewformula.value='changesheet';
 3115:         document.sheet.submit();
 3116:     }
 3117: 
 3118:     function insertrow(cn) {
 3119: 	document.sheet.unewfield.value='insertrow';
 3120:         document.sheet.unewformula.value=cn;
 3121:         document.sheet.submit();
 3122:     }
 3123: 
 3124: </script>
 3125: ENDSCRIPT
 3126:     }
 3127:     $r->print('</head>'.&Apache::loncommon::bodytag('Grades Spreadsheet').
 3128:               '<form action="'.$r->uri.'" name="sheet" method="post">');
 3129:     $r->print(&hiddenfield('uname',$ENV{'form.uname'}).
 3130:               &hiddenfield('udom',$ENV{'form.udom'}).
 3131:               &hiddenfield('usymb',$ENV{'form.usymb'}).
 3132:               &hiddenfield('unewfield','').
 3133:               &hiddenfield('unewformula',''));
 3134:     $r->rflush();
 3135:     #
 3136:     # Full recalc?
 3137:     #
 3138:     if ($ENV{'form.forcerecalc'}) {
 3139:         $r->print('<h4>Completely Recalculating Sheet ...</h4>');
 3140:         undef %spreadsheets;
 3141:         undef %courserdatas;
 3142:         undef %userrdatas;
 3143:         undef %defaultsheets;
 3144:         undef %rowlabel_cache;
 3145:     }
 3146:     # Read new sheet or modified worksheet
 3147:     my ($sheet)=&makenewsheet($aname,$adom,$sheettype,$ENV{'form.usymb'});
 3148:     #
 3149:     # Check user permissions
 3150:     if (($sheet->{'sheettype'} eq 'classcalc'       ) || 
 3151:         ($sheet->{'uname'}     ne $ENV{'user.name'} ) ||
 3152:         ($sheet->{'udom'}      ne $ENV{'user.domain'})) {
 3153:         unless (&Apache::lonnet::allowed('vgr',$sheet->{'cid'})) {
 3154:             $r->print('<h1>Access Permission Denied</h1>'.
 3155:                       '</form></body></html>');
 3156:             return OK;
 3157:         }
 3158:     }
 3159:     # Print out user information
 3160:     $r->print('<h2>'.$sheet->{'coursedesc'}.'</h2>');
 3161:     if ($sheet->{'sheettype'} ne 'classcalc') {
 3162:         $r->print('<h2>'.&gettitle($sheet).'</h2><p>');
 3163:     }
 3164:     if ($sheet->{'sheettype'} eq 'assesscalc') {
 3165:         $r->print('<b>User:</b> '.$sheet->{'uname'}.
 3166:                   '<br /><b>Domain:</b> '.$sheet->{'udom'}.'<br />');
 3167:     }
 3168:     if ($sheet->{'sheettype'} eq 'studentcalc' || 
 3169:         $sheet->{'sheettype'} eq 'assesscalc') {
 3170:         $r->print('<b>Section/Group:</b>'.$sheet->{'csec'}.'</p>');
 3171:     } 
 3172:     #
 3173:     # If a new formula had been entered, go from work copy
 3174:     if ($ENV{'form.unewfield'}) {
 3175:         $r->print('<h2>Modified Workcopy</h2>');
 3176:         #$ENV{'form.unewformula'}=~s/\'/\"/g;
 3177:         $r->print('<p>Cell '.$ENV{'form.unewfield'}.' = <pre>');
 3178:         $r->print(&HTML::Entities::encode($ENV{'form.unewformula'}).
 3179:                   '</pre></p>');
 3180:         $sheet->{'filename'} = $ENV{'form.ufn'};
 3181:         &tmpread($sheet,$ENV{'form.unewfield'},$ENV{'form.unewformula'});
 3182:     } elsif ($ENV{'form.saveas'}) {
 3183:         $sheet->{'filename'} = $ENV{'form.ufn'};
 3184:         &tmpread($sheet);
 3185:     } else {
 3186:         &readsheet($sheet,$ENV{'form.ufn'});
 3187:     }
 3188:     # Additional options
 3189:     if ($sheet->{'sheettype'} eq 'assesscalc') {
 3190:         $r->print('<p><font size=+2>'.
 3191:                   '<a href="/adm/studentcalc?'.
 3192:                   'uname='.$sheet->{'uname'}.
 3193:                   '&udom='.$sheet->{'udom'}.'">'.
 3194:                   'Level up: Student Sheet</a></font></p>');
 3195:     }
 3196:     if (($sheet->{'sheettype'} eq 'studentcalc') && 
 3197:         (&Apache::lonnet::allowed('vgr',$sheet->{'cid'}))) {
 3198:         $r->print ('<p><font size=+2><a href="/adm/classcalc">'.
 3199:                    'Level up: Course Sheet</a></font></p>');
 3200:     }
 3201:     # Recalc button
 3202:     $r->print('<br />'.
 3203:               '<input type="submit" name="forcerecalc" '.
 3204:               'value="Completely Recalculate Sheet"></p>');
 3205:     # Save dialog
 3206:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 3207:         my $fname=$ENV{'form.ufn'};
 3208:         $fname=~s/\_[^\_]+$//;
 3209:         if ($fname eq 'default') { $fname='course_default'; }
 3210:         $r->print('<input type=submit name=saveas value="Save as ...">'.
 3211:                   '<input type=text size=20 name=newfn value="'.$fname.'">'.
 3212:                   'make default: <input type=checkbox name="makedefufn"><p>');
 3213:     }
 3214:     $r->print(&hiddenfield('ufn',$sheet->{'filename'}));
 3215:     # Load dialog
 3216:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 3217:         $r->print('<p><input type=submit name=load value="Load ...">'.
 3218:                   '<select name="loadthissheet">'.
 3219:                   '<option name="default">Default</option>');
 3220:         foreach (&othersheets($sheet)) {
 3221:             $r->print('<option name="'.$_.'"');
 3222:             if ($ENV{'form.ufn'} eq $_) {
 3223:                 $r->print(' selected');
 3224:             }
 3225:             $r->print('>'.$_.'</option>');
 3226:         } 
 3227:         $r->print('</select><p>');
 3228:         if ($sheet->{'sheettype'} eq 'studentcalc') {
 3229:             &setothersheets($sheet,
 3230:                             &othersheets($sheet,'assesscalc'));
 3231:         }
 3232:     }
 3233:     #
 3234:     # Set up caching mechanisms
 3235:     #
 3236:     &load_spreadsheet_expirationdates();
 3237:     # Clear out old caches if we have not seen this class before.
 3238:     if (exists($oldsheets{'course'}) &&
 3239:         $oldsheets{'course'} ne $sheet->{'cid'}) {
 3240:         undef %oldsheets;
 3241:         undef %loadedcaches;
 3242:         undef %Section;
 3243:     }
 3244:     $oldsheets{'course'} = $sheet->{'cid'};
 3245:     #
 3246:     if ($sheet->{'sheettype'} eq 'classcalc') {
 3247:         $r->print("Loading previously calculated student sheets ...\n");
 3248:         $r->rflush();
 3249:         &cachedcsheets();
 3250:     } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
 3251:         $r->print("Loading previously calculated assessment sheets ...\n");
 3252:         $r->rflush();
 3253:         &cachedssheets($sheet);
 3254:     }
 3255:     # Update sheet, load rows
 3256:     $r->print("Loaded sheet(s), updating rows ...<br>\n");
 3257:     $r->rflush();
 3258:     #
 3259:     &updatesheet($sheet);
 3260:     $r->print("Updated rows, loading row data ...\n");
 3261:     $r->rflush();
 3262:     #
 3263:     &loadrows($sheet,$r);
 3264:     $r->print("Loaded row data, calculating sheet ...<br>\n");
 3265:     $r->rflush();
 3266:     #
 3267:     my $calcoutput=&calcsheet($sheet);
 3268:     $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
 3269:     # See if something to save
 3270:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 3271:         my $fname='';
 3272:         if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
 3273:             $fname=~s/\W/\_/g;
 3274:             if ($fname eq 'default') { $fname='course_default'; }
 3275:             $fname.='_'.$sheet->{'sheettype'};
 3276:             $sheet->{'filename'} = $fname;
 3277:             $ENV{'form.ufn'}=$fname;
 3278:             $r->print('<p>Saving spreadsheet: '.
 3279:                       &writesheet($sheet,$ENV{'form.makedefufn'}).
 3280:                       '<p>');
 3281:         }
 3282:     }
 3283:     #
 3284:     # Write the modified worksheet
 3285:     $r->print('<b>Current sheet:</b> '.$sheet->{'filename'}.'</p>');
 3286:     &tmpwrite($sheet);
 3287:     if ($sheet->{'sheettype'} eq 'assesscalc') {
 3288:         $r->print('<p>Show rows with empty A column: ');
 3289:     } else {
 3290:         $r->print('<p>Show empty rows: ');
 3291:     }
 3292:     #
 3293:     $r->print(&hiddenfield('userselhidden','true').
 3294:               '<input type="checkbox" name="showall" onClick="submit()"');
 3295:     #
 3296:     if ($ENV{'form.showall'}) { 
 3297:         $r->print(' checked'); 
 3298:     } else {
 3299:         unless ($ENV{'form.userselhidden'}) {
 3300:             unless 
 3301:                 ($ENV{'course.'.$sheet->{'cid'}.'.hideemptyrows'} eq 'yes') {
 3302:                     $r->print(' checked');
 3303:                     $ENV{'form.showall'}=1;
 3304:                 }
 3305:         }
 3306:     }
 3307:     $r->print('>');
 3308:     #
 3309:     # output format select box 
 3310:     $r->print(' Output as <select name="output" size="1" onChange="submit()">'.
 3311:               "\n");
 3312:     foreach my $mode (qw/HTML CSV Excel/) {
 3313:         $r->print('<option value="'.$mode.'"');
 3314:         if ($ENV{'form.output'} eq $mode) {
 3315:             $r->print(' selected ');
 3316:         } 
 3317:         $r->print('>'.$mode.'</option>'."\n");
 3318:     }
 3319: #
 3320: #    Mulit-sheet excel takes too long and does not work at all for large
 3321: #    classes.  Future inclusion of this option may be possible with the
 3322: #    Spreadsheet::WriteExcel::Big and speed improvements.
 3323: #
 3324: #    if ($sheet->{'sheettype'} eq 'classcalc') {
 3325: #        $r->print('<option value="recursive excel"');
 3326: #        if ($ENV{'form.output'} eq 'recursive excel') {
 3327: #            $r->print(' selected ');
 3328: #        } 
 3329: #        $r->print(">Multi-Sheet Excel</option>\n");
 3330: #    }
 3331:     $r->print("</select>\n");
 3332:     #
 3333:     if ($sheet->{'sheettype'} eq 'classcalc') {
 3334:         $r->print('&nbsp;Student Status: '.
 3335:                   &Apache::lonhtmlcommon::StatusOptions
 3336:                   ($ENV{'form.Status'},'sheet'));
 3337:     }
 3338:     #
 3339:     # Buttons to insert rows
 3340: #    $r->print(<<ENDINSERTBUTTONS);
 3341: #<br>
 3342: #<input type='button' onClick='insertrow("top");' 
 3343: #value='Insert Row Top'>
 3344: #<input type='button' onClick='insertrow("bottom");' 
 3345: #value='Insert Row Bottom'><br>
 3346: #ENDINSERTBUTTONS
 3347:     # Print out sheet
 3348:     &outsheet($sheet,$r);
 3349:     $r->print('</form></body></html>');
 3350:     #  Done
 3351:     return OK;
 3352: }
 3353: 
 3354: 1;
 3355: __END__
 3356: 
 3357: 

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