File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.63: download - view: text, annotated - select for diffs
Thu Sep 13 15:55:40 2001 UTC (22 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Less silly, and still not good.

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

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