File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.141: download - view: text, annotated - select for diffs
Fri Nov 15 18:59:28 2002 UTC (21 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Bugfix: 'Hide empty rows' now works.

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

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