File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.87: download - view: text, annotated - select for diffs
Thu Apr 18 20:21:38 2002 UTC (22 years, 2 months ago) by matthew
Branches: MAIN
CVS tags: stable_2002_april, HEAD
Removed subroutines to send internal messages.

    1: #
    2: # $Id: lonspreadsheet.pm,v 1.87 2002/04/18 20:21:38 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:         return '$c{\''.$expression.'\'}';
  746:     }
  747: }
  748: 
  749: sub sett {
  750:     %t=();
  751:     my $pattern='';
  752:     if ($sheettype eq 'assesscalc') {
  753: 	$pattern='A';
  754:     } else {
  755:         $pattern='[A-Z]';
  756:     }
  757:     foreach (keys(%f)) {
  758: 	if ($_=~/template\_(\w)/) {
  759: 	  my $col=$1;
  760:           unless ($col=~/^$pattern/) {
  761: 	    foreach (keys(%f)) {
  762: 	      if ($_=~/A(\d+)/) {
  763: 		my $trow=$1;
  764:                 if ($trow) {
  765: 		    my $lb=$col.$trow;
  766:                     $t{$lb}=$f{'template_'.$col};
  767:                     $t{$lb}=~s/\#/$trow/g;
  768:                     $t{$lb}=~s/\.\.+/\,/g;
  769:                     $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
  770:                     $t{$lb}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  771:                 }
  772: 	      }
  773: 	    }
  774: 	  }
  775:       }
  776:     }
  777:     foreach (keys(%f)) {
  778: 	if (($f{$_}) && ($_!~/template\_/)) {
  779:             my $matches=($_=~/^$pattern(\d+)/);
  780:             if  (($matches) && ($1)) {
  781: 	        unless ($f{$_}=~/^\!/) {
  782: 		    $t{$_}=$c{$_};
  783:                 }
  784:             } else {
  785: 	       $t{$_}=$f{$_};
  786:                $t{$_}=~s/\.\.+/\,/g;
  787:                $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
  788:                $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  789:             }
  790:         }
  791:     }
  792:     $t{'A0'}=$f{'A0'};
  793:     $t{'A0'}=~s/\.\.+/\,/g;
  794:     $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$v\{\'$2\'\}/g;
  795:     $t{'A0'}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
  796: }
  797: 
  798: sub calc {
  799:     %v=();
  800:     &sett();
  801:     my $notfinished=1;
  802:     my $depth=0;
  803:     while ($notfinished) {
  804: 	$notfinished=0;
  805:         foreach (keys(%t)) {
  806:             my $old=$v{$_};
  807:             $v{$_}=eval($t{$_});
  808: 	    if ($@) {
  809: 		%v=();
  810:                 return $@;
  811:             }
  812: 	    if ($v{$_} ne $old) { $notfinished=1; }
  813:         }
  814:         $depth++;
  815:         if ($depth>100) {
  816: 	    %v=();
  817:             return 'Maximum calculation depth exceeded';
  818:         }
  819:     }
  820:     return '';
  821: }
  822: 
  823: sub templaterow {
  824:     my @cols=();
  825:     $cols[0]='<b><font size=+1>Template</font></b>';
  826:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  827: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  828: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
  829: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
  830:         my $fm=$f{'template_'.$_};
  831:         $fm=~s/[\'\"]/\&\#34;/g;
  832:         $cols[$#cols+1]="'template_$_','$fm'".'___eq___'.$fm;
  833:     }
  834:     return @cols;
  835: }
  836: 
  837: sub outrowassess {
  838:     my $n=shift;
  839:     my @cols=();
  840:     if ($n) {
  841:        my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{'A'.$n});
  842:        $cols[0]=$rl{$usy}.'<br>'.
  843:                 '<select name="sel_'.$n.'" onChange="changesheet('.$n.
  844:                 ')"><option name="default">Default</option>';
  845:        foreach (@os) {
  846:            $cols[0].='<option name="'.$_.'"';
  847:             if ($ufn eq $_) {
  848:                $cols[0].=' selected';
  849:             }
  850:             $cols[0].='>'.$_.'</option>';
  851:        }
  852:        $cols[0].='</select>';
  853:     } else {
  854:        $cols[0]='<b><font size=+1>Export</font></b>';
  855:     }
  856:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  857: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  858: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
  859: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
  860:         my $fm=$f{$_.$n};
  861:         $fm=~s/[\'\"]/\&\#34;/g;
  862:         push(@cols,"'$_$n','$fm'".'___eq___'.$v{$_.$n});
  863:     }
  864:     return @cols;
  865: }
  866: 
  867: sub outrow {
  868:     my $n=shift;
  869:     my @cols=();
  870:     if ($n) {
  871:        $cols[0]=$rl{$f{'A'.$n}};
  872:     } else {
  873:        $cols[0]='<b><font size=+1>Export</font></b>';
  874:     }
  875:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  876: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  877: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
  878: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
  879:         my $fm=$f{$_.$n};
  880:         $fm=~s/[\'\"]/\&\#34;/g;
  881:         $cols[$#cols+1]="'$_$n','$fm'".'___eq___'.$v{$_.$n};
  882:     }
  883:     return @cols;
  884: }
  885: 
  886: sub exportrowa {
  887:     my @exportarray=();
  888:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  889: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
  890: 	$exportarray[$#exportarray+1]=$v{$_.'0'};
  891:     } 
  892:     return @exportarray;
  893: }
  894: 
  895: # ------------------------------------------- End of "Inside of the safe space"
  896: ENDDEFS
  897:     $safeeval->reval($code);
  898:     return $safeeval;
  899: }
  900: 
  901: # ------------------------------------------------ Add or change formula values
  902: 
  903: sub setformulas {
  904:     my ($safeeval,%f)=@_;
  905:     %{$safeeval->varglob('f')}=%f;
  906: }
  907: 
  908: # ------------------------------------------------ Add or change formula values
  909: 
  910: sub setconstants {
  911:     my ($safeeval,%c)=@_;
  912:     %{$safeeval->varglob('c')}=%c;
  913: }
  914: 
  915: # --------------------------------------------- Set names of other spreadsheets
  916: 
  917: sub setothersheets {
  918:     my ($safeeval,@os)=@_;
  919:     @{$safeeval->varglob('os')}=@os;
  920: }
  921: 
  922: # ------------------------------------------------ Add or change formula values
  923: 
  924: sub setrowlabels {
  925:     my ($safeeval,%rl)=@_;
  926:     %{$safeeval->varglob('rl')}=%rl;
  927: }
  928: 
  929: # ------------------------------------------------------- Calculate spreadsheet
  930: 
  931: sub calcsheet {
  932:     my $safeeval=shift;
  933:     $safeeval->reval('&calc();');
  934: }
  935: 
  936: # ------------------------------------------------------------------ Get values
  937: 
  938: sub getvalues {
  939:     my $safeeval=shift;
  940:     return $safeeval->reval('%v');
  941: }
  942: 
  943: # ---------------------------------------------------------------- Get formulas
  944: 
  945: sub getformulas {
  946:     my $safeeval=shift;
  947:     return %{$safeeval->varglob('f')};
  948: }
  949: 
  950: # -------------------------------------------------------------------- Get type
  951: 
  952: sub gettype {
  953:     my $safeeval=shift;
  954:     return $safeeval->reval('$sheettype');
  955: }
  956: 
  957: # ------------------------------------------------------------------ Set maxrow
  958: 
  959: sub setmaxrow {
  960:     my ($safeeval,$row)=@_;
  961:     $safeeval->reval('$maxrow='.$row.';');
  962: }
  963: 
  964: # ------------------------------------------------------------------ Get maxrow
  965: 
  966: sub getmaxrow {
  967:     my $safeeval=shift;
  968:     return $safeeval->reval('$maxrow');
  969: }
  970: 
  971: # ---------------------------------------------------------------- Set filename
  972: 
  973: sub setfilename {
  974:     my ($safeeval,$fn)=@_;
  975:     $safeeval->reval('$filename="'.$fn.'";');
  976: }
  977: 
  978: # ---------------------------------------------------------------- Get filename
  979: 
  980: sub getfilename {
  981:     my $safeeval=shift;
  982:     return $safeeval->reval('$filename');
  983: }
  984: 
  985: # --------------------------------------------------------------- Get course ID
  986: 
  987: sub getcid {
  988:     my $safeeval=shift;
  989:     return $safeeval->reval('$cid');
  990: }
  991: 
  992: # --------------------------------------------------------- Get course filename
  993: 
  994: sub getcfn {
  995:     my $safeeval=shift;
  996:     return $safeeval->reval('$cfn');
  997: }
  998: 
  999: # ----------------------------------------------------------- Get course number
 1000: 
 1001: sub getcnum {
 1002:     my $safeeval=shift;
 1003:     return $safeeval->reval('$cnum');
 1004: }
 1005: 
 1006: # ------------------------------------------------------------- Get course home
 1007: 
 1008: sub getchome {
 1009:     my $safeeval=shift;
 1010:     return $safeeval->reval('$chome');
 1011: }
 1012: 
 1013: # ----------------------------------------------------------- Get course domain
 1014: 
 1015: sub getcdom {
 1016:     my $safeeval=shift;
 1017:     return $safeeval->reval('$cdom');
 1018: }
 1019: 
 1020: # ---------------------------------------------------------- Get course section
 1021: 
 1022: sub getcsec {
 1023:     my $safeeval=shift;
 1024:     return $safeeval->reval('$csec');
 1025: }
 1026: 
 1027: # --------------------------------------------------------------- Get user name
 1028: 
 1029: sub getuname {
 1030:     my $safeeval=shift;
 1031:     return $safeeval->reval('$uname');
 1032: }
 1033: 
 1034: # ------------------------------------------------------------- Get user domain
 1035: 
 1036: sub getudom {
 1037:     my $safeeval=shift;
 1038:     return $safeeval->reval('$udom');
 1039: }
 1040: 
 1041: # --------------------------------------------------------------- Get user home
 1042: 
 1043: sub getuhome {
 1044:     my $safeeval=shift;
 1045:     return $safeeval->reval('$uhome');
 1046: }
 1047: 
 1048: # -------------------------------------------------------------------- Get symb
 1049: 
 1050: sub getusymb {
 1051:     my $safeeval=shift;
 1052:     return $safeeval->reval('$usymb');
 1053: }
 1054: 
 1055: # ------------------------------------------------------------- Export of A-row
 1056: 
 1057: sub exportdata {
 1058:     my $safeeval=shift;
 1059:     return $safeeval->reval('&exportrowa()');
 1060: }
 1061: 
 1062: 
 1063: # ========================================================== End of Spreadsheet
 1064: # =============================================================================
 1065: 
 1066: #
 1067: # Procedures for screen output
 1068: #
 1069: # --------------------------------------------- Produce output row n from sheet
 1070: 
 1071: sub rown {
 1072:     my ($safeeval,$n)=@_;
 1073:     my $defaultbg;
 1074:     my $rowdata='';
 1075:     my $dataflag=0;
 1076:     unless ($n eq '-') {
 1077:        $defaultbg=((($n-1)/5)==int(($n-1)/5))?'#E0E0':'#FFFF';
 1078:     } else {
 1079:        $defaultbg='#E0FF';
 1080:     }
 1081:     unless ($ENV{'form.showcsv'}) {
 1082:        $rowdata.="\n<tr><td><b><font size=+1>$n</font></b></td>";
 1083:     } else {
 1084:        $rowdata.="\n".'"'.$n.'"';
 1085:     }
 1086:     my $showf=0;
 1087:     my $proc;
 1088:     my $maxred;
 1089:     my $sheettype=&gettype($safeeval);
 1090:     if ($sheettype eq 'studentcalc') {
 1091:         $proc='&outrowassess';
 1092:         $maxred=26;
 1093:     } else {
 1094:         $proc='&outrow';
 1095:     }
 1096:     if ($sheettype eq 'assesscalc') {
 1097:         $maxred=1;
 1098:     } else {
 1099:         $maxred=26;
 1100:     }
 1101:     if ($n eq '-') { $proc='&templaterow'; $n=-1; $dataflag=1; }
 1102:     foreach ($safeeval->reval($proc.'('.$n.')')) {
 1103:        my $bgcolor=$defaultbg.((($showf-1)/5==int(($showf-1)/5))?'99':'DD');
 1104:        my ($fm,$vl)=split(/\_\_\_eq\_\_\_/,$_);
 1105:        if ((($vl ne '') || ($vl eq '0')) &&
 1106:            (($showf==1) || ($sheettype ne 'studentcalc'))) { $dataflag=1; }
 1107:        if ($showf==0) { $vl=$_; }
 1108:       unless ($ENV{'form.showcsv'}) {
 1109:        if ($showf<=$maxred) { $bgcolor='#FFDDDD'; }
 1110:        if (($n==0) && ($showf<=26)) { $bgcolor='#CCCCFF'; } 
 1111:        if (($showf>$maxred) || ((!$n) && ($showf>0))) {
 1112: 	   if ($vl eq '') {
 1113: 	       $vl='<font size=+2 color='.$bgcolor.'>&#35;</font>';
 1114:            }
 1115:            $rowdata.=
 1116:        '<td bgcolor='.$bgcolor.'><a href="javascript:celledit('.$fm.');">'.$vl.
 1117: 	       '</a></td>';
 1118:        } else {
 1119:            $rowdata.='<td bgcolor='.$bgcolor.'>&nbsp;'.$vl.'&nbsp;</td>';
 1120:        }
 1121:       } else {
 1122: 	  $rowdata.=',"'.$vl.'"';
 1123:       }
 1124:        $showf++;
 1125:     }  # End of foreach($safeval...)
 1126:     if ($ENV{'form.showall'} || ($dataflag)) {
 1127:        return $rowdata.($ENV{'form.showcsv'}?'':'</tr>');
 1128:     } else {
 1129:        return '';
 1130:     }
 1131: }
 1132: 
 1133: # ------------------------------------------------------------- Print out sheet
 1134: 
 1135: sub outsheet {
 1136:     my ($r,$safeeval)=@_;
 1137:     my $maxred;
 1138:     my $realm;
 1139:     if (&gettype($safeeval) eq 'assesscalc') {
 1140:         $maxred=1;
 1141:         $realm='Assessment';
 1142:     } elsif (&gettype($safeeval) eq 'studentcalc') {
 1143:         $maxred=26;
 1144:         $realm='User';
 1145:     } else {
 1146:         $maxred=26;
 1147:         $realm='Course';
 1148:     }
 1149:     my $maxyellow=52-$maxred;
 1150:     my $tabledata;
 1151:     unless ($ENV{'form.showcsv'}) {
 1152:        $tabledata=
 1153:         '<table border=2><tr><th colspan=2 rowspan=2><font size=+2>'.
 1154:                   $realm.'</font></th>'.
 1155:                   '<td bgcolor=#FFDDDD colspan='.$maxred.
 1156:                   '><b><font size=+1>Import</font></b></td>'.
 1157:                   '<td colspan='.$maxyellow.
 1158: 		  '><b><font size=+1>Calculations</font></b></td></tr><tr>';
 1159:     my $showf=0;
 1160:     foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1161: 	     'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 1162: 	     'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1163: 	     'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1164:         $showf++;
 1165:         if ($showf<=$maxred) { 
 1166:            $tabledata.='<td bgcolor="#FFDDDD">'; 
 1167:         } else {
 1168:            $tabledata.='<td>';
 1169:         }
 1170:         $tabledata.="<b><font size=+1>$_</font></b></td>";
 1171:     }
 1172:     $tabledata.='</tr>'.&rown($safeeval,'-').&rown($safeeval,0);
 1173:    } else { $tabledata='<pre>'; }
 1174: 
 1175:     $r->print($tabledata);
 1176: 
 1177:     my $row;
 1178:     my $maxrow=&getmaxrow($safeeval);
 1179: 
 1180:     my @sortby=();
 1181:     my @sortidx=();
 1182:     for ($row=1;$row<=$maxrow;$row++) {
 1183:        $sortby[$row-1]=$safeeval->reval('$f{"A'.$row.'"}');
 1184:        $sortidx[$row-1]=$row-1;
 1185:     }
 1186:     @sortidx=sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
 1187: 
 1188:         my $what='Student';
 1189:         if (&gettype($safeeval) eq 'assesscalc') {
 1190: 	    $what='Item';
 1191: 	} elsif (&gettype($safeeval) eq 'studentcalc') {
 1192:             $what='Assessment';
 1193:         }
 1194: 
 1195:     my $n=0;
 1196:     for ($row=0;$row<$maxrow;$row++) {
 1197:      my $thisrow=&rown($safeeval,$sortidx[$row]+1);
 1198:      if ($thisrow) {
 1199:        if (($n/25==int($n/25)) && (!$ENV{'form.showcsv'})) {
 1200: 	$r->print("</table>\n<br>\n");
 1201:         $r->rflush();
 1202:         $r->print('<table border=2><tr><td>&nbsp;<td>'.$what.'</td>');
 1203:         foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1204: 		 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 1205: 		 'a','b','c','d','e','f','g','h','i','j','k','l','m',
 1206: 		 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
 1207:            $r->print('<td>'.$_.'</td>');
 1208:         }
 1209:         $r->print('</tr>');
 1210:        }
 1211:        $n++;
 1212:        $r->print($thisrow);
 1213:       }
 1214:     }
 1215:     $r->print($ENV{'form.showcsv'}?'</pre>':'</table>');
 1216: }
 1217: 
 1218: #
 1219: # ----------------------------------------------- Read list of available sheets
 1220: # 
 1221: sub othersheets {
 1222:     my ($safeeval,$stype)=@_;
 1223:     #
 1224:     my $cnum=&getcnum($safeeval);
 1225:     my $cdom=&getcdom($safeeval);
 1226:     my $chome=&getchome($safeeval);
 1227:     #
 1228:     my @alternatives=();
 1229:     my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
 1230:     my ($tmp) = keys(%results);
 1231:     unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1232:         @alternatives = sort (keys(%results));
 1233:     }
 1234:     return @alternatives; 
 1235: }
 1236: 
 1237: 
 1238: #
 1239: # -------------------------------------- Parse a spreadsheet
 1240: # 
 1241: sub parse_sheet {
 1242:     # $sheetxml is a scalar reference or a scalar
 1243:     my ($sheetxml) = @_;
 1244:     if (! ref($sheetxml)) {
 1245:         my $tmp = $sheetxml;
 1246:         $sheetxml = \$tmp;
 1247:     }
 1248:     my %f;
 1249:     my $parser=HTML::TokeParser->new($sheetxml);
 1250:     my $token;
 1251:     while ($token=$parser->get_token) {
 1252:         if ($token->[0] eq 'S') {
 1253:             if ($token->[1] eq 'field') {
 1254:                 $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
 1255:                     $parser->get_text('/field');
 1256:             }
 1257:             if ($token->[1] eq 'template') {
 1258:                 $f{'template_'.$token->[2]->{'col'}}=
 1259:                     $parser->get_text('/template');
 1260:             }
 1261:         }
 1262:     }
 1263:     return \%f;
 1264: }
 1265: 
 1266: #
 1267: # -------------------------------------- Read spreadsheet formulas for a course
 1268: #
 1269: 
 1270: sub readsheet {
 1271:   my ($safeeval,$fn)=@_;
 1272:   my $stype=&gettype($safeeval);
 1273:   my $cnum=&getcnum($safeeval);
 1274:   my $cdom=&getcdom($safeeval);
 1275:   my $chome=&getchome($safeeval);
 1276: 
 1277:   if (! defined($fn)) {
 1278:       # There is no filename. Look for defaults in course and global, cache
 1279:       unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
 1280:           my %tmphash = &Apache::lonnet::get('environment',
 1281:                                              ['spreadsheet_default_'.$stype],
 1282:                                              $cdom,$cnum);
 1283:           my ($tmp) = keys(%tmphash);
 1284:           if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1285:               $fn = 'default_'.$stype;
 1286:           } else {
 1287:               $fn = $tmphash{'spreadsheet_default_'.$stype};
 1288:           } 
 1289:           $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn; 
 1290:       }
 1291:   }
 1292: 
 1293: # ---------------------------------------------------------- fn now has a value
 1294: 
 1295:   &setfilename($safeeval,$fn);
 1296: 
 1297: # ------------------------------------------------------ see if sheet is cached
 1298:   my $fstring='';
 1299:   if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
 1300:       &setformulas($safeeval,split(/\_\_\_\;\_\_\_/,$fstring));
 1301:   } else {
 1302: 
 1303: # ---------------------------------------------------- Not cached, need to read
 1304: 
 1305:      my %f=();
 1306: 
 1307:      if ($fn=~/^default\_/) {
 1308:          my $sheetxml='';
 1309:          my $fh;
 1310:          my $dfn=$fn;
 1311:          $dfn=~s/\_/\./g;
 1312:          if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
 1313:              $sheetxml=join('',<$fh>);
 1314:          } else {
 1315:              $sheetxml='<field row="0" col="A">"Error"</field>';
 1316:          }
 1317:          %f=%{&parse_sheet(\$sheetxml)};
 1318:      } elsif($fn=~/\/*\.spreadsheet$/) {
 1319:          my $sheetxml=&Apache::lonnet::getfile
 1320:              (&Apache::lonnet::filelocation('',$fn));
 1321:          if ($sheetxml == -1) {
 1322:              $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
 1323:                  .$fn.'"</field>';
 1324:          }
 1325:          %f=%{&parse_sheet(\$sheetxml)};
 1326:      } else {
 1327:          my $sheet='';
 1328:          my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
 1329:          my ($tmp) = keys(%tmphash);
 1330:          unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
 1331:              foreach (keys(%tmphash)) {
 1332:                  $f{$_}=$tmphash{$_};
 1333:              }
 1334:          }
 1335:      }
 1336: # --------------------------------------------------------------- Cache and set
 1337:        $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);  
 1338:        &setformulas($safeeval,%f);
 1339:     }
 1340: }
 1341: 
 1342: # -------------------------------------------------------- Make new spreadsheet
 1343: 
 1344: sub makenewsheet {
 1345:     my ($uname,$udom,$stype,$usymb)=@_;
 1346:     my $safeeval=initsheet($stype);
 1347:     $safeeval->reval(
 1348:        '$uname="'.$uname.
 1349:       '";$udom="'.$udom.
 1350:       '";$uhome="'.&Apache::lonnet::homeserver($uname,$udom).
 1351:       '";$sheettype="'.$stype.
 1352:       '";$usymb="'.$usymb.
 1353:       '";$csec="'.&Apache::lonnet::usection($udom,$uname,
 1354:                                             $ENV{'request.course.id'}).
 1355:       '";$cid="'.$ENV{'request.course.id'}.
 1356:       '";$cfn="'.$ENV{'request.course.fn'}.
 1357:       '";$cnum="'.$ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
 1358:       '";$cdom="'.$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
 1359:       '";$chome="'.$ENV{'course.'.$ENV{'request.course.id'}.'.home'}.'";');
 1360:     return $safeeval;
 1361: }
 1362: 
 1363: # ------------------------------------------------------------ Save spreadsheet
 1364: 
 1365: sub writesheet {
 1366:   my ($safeeval,$makedef)=@_;
 1367:   my $cid=&getcid($safeeval);
 1368:   if (&Apache::lonnet::allowed('opa',$cid)) {
 1369:     my %f=&getformulas($safeeval);
 1370:     my $stype=&gettype($safeeval);
 1371:     my $cnum=&getcnum($safeeval);
 1372:     my $cdom=&getcdom($safeeval);
 1373:     my $chome=&getchome($safeeval);
 1374:     my $fn=&getfilename($safeeval);
 1375: 
 1376: # ------------------------------------------------------------- Cache new sheet
 1377:     $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);    
 1378: # ----------------------------------------------------------------- Write sheet
 1379:     my $sheetdata='';
 1380:     foreach (keys(%f)) {
 1381:      unless ($f{$_} eq 'import') {
 1382:        $sheetdata.=&Apache::lonnet::escape($_).'='.
 1383: 	   &Apache::lonnet::escape($f{$_}).'&';
 1384:      }
 1385:     }
 1386:     $sheetdata=~s/\&$//;
 1387:     my $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.$fn.':'.
 1388:               $sheetdata,$chome);
 1389:     if ($reply eq 'ok') {
 1390:           $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.
 1391:               $stype.'_spreadsheets:'.
 1392:               &Apache::lonnet::escape($fn).'='.$ENV{'user.name'}.'@'.
 1393:                                                $ENV{'user.domain'},
 1394:               $chome);
 1395:           if ($reply eq 'ok') {
 1396:               if ($makedef) { 
 1397:                 return &Apache::lonnet::reply('put:'.$cdom.':'.$cnum.
 1398:                                 ':environment:spreadsheet_default_'.$stype.'='.
 1399:                                 &Apache::lonnet::escape($fn),
 1400:                                 $chome);
 1401: 	      } else {
 1402: 		  return $reply;
 1403:     	      }
 1404: 	   } else {
 1405: 	       return $reply;
 1406:            }
 1407:       } else {
 1408: 	  return $reply;
 1409:       }
 1410:   }
 1411:   return 'unauthorized';
 1412: }
 1413: 
 1414: # ----------------------------------------------- Make a temp copy of the sheet
 1415: # "Modified workcopy" - interactive only
 1416: #
 1417: 
 1418: sub tmpwrite {
 1419:     my $safeeval=shift;
 1420:     my $fn=$ENV{'user.name'}.'_'.
 1421:            $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
 1422:            &getfilename($safeeval);
 1423:     $fn=~s/\W/\_/g;
 1424:     $fn=$tmpdir.$fn.'.tmp';
 1425:     my $fh;
 1426:     if ($fh=Apache::File->new('>'.$fn)) {
 1427: 	print $fh join("\n",&getformulas($safeeval));
 1428:     }
 1429: }
 1430: 
 1431: # ---------------------------------------------------------- Read the temp copy
 1432: 
 1433: sub tmpread {
 1434:     my ($safeeval,$nfield,$nform)=@_;
 1435:     my $fn=$ENV{'user.name'}.'_'.
 1436:            $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
 1437:            &getfilename($safeeval);
 1438:     $fn=~s/\W/\_/g;
 1439:     $fn=$tmpdir.$fn.'.tmp';
 1440:     my $fh;
 1441:     my %fo=();
 1442:     if ($fh=Apache::File->new($fn)) {
 1443:         my $name;
 1444:         while ($name=<$fh>) {
 1445: 	    chomp($name);
 1446:             my $value=<$fh>;
 1447:             chomp($value);
 1448:             $fo{$name}=$value;
 1449:         }
 1450:     }
 1451:     if ($nform eq 'changesheet') {
 1452:         $fo{'A'.$nfield}=(split(/\_\_\&\&\&\_\_/,$fo{'A'.$nfield}))[0];
 1453:         unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
 1454: 	    $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
 1455:         }
 1456:     } else {
 1457:        if ($nfield) { $fo{$nfield}=$nform; }
 1458:     }
 1459:     &setformulas($safeeval,%fo);
 1460: }
 1461: 
 1462: # ================================================================== Parameters
 1463: # -------------------------------------------- Figure out a cascading parameter
 1464: #
 1465: # For this function to work
 1466: #
 1467: # * parmhash needs to be tied
 1468: # * courseopt and useropt need to be initialized for this user and course
 1469: #
 1470: 
 1471: sub parmval {
 1472:     my ($what,$safeeval)=@_;
 1473:     my $cid=&getcid($safeeval);
 1474:     my $csec=&getcsec($safeeval);
 1475:     my $uname=&getuname($safeeval);
 1476:     my $udom=&getudom($safeeval);
 1477:     my $symb=&getusymb($safeeval);
 1478: 
 1479:     unless ($symb) { return ''; }
 1480:     my $result='';
 1481: 
 1482:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 1483: # ----------------------------------------------------- Cascading lookup scheme
 1484:        my $rwhat=$what;
 1485:        $what=~s/^parameter\_//;
 1486:        $what=~s/\_([^\_]+)$/\.$1/;
 1487: 
 1488:        my $symbparm=$symb.'.'.$what;
 1489:        my $mapparm=$mapname.'___(all).'.$what;
 1490:        my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
 1491: 
 1492:        my $seclevel=
 1493:             $usercourseprefix.'.['.
 1494: 		$csec.'].'.$what;
 1495:        my $seclevelr=
 1496:             $usercourseprefix.'.['.
 1497: 		$csec.'].'.$symbparm;
 1498:        my $seclevelm=
 1499:             $usercourseprefix.'.['.
 1500: 		$csec.'].'.$mapparm;
 1501: 
 1502:        my $courselevel=
 1503:             $usercourseprefix.'.'.$what;
 1504:        my $courselevelr=
 1505:             $usercourseprefix.'.'.$symbparm;
 1506:        my $courselevelm=
 1507:             $usercourseprefix.'.'.$mapparm;
 1508: 
 1509: # ---------------------------------------------------------- fourth, check user
 1510:       
 1511:       if ($uname) { 
 1512: 
 1513:        if ($useropt{$courselevelr}) { return $useropt{$courselevelr}; }
 1514: 
 1515:        if ($useropt{$courselevelm}) { return $useropt{$courselevelm}; }
 1516: 
 1517:        if ($useropt{$courselevel}) { return $useropt{$courselevel}; }
 1518: 
 1519:       }
 1520: 
 1521: # --------------------------------------------------------- third, check course
 1522:      
 1523:        if ($csec) {
 1524:  
 1525:         if ($courseopt{$seclevelr}) { return $courseopt{$seclevelr}; }
 1526: 
 1527:         if ($courseopt{$seclevelm}) { return $courseopt{$seclevelm}; }  
 1528: 
 1529:         if ($courseopt{$seclevel}) { return $courseopt{$seclevel}; }
 1530:   
 1531:       }
 1532: 
 1533:        if ($courseopt{$courselevelr}) { return $courseopt{$courselevelr}; }
 1534: 
 1535:        if ($courseopt{$courselevelm}) { return $courseopt{$courselevelm}; }
 1536: 
 1537:        if ($courseopt{$courselevel}) { return $courseopt{$courselevel}; }
 1538: 
 1539: # ----------------------------------------------------- second, check map parms
 1540: 
 1541:        my $thisparm=$parmhash{$symbparm};
 1542:        if ($thisparm) { return $thisparm; }
 1543: 
 1544: # -------------------------------------------------------- first, check default
 1545: 
 1546:        return &Apache::lonnet::metadata($fn,$rwhat.'.default');
 1547:         
 1548: }
 1549: 
 1550: # ---------------------------------------------- Update rows for course listing
 1551: 
 1552: sub updateclasssheet {
 1553:     my $safeeval=shift;
 1554:     my $cnum=&getcnum($safeeval);
 1555:     my $cdom=&getcdom($safeeval);
 1556:     my $cid=&getcid($safeeval);
 1557:     my $chome=&getchome($safeeval);
 1558: 
 1559: # ---------------------------------------------- Read class list and row labels
 1560: 
 1561:     my $classlst=&Apache::lonnet::reply
 1562:                                  ('dump:'.$cdom.':'.$cnum.':classlist',$chome);
 1563:     my %currentlist=();
 1564:     my $now=time;
 1565:     unless ($classlst=~/^error\:/) {
 1566:         foreach (split(/\&/,$classlst)) {
 1567:             my ($name,$value)=split(/\=/,$_);
 1568:             my ($end,$start)=split(/\:/,&Apache::lonnet::unescape($value));
 1569:             my $active=1;
 1570:             if (($end) && ($now>$end)) { $active=0; }
 1571:             if ($active) {
 1572:                 my $rowlabel='';
 1573:                 $name=&Apache::lonnet::unescape($name);
 1574:                 my ($sname,$sdom)=split(/\:/,$name);
 1575:                 my $ssec=&Apache::lonnet::usection($sdom,$sname,$cid);
 1576:                 if ($ssec==-1) {
 1577: 		   unless ($ENV{'form.showcsv'}) {
 1578:                     $rowlabel='<font color=red>Data not available: '.$name.
 1579: 			      '</font>';
 1580: 		   } else {
 1581: 		       $rowlabel='ERROR","'.$name.
 1582:                                  '","Data not available","","","';
 1583:                    }
 1584:                 } else {
 1585:                     my %reply=&Apache::lonnet::idrget($sdom,$sname);
 1586:                     my $reply=&Apache::lonnet::reply('get:'.$sdom.':'.$sname.
 1587: 		      ':environment:firstname&middlename&lastname&generation',
 1588:                       &Apache::lonnet::homeserver($sname,$sdom));
 1589: 		   unless ($ENV{'form.showcsv'}) {
 1590:                     $rowlabel='<a href="/adm/studentcalc?uname='.$sname.
 1591:                               '&udom='.$sdom.'">'.
 1592:                               $ssec.'&nbsp;'.$reply{$sname}.'<br>';
 1593:                     foreach ( split(/\&/,$reply)) {
 1594:                         $rowlabel.=&Apache::lonnet::unescape($_).' ';
 1595:                     }
 1596:                     $rowlabel.='</a>';
 1597: 		   } else {
 1598: 		    $rowlabel=$ssec.'","'.$reply{$sname}.'"';
 1599:                     my $ncount=0;
 1600:                     foreach (split(/\&/,$reply)) {
 1601:                         $rowlabel.=',"'.&Apache::lonnet::unescape($_).'"';
 1602:                         $ncount++;
 1603:                     }
 1604:                     unless ($ncount==4) { $rowlabel.=',""'; }
 1605:                     $rowlabel=~s/\"$//;
 1606: 		   }
 1607:                 }
 1608: 		$currentlist{&Apache::lonnet::unescape($name)}=$rowlabel;
 1609:             }
 1610:         } # end of foreach (split(/\&/,$classlst))
 1611: #
 1612: # -------------------- Find discrepancies between the course row table and this
 1613: #
 1614:         my %f=&getformulas($safeeval);
 1615:         my $changed=0;
 1616: 
 1617:         my $maxrow=0;
 1618:         my %existing=();
 1619: 
 1620: # ----------------------------------------------------------- Now obsolete rows
 1621: 	foreach (keys(%f)) {
 1622: 	    if ($_=~/^A(\d+)/) {
 1623:                 $maxrow=($1>$maxrow)?$1:$maxrow;
 1624:                 $existing{$f{$_}}=1;
 1625: 		unless ((defined($currentlist{$f{$_}})) || (!$1)) {
 1626: 		   $f{$_}='!!! Obsolete';
 1627:                    $changed=1;
 1628:                 }
 1629:             }
 1630:         }
 1631: 
 1632: # -------------------------------------------------------- New and unknown keys
 1633:      
 1634:         foreach (sort keys(%currentlist)) {
 1635:             unless ($existing{$_}) {
 1636: 		$changed=1;
 1637:                 $maxrow++;
 1638:                 $f{'A'.$maxrow}=$_;
 1639:             }
 1640:         }
 1641:      
 1642:         if ($changed) { &setformulas($safeeval,%f); }
 1643: 
 1644:         &setmaxrow($safeeval,$maxrow);
 1645:         &setrowlabels($safeeval,%currentlist);
 1646: 
 1647:     } else {
 1648:         return 'Could not access course data';
 1649:     }
 1650: }
 1651: 
 1652: # ----------------------------------- Update rows for student and assess sheets
 1653: 
 1654: sub updatestudentassesssheet {
 1655:     my $safeeval=shift;
 1656:     my %bighash;
 1657:     my $stype=&gettype($safeeval);
 1658:     my %current=();
 1659:     unless ($updatedata{$ENV{'request.course.fn'}.'_'.$stype}) {
 1660: # -------------------------------------------------------------------- Tie hash
 1661:       if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 1662:                        &GDBM_READER,0640)) {
 1663: # --------------------------------------------------------- Get all assessments
 1664: 
 1665: 	my %allkeys=('timestamp' => 
 1666:                      'Timestamp of Last Transaction<br>timestamp',
 1667:                      'subnumber' =>
 1668:                      'Number of Submissions<br>subnumber',
 1669:                      'tutornumber' =>
 1670:                      'Number of Tutor Responses<br>tutornumber',
 1671:                      'totalpoints' =>
 1672:                      'Total Points Granted<br>totalpoints');
 1673: 
 1674:         my $adduserstr='';
 1675:         if ((&getuname($safeeval) ne $ENV{'user.name'}) ||
 1676:             (&getudom($safeeval) ne $ENV{'user.domain'})) {
 1677:             $adduserstr='&uname='.&getuname($safeeval).
 1678: 		'&udom='.&getudom($safeeval);
 1679:         }
 1680: 
 1681:         my %allassess=('_feedback' =>
 1682: 	              '<a href="/adm/assesscalc?usymb=_feedback'.$adduserstr.
 1683:                        '">Feedback</a>',
 1684:                        '_evaluation' =>
 1685: 	              '<a href="/adm/assesscalc?usymb=_evaluation'.$adduserstr.
 1686:                        '">Evaluation</a>',
 1687:                        '_tutoring' =>
 1688: 	              '<a href="/adm/assesscalc?usymb=_tutoring'.$adduserstr.
 1689:                        '">Tutoring</a>',
 1690:                        '_discussion' =>
 1691: 	              '<a href="/adm/assesscalc?usymb=_discussion'.$adduserstr.
 1692:                        '">Discussion</a>'
 1693:         );
 1694: 
 1695:         foreach (keys(%bighash)) {
 1696: 	    if ($_=~/^src\_(\d+)\.(\d+)$/) {
 1697: 	       my $mapid=$1;
 1698:                my $resid=$2;
 1699:                my $id=$mapid.'.'.$resid;
 1700:                my $srcf=$bighash{$_};
 1701:                if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
 1702:                  my $symb=
 1703:                      &Apache::lonnet::declutter($bighash{'map_id_'.$mapid}).
 1704: 			    '___'.$resid.'___'.
 1705: 			    &Apache::lonnet::declutter($srcf);
 1706: 		 $allassess{$symb}=
 1707: 	            '<a href="/adm/assesscalc?usymb='.$symb.$adduserstr.'">'.
 1708:                      $bighash{'title_'.$id}.'</a>';
 1709:                  if ($stype eq 'assesscalc') {
 1710: 		     foreach (split(/\,/,
 1711: 				    &Apache::lonnet::metadata($srcf,'keys'))) {
 1712:                        if (($_=~/^stores\_(.*)/) || ($_=~/^parameter\_(.*)/)) {
 1713: 			  my $key=$_;
 1714:                           my $display=
 1715: 			      &Apache::lonnet::metadata($srcf,$key.'.display');
 1716:                           unless ($display) {
 1717:                               $display.=
 1718: 			         &Apache::lonnet::metadata($srcf,$key.'.name');
 1719:                           }
 1720:                           $display.='<br>'.$key;
 1721:                           $allkeys{$key}=$display;
 1722: 		       }
 1723:                    } # end of foreach
 1724: 	         }
 1725: 	      }
 1726: 	   }
 1727:         } # end of foreach (keys(%bighash))
 1728:         untie(%bighash);
 1729:     
 1730: #
 1731: # %allkeys has a list of storage and parameter displays by unikey
 1732: # %allassess has a list of all resource displays by symb
 1733: #
 1734: 
 1735:         if ($stype eq 'assesscalc') {
 1736: 	    %current=%allkeys;
 1737:         } elsif ($stype eq 'studentcalc') {
 1738:             %current=%allassess;
 1739:         }
 1740:         $updatedata{$ENV{'request.course.fn'}.'_'.$stype}=
 1741: 	    join('___;___',%current);
 1742:     } else {
 1743:         return 'Could not access course data';
 1744:     }
 1745: # ------------------------------------------------------ Get current from cache
 1746:     } else {
 1747:         %current=split(/\_\_\_\;\_\_\_/,
 1748: 		       $updatedata{$ENV{'request.course.fn'}.'_'.$stype});
 1749:     }
 1750: # -------------------- Find discrepancies between the course row table and this
 1751: #
 1752:         my %f=&getformulas($safeeval);
 1753:         my $changed=0;
 1754: 
 1755:         my $maxrow=0;
 1756:         my %existing=();
 1757: 
 1758: # ----------------------------------------------------------- Now obsolete rows
 1759: 	foreach (keys(%f)) {
 1760: 	    if ($_=~/^A(\d+)/) {
 1761:                 $maxrow=($1>$maxrow)?$1:$maxrow;
 1762:                 my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
 1763:                 $existing{$usy}=1;
 1764: 		unless ((defined($current{$usy})) || (!$1)) {
 1765: 		   $f{$_}='!!! Obsolete';
 1766:                    $changed=1;
 1767: 	        } elsif ($ufn) {
 1768: 		    $current{$usy}
 1769:                        =~s/assesscalc\?usymb\=/assesscalc\?ufn\=$ufn\&usymb\=/;
 1770:                 }
 1771:             }
 1772:         }
 1773: 
 1774: # -------------------------------------------------------- New and unknown keys
 1775:      
 1776:         foreach (keys(%current)) {
 1777:             unless ($existing{$_}) {
 1778: 		$changed=1;
 1779:                 $maxrow++;
 1780:                 $f{'A'.$maxrow}=$_;
 1781:             }
 1782:         }
 1783:     
 1784:         if ($changed) { &setformulas($safeeval,%f); }
 1785: 
 1786:         &setmaxrow($safeeval,$maxrow);
 1787:         &setrowlabels($safeeval,%current);
 1788:  
 1789:         undef %current;
 1790:         undef %existing;
 1791: }
 1792: 
 1793: # ------------------------------------------------ Load data for one assessment
 1794: 
 1795: sub loadstudent {
 1796:     my $safeeval=shift;
 1797:     my %c=();
 1798:     my %f=&getformulas($safeeval);
 1799:     $cachedassess=&getuname($safeeval).':'.&getudom($safeeval);
 1800:     %cachedstores=();
 1801:     {
 1802:       my $reply=&Apache::lonnet::reply('dump:'.&getudom($safeeval).':'.
 1803:                                                &getuname($safeeval).':'.
 1804:                                                &getcid($safeeval),
 1805:                                                &getuhome($safeeval));
 1806:       unless ($reply=~/^error\:/) {
 1807: 	 foreach ( split(/\&/,$reply)) {
 1808:             my ($name,$value)=split(/\=/,$_);
 1809:             $cachedstores{&Apache::lonnet::unescape($name)}=
 1810: 	                  &Apache::lonnet::unescape($value);
 1811: 	}
 1812:       }
 1813:     }
 1814:     my @assessdata=();
 1815:     foreach (keys(%f)) {
 1816: 	if ($_=~/^A(\d+)/) {
 1817: 	   my $row=$1;
 1818:            unless (($f{$_}=~/^\!/) || ($row==0)) {
 1819: 	      my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
 1820: 	      @assessdata=&exportsheet(&getuname($safeeval),
 1821:                                        &getudom($safeeval),
 1822:                                        'assesscalc',$usy,$ufn);
 1823:               my $index=0;
 1824:               foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1825: 	               'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 1826:                   if ($assessdata[$index]) {
 1827: 		     my $col=$_;
 1828: 		     if ($assessdata[$index]=~/\D/) {
 1829:                          $c{$col.$row}="'".$assessdata[$index]."'";
 1830:  		     } else {
 1831: 		         $c{$col.$row}=$assessdata[$index];
 1832: 		     }
 1833:                      unless ($col eq 'A') { 
 1834: 			 $f{$col.$row}='import';
 1835:                      }
 1836: 		  }
 1837:                   $index++;
 1838:               }
 1839: 	   }
 1840:         }
 1841:     }
 1842:     $cachedassess='';
 1843:     undef %cachedstores;
 1844:     &setformulas($safeeval,%f);
 1845:     &setconstants($safeeval,%c);
 1846: }
 1847: 
 1848: # --------------------------------------------------- Load data for one student
 1849: 
 1850: sub loadcourse {
 1851:     my ($safeeval,$r)=@_;
 1852:     my %c=();
 1853:     my %f=&getformulas($safeeval);
 1854:     my $total=0;
 1855:     foreach (keys(%f)) {
 1856: 	if ($_=~/^A(\d+)/) {
 1857: 	    unless ($f{$_}=~/^\!/) { $total++; }
 1858:         }
 1859:     }
 1860:     my $now=0;
 1861:     my $since=time;
 1862:     $r->print(<<ENDPOP);
 1863: <script>
 1864:     popwin=open('','popwin','width=400,height=100');
 1865:     popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
 1866:       '<h3>Spreadsheet Calculation Progress</h3>'+
 1867:       '<form name=popremain>'+
 1868:       '<input type=text size=35 name=remaining value=Starting></form>'+
 1869:       '</body></html>');
 1870:     popwin.document.close();
 1871: </script>
 1872: ENDPOP
 1873:     $r->rflush();
 1874:     foreach (keys(%f)) {
 1875: 	if ($_=~/^A(\d+)/) {
 1876: 	   my $row=$1;
 1877:            unless (($f{$_}=~/^\!/)  || ($row==0)) {
 1878: 	      my @studentdata=&exportsheet(split(/\:/,$f{$_}),
 1879:                                            'studentcalc');
 1880:               undef %userrdatas;
 1881:               $now++;
 1882:               $r->print('<script>popwin.document.popremain.remaining.value="'.
 1883:                   $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
 1884:                         ' secs remaining";</script>');
 1885:               $r->rflush(); 
 1886: 
 1887:               my $index=0;
 1888:              foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1889: 	              'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
 1890:                   if ($studentdata[$index]) {
 1891: 		     my $col=$_;
 1892: 		     if ($studentdata[$index]=~/\D/) {
 1893:                          $c{$col.$row}="'".$studentdata[$index]."'";
 1894:  		     } else {
 1895: 		         $c{$col.$row}=$studentdata[$index];
 1896: 		     }
 1897:                      unless ($col eq 'A') { 
 1898: 			 $f{$col.$row}='import';
 1899:                      }
 1900: 		  }
 1901:                   $index++;
 1902:               }
 1903: 	   }
 1904:         }
 1905:     }
 1906:     &setformulas($safeeval,%f);
 1907:     &setconstants($safeeval,%c);
 1908:     $r->print('<script>popwin.close()</script>');
 1909:     $r->rflush(); 
 1910: }
 1911: 
 1912: # ------------------------------------------------ Load data for one assessment
 1913: 
 1914: sub loadassessment {
 1915:     my $safeeval=shift;
 1916: 
 1917:     my $uhome=&getuhome($safeeval);
 1918:     my $uname=&getuname($safeeval);
 1919:     my $udom=&getudom($safeeval);
 1920:     my $symb=&getusymb($safeeval);
 1921:     my $cid=&getcid($safeeval);
 1922:     my $cnum=&getcnum($safeeval);
 1923:     my $cdom=&getcdom($safeeval);
 1924:     my $chome=&getchome($safeeval);
 1925: 
 1926:     my $namespace;
 1927:     unless ($namespace=$cid) { return ''; }
 1928: 
 1929: # ----------------------------------------------------------- Get stored values
 1930: 
 1931:    my %returnhash=();
 1932: 
 1933:    if ($cachedassess eq $uname.':'.$udom) {
 1934: #
 1935: # get data out of the dumped stores
 1936: # 
 1937: 
 1938:        my $version=$cachedstores{'version:'.$symb};
 1939:        my $scope;
 1940:        for ($scope=1;$scope<=$version;$scope++) {
 1941:            foreach (split(/\:/,$cachedstores{$scope.':keys:'.$symb})) {
 1942:                $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
 1943:            } 
 1944:        }
 1945: 
 1946:    } else {
 1947: #
 1948: # restore individual
 1949: #
 1950: 
 1951:     my $answer=&Apache::lonnet::reply(
 1952:        "restore:$udom:$uname:".
 1953:        &Apache::lonnet::escape($namespace).":".
 1954:        &Apache::lonnet::escape($symb),$uhome);
 1955:     foreach (split(/\&/,$answer)) {
 1956: 	my ($name,$value)=split(/\=/,$_);
 1957:         $returnhash{&Apache::lonnet::unescape($name)}=
 1958:                     &Apache::lonnet::unescape($value);
 1959:     }
 1960:     my $version;
 1961:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 1962:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 1963:           $returnhash{$_}=$returnhash{$version.':'.$_};
 1964:        } 
 1965:     }
 1966:    }
 1967: # ----------------------------- returnhash now has all stores for this resource
 1968: 
 1969: # --------- convert all "_" to "." to be able to use libraries, multiparts, etc
 1970: 
 1971:     my @oldkeys=keys %returnhash;
 1972: 
 1973:     foreach (@oldkeys) {
 1974:         my $name=$_;
 1975:         my $value=$returnhash{$_};
 1976:         delete $returnhash{$_};
 1977:         $name=~s/\_/\./g;
 1978:         $returnhash{$name}=$value;
 1979:     }
 1980: 
 1981: # ---------------------------- initialize coursedata and userdata for this user
 1982:     undef %courseopt;
 1983:     undef %useropt;
 1984: 
 1985:     my $userprefix=$uname.'_'.$udom.'_';
 1986: 
 1987:     unless ($uhome eq 'no_host') { 
 1988: # -------------------------------------------------------------- Get coursedata
 1989:       unless
 1990:         ((time-$courserdatas{$cid.'.last_cache'})<240) {
 1991:          my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
 1992:               ':resourcedata',$chome);
 1993:          if ($reply!~/^error\:/) {
 1994:             $courserdatas{$cid}=$reply;
 1995:             $courserdatas{$cid.'.last_cache'}=time;
 1996:          }
 1997:       }
 1998:       foreach (split(/\&/,$courserdatas{$cid})) {
 1999:          my ($name,$value)=split(/\=/,$_);
 2000:          $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
 2001:                     &Apache::lonnet::unescape($value);  
 2002:       }
 2003: # --------------------------------------------------- Get userdata (if present)
 2004:       unless
 2005:         ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
 2006:          my $reply=
 2007:        &Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
 2008:          if ($reply!~/^error\:/) {
 2009: 	     $userrdatas{$uname.'___'.$udom}=$reply;
 2010: 	     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
 2011:          }
 2012:       }
 2013:       foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
 2014:          my ($name,$value)=split(/\=/,$_);
 2015:          $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
 2016: 	          &Apache::lonnet::unescape($value);
 2017:       }
 2018:     }
 2019: # ----------------- now courseopt, useropt initialized for this user and course
 2020: # (used by parmval)
 2021: 
 2022: #
 2023: # Load keys for this assessment only
 2024: #
 2025:     my %thisassess=();
 2026:     my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
 2027:     
 2028:     foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
 2029:         $thisassess{$_}=1;
 2030:     } 
 2031: #
 2032: # Load parameters
 2033: #
 2034:    my %c=();
 2035: 
 2036:    if (tie(%parmhash,'GDBM_File',
 2037:            &getcfn($safeeval).'_parms.db',&GDBM_READER,0640)) {
 2038:     my %f=&getformulas($safeeval);
 2039:     foreach (keys(%f))  {
 2040: 	if ($_=~/^A/) {
 2041:             unless ($f{$_}=~/^\!/) {
 2042:   	       if ($f{$_}=~/^parameter/) {
 2043: 		if ($thisassess{$f{$_}}) {
 2044:                   my $val=&parmval($f{$_},$safeeval);
 2045:                   $c{$_}=$val;
 2046:                   $c{$f{$_}}=$val;
 2047: 	        }
 2048: 	       } else {
 2049: 		  my $key=$f{$_};
 2050:                   my $ckey=$key;
 2051:                   $key=~s/^stores\_/resource\./;
 2052:                   $key=~s/\_/\./g;
 2053:  	          $c{$_}=$returnhash{$key};
 2054:                   $c{$ckey}=$returnhash{$key};
 2055: 	       }
 2056: 	   }
 2057:         }
 2058:     }
 2059:     untie(%parmhash);
 2060:    }
 2061:    &setconstants($safeeval,%c);
 2062: }
 2063: 
 2064: # --------------------------------------------------------- Various form fields
 2065: 
 2066: sub textfield {
 2067:     my ($title,$name,$value)=@_;
 2068:     return "\n<p><b>$title:</b><br>".
 2069:            '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
 2070: }
 2071: 
 2072: sub hiddenfield {
 2073:     my ($name,$value)=@_;
 2074:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
 2075: }
 2076: 
 2077: sub selectbox {
 2078:     my ($title,$name,$value,%options)=@_;
 2079:     my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
 2080:     foreach (sort keys(%options)) {
 2081:         $selout.='<option value="'.$_.'"';
 2082:         if ($_ eq $value) { $selout.=' selected'; }
 2083:         $selout.='>'.$options{$_}.'</option>';
 2084:     }
 2085:     return $selout.'</select>';
 2086: }
 2087: 
 2088: # =============================================== Update information in a sheet
 2089: #
 2090: # Add new users or assessments, etc.
 2091: #
 2092: 
 2093: sub updatesheet {
 2094:     my $safeeval=shift;
 2095:     my $stype=&gettype($safeeval);
 2096:     if ($stype eq 'classcalc') {
 2097: 	return &updateclasssheet($safeeval);
 2098:     } else {
 2099:         return &updatestudentassesssheet($safeeval);
 2100:     }
 2101: }
 2102: 
 2103: # =================================================== Load the rows for a sheet
 2104: #
 2105: # Import the data for rows
 2106: #
 2107: 
 2108: sub loadrows {
 2109:     my ($safeeval,$r)=@_;
 2110:     my $stype=&gettype($safeeval);
 2111:     if ($stype eq 'classcalc') {
 2112: 	&loadcourse($safeeval,$r);
 2113:     } elsif ($stype eq 'studentcalc') {
 2114:         &loadstudent($safeeval);
 2115:     } else {
 2116:         &loadassessment($safeeval);
 2117:     }
 2118: }
 2119: 
 2120: # ======================================================= Forced recalculation?
 2121: 
 2122: sub checkthis {
 2123:     my ($keyname,$time)=@_;
 2124:     return ($time<$expiredates{$keyname});
 2125: }
 2126: sub forcedrecalc {
 2127:     my ($uname,$udom,$stype,$usymb)=@_;
 2128:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2129:     my $time=$oldsheets{$key.'.time'};
 2130:     if ($ENV{'form.forcerecalc'}) { return 1; }
 2131:     unless ($time) { return 1; }
 2132:     if ($stype eq 'assesscalc') {
 2133:         my $map=(split(/\_\_\_/,$usymb))[0];
 2134:         if (&checkthis('::assesscalc:',$time) ||
 2135:             &checkthis('::assesscalc:'.$map,$time) ||
 2136:             &checkthis('::assesscalc:'.$usymb,$time) ||
 2137:             &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
 2138:             &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
 2139:             &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
 2140:             return 1;
 2141:         } 
 2142:     } else {
 2143:         if (&checkthis('::studentcalc:',$time) || 
 2144:             &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
 2145: 	    return 1;
 2146:         }
 2147:     }
 2148:     return 0; 
 2149: }
 2150: 
 2151: # ============================================================== Export handler
 2152: #
 2153: # Non-interactive call from with program
 2154: #
 2155: 
 2156: sub exportsheet {
 2157:  my ($uname,$udom,$stype,$usymb,$fn)=@_;
 2158:  my @exportarr=();
 2159: 
 2160:  if (($usymb=~/^\_(\w+)/) && (!$fn)) {
 2161:     $fn='default_'.$1;
 2162:  }
 2163: 
 2164: #
 2165: # Check if cached
 2166: #
 2167: 
 2168:  my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2169:  my $found='';
 2170: 
 2171:  if ($oldsheets{$key}) {
 2172:      foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
 2173:          my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 2174:          if ($name eq $fn) {
 2175: 	     $found=$value;
 2176:          }
 2177:      }
 2178:  }
 2179: 
 2180:  unless ($found) {
 2181:      &cachedssheets($uname,$udom,&Apache::lonnet::homeserver($uname,$udom));
 2182:      if ($oldsheets{$key}) {
 2183: 	foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
 2184:             my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 2185:             if ($name eq $fn) {
 2186: 	        $found=$value;
 2187:             }
 2188:         } 
 2189:      }
 2190:  }
 2191: #
 2192: # Check if still valid
 2193: #
 2194:  if ($found) {
 2195:      if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
 2196: 	 $found='';
 2197:      }
 2198:  }
 2199:  
 2200:  if ($found) {
 2201: #
 2202: # Return what was cached
 2203: #
 2204:      @exportarr=split(/\_\_\_\;\_\_\_/,$found);
 2205: 
 2206:  } else {
 2207: #
 2208: # Not cached
 2209: #        
 2210: 
 2211:     my $thissheet=&makenewsheet($uname,$udom,$stype,$usymb);
 2212:     &readsheet($thissheet,$fn);
 2213:     &updatesheet($thissheet);
 2214:     &loadrows($thissheet);
 2215:     &calcsheet($thissheet); 
 2216:     @exportarr=&exportdata($thissheet);
 2217: #
 2218: # Store now
 2219: #
 2220:     my $cid=$ENV{'request.course.id'}; 
 2221:     my $current='';
 2222:     if ($stype eq 'studentcalc') {
 2223:        $current=&Apache::lonnet::reply('get:'.
 2224:                                      $ENV{'course.'.$cid.'.domain'}.':'.
 2225:                                      $ENV{'course.'.$cid.'.num'}.
 2226: 				     ':nohist_calculatedsheets:'.
 2227:                                      &Apache::lonnet::escape($key),
 2228:                                      $ENV{'course.'.$cid.'.home'});
 2229:     } else {
 2230:        $current=&Apache::lonnet::reply('get:'.
 2231:                                      &getudom($thissheet).':'.
 2232:                                      &getuname($thissheet).
 2233: 				     ':nohist_calculatedsheets_'.
 2234:                                      $ENV{'request.course.id'}.':'.
 2235:                                      &Apache::lonnet::escape($key),
 2236:                                      &getuhome($thissheet));
 2237: 
 2238:     }
 2239:     my %currentlystored=();
 2240:     unless ($current=~/^error\:/) {
 2241:        foreach (split(/\_\_\_\&\_\_\_/,&Apache::lonnet::unescape($current))) {
 2242:            my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 2243:            $currentlystored{$name}=$value;
 2244:        }
 2245:     }
 2246:     $currentlystored{$fn}=join('___;___',@exportarr);
 2247: 
 2248:     my $newstore='';
 2249:     foreach (keys(%currentlystored)) {
 2250:         if ($newstore) { $newstore.='___&___'; }
 2251:         $newstore.=$_.'___=___'.$currentlystored{$_};
 2252:     }
 2253:     my $now=time;
 2254:     if ($stype eq 'studentcalc') {
 2255:        &Apache::lonnet::reply('put:'.
 2256:                          $ENV{'course.'.$cid.'.domain'}.':'.
 2257:                          $ENV{'course.'.$cid.'.num'}.
 2258: 			 ':nohist_calculatedsheets:'.
 2259:                          &Apache::lonnet::escape($key).'='.
 2260: 			 &Apache::lonnet::escape($newstore).'&'.
 2261:                          &Apache::lonnet::escape($key).'.time='.$now,
 2262:                          $ENV{'course.'.$cid.'.home'});
 2263:    } else {
 2264:        &Apache::lonnet::reply('put:'.
 2265:                          &getudom($thissheet).':'.
 2266:                          &getuname($thissheet).
 2267: 			 ':nohist_calculatedsheets_'.
 2268:                          $ENV{'request.course.id'}.':'.
 2269:                          &Apache::lonnet::escape($key).'='.
 2270: 			 &Apache::lonnet::escape($newstore).'&'.
 2271:                          &Apache::lonnet::escape($key).'.time='.$now,
 2272:                          &getuhome($thissheet));
 2273:    }
 2274:  }
 2275:  return @exportarr;
 2276: }
 2277: # ============================================================ Expiration Dates
 2278: #
 2279: # Load previously cached student spreadsheets for this course
 2280: #
 2281: 
 2282: sub expirationdates {
 2283:     undef %expiredates;
 2284:     my $cid=$ENV{'request.course.id'};
 2285:     my $reply=&Apache::lonnet::reply('dump:'.
 2286: 				     $ENV{'course.'.$cid.'.domain'}.':'.
 2287:                                      $ENV{'course.'.$cid.'.num'}.
 2288: 				     ':nohist_expirationdates',
 2289:                                      $ENV{'course.'.$cid.'.home'});
 2290:     unless ($reply=~/^error\:/) {
 2291: 	foreach (split(/\&/,$reply)) {
 2292:             my ($name,$value)=split(/\=/,$_);
 2293:             $expiredates{&Apache::lonnet::unescape($name)}
 2294:                         =&Apache::lonnet::unescape($value);
 2295:         }
 2296:     }
 2297: }
 2298: 
 2299: # ===================================================== Calculated sheets cache
 2300: #
 2301: # Load previously cached student spreadsheets for this course
 2302: #
 2303: 
 2304: sub cachedcsheets {
 2305:     my $cid=$ENV{'request.course.id'};
 2306:     my $reply=&Apache::lonnet::reply('dump:'.
 2307: 				     $ENV{'course.'.$cid.'.domain'}.':'.
 2308:                                      $ENV{'course.'.$cid.'.num'}.
 2309: 				     ':nohist_calculatedsheets',
 2310:                                      $ENV{'course.'.$cid.'.home'});
 2311:     unless ($reply=~/^error\:/) {
 2312: 	foreach ( split(/\&/,$reply)) {
 2313:             my ($name,$value)=split(/\=/,$_);
 2314:             $oldsheets{&Apache::lonnet::unescape($name)}
 2315:                       =&Apache::lonnet::unescape($value);
 2316:         }
 2317:     }
 2318: }
 2319: 
 2320: # ===================================================== Calculated sheets cache
 2321: #
 2322: # Load previously cached assessment spreadsheets for this student
 2323: #
 2324: 
 2325: sub cachedssheets {
 2326:   my ($sname,$sdom,$shome)=@_;
 2327:   unless (($loadedcaches{$sname.'_'.$sdom}) || ($shome eq 'no_host')) {
 2328:     my $cid=$ENV{'request.course.id'};
 2329:     my $reply=&Apache::lonnet::reply('dump:'.$sdom.':'.$sname.
 2330: 			             ':nohist_calculatedsheets_'.
 2331:                                       $ENV{'request.course.id'},
 2332:                                      $shome);
 2333:     unless ($reply=~/^error\:/) {
 2334: 	foreach ( split(/\&/,$reply)) {
 2335:             my ($name,$value)=split(/\=/,$_);
 2336:             $oldsheets{&Apache::lonnet::unescape($name)}
 2337:                       =&Apache::lonnet::unescape($value);
 2338:         }
 2339:     }
 2340:     $loadedcaches{$sname.'_'.$sdom}=1;
 2341:   }
 2342: }
 2343: 
 2344: # ===================================================== Calculated sheets cache
 2345: #
 2346: # Load previously cached assessment spreadsheets for this student
 2347: #
 2348: 
 2349: # ================================================================ Main handler
 2350: #
 2351: # Interactive call to screen
 2352: #
 2353: #
 2354: 
 2355: 
 2356: sub handler {
 2357:     my $r=shift;
 2358: 
 2359:     if ($r->header_only) {
 2360:       $r->content_type('text/html');
 2361:       $r->send_http_header;
 2362:       return OK;
 2363:     }
 2364: 
 2365: # ---------------------------------------------------- Global directory configs
 2366: 
 2367: $includedir=$r->dir_config('lonIncludes');
 2368: $tmpdir=$r->dir_config('lonDaemons').'/tmp/';
 2369: 
 2370: # ----------------------------------------------------- Needs to be in a course
 2371: 
 2372:   if ($ENV{'request.course.fn'}) { 
 2373: 
 2374: # --------------------------- Get query string for limited number of parameters
 2375: 
 2376:     foreach (split(/&/,$ENV{'QUERY_STRING'})) {
 2377:        my ($name, $value) = split(/=/,$_);
 2378:        $value =~ tr/+/ /;
 2379:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 2380:        if (($name eq 'uname') || ($name eq 'udom') || 
 2381:            ($name eq 'usymb') || ($name eq 'ufn')) {
 2382:            unless ($ENV{'form.'.$name}) {
 2383:               $ENV{'form.'.$name}=$value;
 2384: 	   }
 2385:        }
 2386:     }
 2387: 
 2388:     if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'})) {
 2389: 	$ENV{'form.ufn'}='default_'.$1;
 2390:     }
 2391: 
 2392: # -------------------------------------- Interactive loading of specific sheet?
 2393:     if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
 2394: 	$ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
 2395:     }
 2396: # ------------------------------------------- Nothing there? Must be login user
 2397: 
 2398:     my $aname;
 2399:     my $adom;
 2400: 
 2401:     unless ($ENV{'form.uname'}) {
 2402: 	$aname=$ENV{'user.name'};
 2403:         $adom=$ENV{'user.domain'};
 2404:     } else {
 2405:         $aname=$ENV{'form.uname'};
 2406:         $adom=$ENV{'form.udom'};
 2407:     }
 2408: 
 2409: # ------------------------------------------------------------------- Open page
 2410: 
 2411:     $r->content_type('text/html');
 2412:     $r->header_out('Cache-control','no-cache');
 2413:     $r->header_out('Pragma','no-cache');
 2414:     $r->send_http_header;
 2415: 
 2416: # --------------------------------------------------------------- Screen output
 2417: 
 2418:     $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
 2419:     $r->print(<<ENDSCRIPT);
 2420: <script language="JavaScript">
 2421: 
 2422:     function celledit(cn,cf) {
 2423:         var cnf=prompt(cn,cf);
 2424:         if (cnf!=null) {
 2425:             document.sheet.unewfield.value=cn;
 2426:             document.sheet.unewformula.value=cnf;
 2427:             document.sheet.submit();
 2428:         }
 2429:     }
 2430: 
 2431:     function changesheet(cn) {
 2432: 	document.sheet.unewfield.value=cn;
 2433:         document.sheet.unewformula.value='changesheet';
 2434:         document.sheet.submit();
 2435:     }
 2436: 
 2437: </script>
 2438: ENDSCRIPT
 2439:     $r->print('</head><body bgcolor="#FFFFFF">'.
 2440:        '<img align=right src=/adm/lonIcons/lonlogos.gif>'.
 2441:        '<h1>LON-CAPA Spreadsheet</h1>'.
 2442:        '<form action="'.$r->uri.'" name=sheet method=post>'.
 2443:        &hiddenfield('uname',$ENV{'form.uname'}).
 2444:        &hiddenfield('udom',$ENV{'form.udom'}).
 2445:        &hiddenfield('usymb',$ENV{'form.usymb'}).
 2446:        &hiddenfield('unewfield','').
 2447:        &hiddenfield('unewformula',''));
 2448: 
 2449: # ---------------------- Make sure that this gets out, even if user hits "stop"
 2450: 
 2451:     $r->rflush();
 2452: 
 2453: # ---------------------------------------------------------------- Full recalc?
 2454: 
 2455: 
 2456:     if ($ENV{'form.forcerecalc'}) {
 2457: 	$r->print('<h4>Completely Recalculating Sheet ...</h4>');
 2458:         undef %spreadsheets;
 2459:         undef %courserdatas;
 2460:         undef %userrdatas;
 2461:         undef %defaultsheets;
 2462:         undef %updatedata;
 2463:    }
 2464:  
 2465: # ---------------------------------------- Read new sheet or modified worksheet
 2466: 
 2467:     $r->uri=~/\/(\w+)$/;
 2468: 
 2469:     my $asheet=&makenewsheet($aname,$adom,$1,$ENV{'form.usymb'});
 2470: 
 2471: # ------------------------ If a new formula had been entered, go from work copy
 2472: 
 2473:     if ($ENV{'form.unewfield'}) {
 2474:         $r->print('<h2>Modified Workcopy</h2>');
 2475:         $ENV{'form.unewformula'}=~s/\'/\"/g;
 2476:         $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
 2477:                   $ENV{'form.unewformula'}.'<p>');
 2478:         &setfilename($asheet,$ENV{'form.ufn'});
 2479: 	&tmpread($asheet,
 2480:                  $ENV{'form.unewfield'},$ENV{'form.unewformula'});
 2481: 
 2482:      } elsif ($ENV{'form.saveas'}) {
 2483:         &setfilename($asheet,$ENV{'form.ufn'});
 2484: 	&tmpread($asheet);
 2485:     } else {
 2486:         &readsheet($asheet,$ENV{'form.ufn'});
 2487:     }
 2488: 
 2489: # -------------------------------------------------- Print out user information
 2490: 
 2491:     unless (&gettype($asheet) eq 'classcalc') {
 2492:         $r->print('<p><b>User:</b> '.&getuname($asheet).
 2493:                   '<br><b>Domain:</b> '.&getudom($asheet));
 2494:         if (&getcsec($asheet) eq '-1') {
 2495:            $r->print('<h3><font color=red>'.
 2496:                      'Not a student in this course</font></h3>');
 2497:         } else {
 2498:            $r->print('<br><b>Section/Group:</b> '.&getcsec($asheet));
 2499:         }
 2500:         if ($ENV{'form.usymb'}) {
 2501:            $r->print('<br><b>Assessment:</b> <tt>'.$ENV{'form.usymb'}.'</tt>');
 2502:         }
 2503:     }
 2504: 
 2505: # ---------------------------------------------------------------- Course title
 2506: 
 2507:     $r->print('<h1>'.
 2508:             $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.
 2509:              '</h1><h3>'.localtime().'</h3>');
 2510: 
 2511: # ---------------------------------------------------- See if user can see this
 2512: 
 2513:     if ((&gettype($asheet) eq 'classcalc') || 
 2514:         (&getuname($asheet) ne $ENV{'user.name'}) ||
 2515:         (&getudom($asheet) ne $ENV{'user.domain'})) {
 2516:         unless (&Apache::lonnet::allowed('vgr',&getcid($asheet))) {
 2517: 	    $r->print(
 2518:            '<h1>Access Permission Denied</h1></form></body></html>');
 2519:             return OK;
 2520:         }
 2521:     }
 2522: 
 2523: # ---------------------------------------------------------- Additional options
 2524: 
 2525:     $r->print(
 2526:  '<input type=submit name=forcerecalc value="Completely Recalculate Sheet"><p>'
 2527: 		 );
 2528:     if (&gettype($asheet) eq 'assesscalc') {
 2529:        $r->print ('<p><font size=+2><a href="/adm/studentcalc?uname='.
 2530:                                                &getuname($asheet).
 2531:                                                '&udom='.&getudom($asheet).
 2532:                   '">Level up: Student Sheet</a></font><p>');
 2533:     }
 2534:     
 2535:     if ((&gettype($asheet) eq 'studentcalc') && 
 2536:         (&Apache::lonnet::allowed('vgr',&getcid($asheet)))) {
 2537:        $r->print (
 2538:                    '<p><font size=+2><a href="/adm/classcalc">'.
 2539:                    'Level up: Course Sheet</a></font><p>');
 2540:     }
 2541:     
 2542: 
 2543: # ----------------------------------------------------------------- Save dialog
 2544: 
 2545: 
 2546:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2547:         my $fname=$ENV{'form.ufn'};
 2548:         $fname=~s/\_[^\_]+$//;
 2549:         if ($fname eq 'default') { $fname='course_default'; }
 2550:         $r->print('<input type=submit name=saveas value="Save as ...">'.
 2551:               '<input type=text size=20 name=newfn value="'.$fname.
 2552:               '"> (make default: <input type=checkbox name="makedefufn">)<p>');
 2553:     }
 2554: 
 2555:     $r->print(&hiddenfield('ufn',&getfilename($asheet)));
 2556: 
 2557: # ----------------------------------------------------------------- Load dialog
 2558:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2559: 	$r->print('<p><input type=submit name=load value="Load ...">'.
 2560:                   '<select name="loadthissheet">'.
 2561:                   '<option name="default">Default</option>');
 2562:         foreach (&othersheets($asheet,&gettype($asheet))) {
 2563: 	    $r->print('<option name="'.$_.'"');
 2564:             if ($ENV{'form.ufn'} eq $_) {
 2565:                $r->print(' selected');
 2566:             }
 2567:             $r->print('>'.$_.'</option>');
 2568:         } 
 2569:         $r->print('</select><p>');
 2570:         if (&gettype($asheet) eq 'studentcalc') {
 2571: 	    &setothersheets($asheet,&othersheets($asheet,'assesscalc'));
 2572:         }
 2573:     }
 2574: 
 2575: # --------------------------------------------------------------- Cached sheets
 2576: 
 2577:     &expirationdates();
 2578: 
 2579:     undef %oldsheets;
 2580:     undef %loadedcaches;
 2581: 
 2582:     if (&gettype($asheet) eq 'classcalc') {
 2583:         $r->print("Loading previously calculated student sheets ...<br>\n");
 2584:         $r->rflush();
 2585:         &cachedcsheets();
 2586:     } elsif (&gettype($asheet) eq 'studentcalc') {
 2587:         $r->print("Loading previously calculated assessment sheets ...<br>\n");
 2588:         $r->rflush();
 2589:         &cachedssheets(&getuname($asheet),&getudom($asheet),
 2590:                        &getuhome($asheet));
 2591:     }
 2592: 
 2593: # ----------------------------------------------------- Update sheet, load rows
 2594: 
 2595:     $r->print("Loaded sheet(s), updating rows ...<br>\n");
 2596:     $r->rflush();
 2597: 
 2598:     &updatesheet($asheet);
 2599: 
 2600:     $r->print("Updated rows, loading row data ...<br>\n");
 2601:     $r->rflush();
 2602: 
 2603:     &loadrows($asheet,$r);
 2604: 
 2605:     $r->print("Loaded row data, calculating sheet ...<br>\n");
 2606:     $r->rflush();
 2607: 
 2608:     my $calcoutput=&calcsheet($asheet);
 2609:     $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
 2610: 
 2611: # ---------------------------------------------------- See if something to save
 2612: 
 2613:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2614:         my $fname='';
 2615: 	if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
 2616:             $fname=~s/\W/\_/g;
 2617:             if ($fname eq 'default') { $fname='course_default'; }
 2618:             $fname.='_'.&gettype($asheet);
 2619:             &setfilename($asheet,$fname);
 2620:             $ENV{'form.ufn'}=$fname;
 2621: 	    $r->print('<p>Saving spreadsheet: '.
 2622:                          &writesheet($asheet,$ENV{'form.makedefufn'}).'<p>');
 2623: 	}
 2624:     }
 2625: 
 2626: # ------------------------------------------------ Write the modified worksheet
 2627: 
 2628:    $r->print('<b>Current sheet:</b> '.&getfilename($asheet).'<p>');
 2629: 
 2630:    &tmpwrite($asheet);
 2631: 
 2632:     if (&gettype($asheet) eq 'studentcalc') {
 2633: 	$r->print('<br>Show rows with empty A column: ');
 2634:     } else {
 2635:         $r->print('<br>Show empty rows: ');
 2636:     } 
 2637: 
 2638:     $r->print(&hiddenfield('userselhidden','true').
 2639:              '<input type=checkbox name=showall onClick="submit()"');
 2640: 
 2641:     if ($ENV{'form.showall'}) { 
 2642:        $r->print(' checked'); 
 2643:     } else {
 2644: 	unless ($ENV{'form.userselhidden'}) {
 2645:            unless 
 2646: 	($ENV{'course.'.$ENV{'request.course.id'}.'.hideemptyrows'} eq 'yes') {
 2647:           $r->print(' checked');
 2648:           $ENV{'form.showall'}=1;
 2649:            }
 2650:        }
 2651:     }
 2652:     $r->print('>');
 2653: 
 2654:     if (&gettype($asheet) eq 'classcalc') {
 2655:        $r->print(
 2656:    ' Output CSV format: <input type=checkbox name=showcsv onClick="submit()"');
 2657:        if ($ENV{'form.showcsv'}) { $r->print(' checked'); }
 2658:        $r->print('>');
 2659:     }
 2660: # ------------------------------------------------------------- Print out sheet
 2661: 
 2662:     &outsheet($r,$asheet);
 2663:     $r->print('</form></body></html>');
 2664: 
 2665: # ------------------------------------------------------------------------ Done
 2666:   } else {
 2667: # ----------------------------- Not in a course, or not allowed to modify parms
 2668:       $ENV{'user.error.msg'}=
 2669:         $r->uri.":opa:0:0:Cannot modify spreadsheet";
 2670:       return HTTP_NOT_ACCEPTABLE; 
 2671:   }
 2672:     return OK;
 2673: 
 2674: }
 2675: 
 2676: 1;
 2677: __END__
 2678: 
 2679: 
 2680: 
 2681: 

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