File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.53: download - view: text, annotated - select for diffs
Thu Apr 5 21:35:02 2001 UTC (23 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Access control, forced recalc, and level up.

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

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