File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.79: download - view: text, annotated - select for diffs
Tue Jan 22 10:05:24 2002 UTC (22 years, 4 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
gpl header

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

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