File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.121: download - view: text, annotated - select for diffs
Tue Oct 22 13:13:15 2002 UTC (21 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Removed safe space function exportrowa.

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

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