Annotation of loncom/interface/lonspreadsheet.pm, revision 1.129

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

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