File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.89: download - view: text, annotated - select for diffs
Tue May 7 18:10:55 2002 UTC (22 years, 3 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
Changed to use get_unprocessed_cgi.  BUG 90.

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

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