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

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

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