File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.62: download - view: text, annotated - select for diffs
Wed Sep 12 21:07:20 2001 UTC (22 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Somewhat silly version.

    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 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:     my $headerrow='';
  680:     if ((($n-1)/25)==int(($n-1)/25)) {
  681:         my $what='Student';
  682:         if (&gettype($safeeval) eq 'assesscalc') {
  683: 	    $what='Item';
  684: 	} elsif (&gettype($safeeval) eq 'studentcalc') {
  685:             $what='Assessment';
  686:         }
  687: 	$headerrow.="</table>\n<br><table border=2>".
  688:         '<tr><td>&nbsp;<td>'.$what.'</td>';
  689:         map {
  690:            $headerrow.='<td>'.$_.'</td>';
  691:         } ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  692:            'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  693:            'a','b','c','d','e','f','g','h','i','j','k','l','m',
  694:            'n','o','p','q','r','s','t','u','v','w','x','y','z');
  695:         $headerrow.='</tr>';
  696:     }
  697:     $rowdata.="\n<tr><td><b><font size=+1>$n</font></b></td>";
  698:     my $showf=0;
  699:     my $proc;
  700:     my $maxred;
  701:     my $sheettype=&gettype($safeeval);
  702:     if ($sheettype eq 'studentcalc') {
  703:         $proc='&outrowassess';
  704:         $maxred=26;
  705:     } else {
  706:         $proc='&outrow';
  707:     }
  708:     if ($sheettype eq 'assesscalc') {
  709:         $maxred=1;
  710:     } else {
  711:         $maxred=26;
  712:     }
  713:     if ($n eq '-') { $proc='&templaterow'; $n=-1; $dataflag=1; }
  714:     map {
  715:        my $bgcolor=$defaultbg.((($showf-1)/5==int(($showf-1)/5))?'99':'DD');
  716:        my ($fm,$vl)=split(/\_\_\_eq\_\_\_/,$_);
  717:        if ((($vl ne '') || ($vl eq '0')) &&
  718:            (($showf==1) || ($sheettype ne 'studentcalc'))) { $dataflag=1; }
  719:        if ($showf==0) { $vl=$_; }
  720:        if ($showf<=$maxred) { $bgcolor='#FFDDDD'; }
  721:        if (($n==0) && ($showf<=26)) { $bgcolor='#CCCCFF'; } 
  722:        if (($showf>$maxred) || ((!$n) && ($showf>0))) {
  723: 	   if ($vl eq '') {
  724: 	       $vl='<font size=+2 color='.$bgcolor.'>&#35;</font>';
  725:            }
  726:            $rowdata.=
  727:        '<td bgcolor='.$bgcolor.'><a href="javascript:celledit('.$fm.');">'.$vl.
  728: 	       '</a></td>';
  729:        } else {
  730:            $rowdata.='<td bgcolor='.$bgcolor.'>&nbsp;'.$vl.'&nbsp;</td>';
  731:        }
  732:        $showf++;
  733:     } $safeeval->reval($proc.'('.$n.')');
  734:     if ($ENV{'form.showall'} || ($dataflag)) {
  735:        return $headerrow.$rowdata.'</tr>';
  736:     } else {
  737:        return $headerrow;
  738:     }
  739: }
  740: 
  741: # ------------------------------------------------------------- Print out sheet
  742: 
  743: sub outsheet {
  744:     my ($r,$safeeval)=@_;
  745:     my $maxred;
  746:     my $realm;
  747:     if (&gettype($safeeval) eq 'assesscalc') {
  748:         $maxred=1;
  749:         $realm='Assessment';
  750:     } elsif (&gettype($safeeval) eq 'studentcalc') {
  751:         $maxred=26;
  752:         $realm='User';
  753:     } else {
  754:         $maxred=26;
  755:         $realm='Course';
  756:     }
  757:     my $maxyellow=52-$maxred;
  758:     my $tabledata=
  759:         '<table border=2><tr><th colspan=2 rowspan=2><font size=+2>'.
  760:                   $realm.'</font></th>'.
  761:                   '<td bgcolor=#FFDDDD colspan='.$maxred.
  762:                   '><b><font size=+1>Import</font></b></td>'.
  763:                   '<td colspan='.$maxyellow.
  764: 		  '><b><font size=+1>Calculations</font></b></td></tr><tr>';
  765:     my $showf=0;
  766:     map {
  767:         $showf++;
  768:         if ($showf<=$maxred) { 
  769:            $tabledata.='<td bgcolor="#FFDDDD">'; 
  770:         } else {
  771:            $tabledata.='<td>';
  772:         }
  773:         $tabledata.="<b><font size=+1>$_</font></b></td>";
  774:     } ('A','B','C','D','E','F','G','H','I','J','K','L','M',
  775:        'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
  776:        'a','b','c','d','e','f','g','h','i','j','k','l','m',
  777:        'n','o','p','q','r','s','t','u','v','w','x','y','z');
  778:     $tabledata.='</tr>';
  779:     my $row;
  780:     my $maxrow=&getmaxrow($safeeval);
  781:     $tabledata.=&rown($safeeval,'-');
  782:     $r->print($tabledata);
  783:     for ($row=0;$row<=$maxrow;$row++) {
  784:         $r->print(&rown($safeeval,$row));
  785:     }
  786:     $r->print('</table>');
  787: }
  788: 
  789: #
  790: # ----------------------------------------------- Read list of available sheets
  791: # 
  792: 
  793: sub othersheets {
  794:     my ($safeeval,$stype)=@_;
  795: 
  796:     my $cnum=&getcnum($safeeval);
  797:     my $cdom=&getcdom($safeeval);
  798:     my $chome=&getchome($safeeval);
  799: 
  800:     my @alternatives=();
  801:     my $result=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.':'.
  802:                                       $stype.'_spreadsheets',$chome);
  803:     if ($result!~/^error\:/) {
  804: 	map {
  805:             $alternatives[$#alternatives+1]=
  806:             &Apache::lonnet::unescape((split(/\=/,$_))[0]);
  807:         } split(/\&/,$result);
  808:     } 
  809:     return @alternatives; 
  810: }
  811: 
  812: #
  813: # -------------------------------------- Read spreadsheet formulas for a course
  814: #
  815: 
  816: sub readsheet {
  817:   my ($safeeval,$fn)=@_;
  818:   my $stype=&gettype($safeeval);
  819:   my $cnum=&getcnum($safeeval);
  820:   my $cdom=&getcdom($safeeval);
  821:   my $chome=&getchome($safeeval);
  822: 
  823: # --------- There is no filename. Look for defaults in course and global, cache
  824: 
  825:   unless($fn) {
  826:       unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
  827:          $fn=&Apache::lonnet::reply('get:'.$cdom.':'.$cnum.
  828:                                     ':environment:spreadsheet_default_'.$stype,
  829:                                     $chome);
  830:          unless (($fn) && ($fn!~/^error\:/)) {
  831: 	     $fn='default_'.$stype;
  832:          }
  833:          $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn; 
  834:       }
  835:   }
  836: 
  837: # ---------------------------------------------------------- fn now has a value
  838: 
  839:   &setfilename($safeeval,$fn);
  840: 
  841: # ------------------------------------------------------ see if sheet is cached
  842:   my $fstring='';
  843:   if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
  844:       &setformulas($safeeval,split(/\_\_\_\;\_\_\_/,$fstring));
  845:   } else {
  846: 
  847: # ---------------------------------------------------- Not cached, need to read
  848: 
  849:      my %f=();
  850: 
  851:      if ($fn=~/^default\_/) {
  852: 	my $sheetxml='';
  853:        {
  854:          my $fh;
  855:          if ($fh=Apache::File->new($includedir.
  856:                          '/default.'.&gettype($safeeval))) {
  857:                $sheetxml=join('',<$fh>);
  858:           }
  859:        }
  860:         my $parser=HTML::TokeParser->new(\$sheetxml);
  861:         my $token;
  862:         while ($token=$parser->get_token) {
  863:           if ($token->[0] eq 'S') {
  864:  	     if ($token->[1] eq 'field') {
  865:  		 $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
  866:  		     $parser->get_text('/field');
  867:  	     }
  868:              if ($token->[1] eq 'template') {
  869:                  $f{'template_'.$token->[2]->{'col'}}=
  870:                      $parser->get_text('/template');
  871:              }
  872:           }
  873:         }
  874:       } else {
  875:           my $sheet='';
  876:           my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.':'.$fn,
  877:                                          $chome);
  878:           unless ($reply=~/^error\:/) {
  879:              $sheet=$reply;
  880: 	  }
  881:           map {
  882:              my ($name,$value)=split(/\=/,$_);
  883:              $f{&Apache::lonnet::unescape($name)}=
  884: 	        &Apache::lonnet::unescape($value);
  885:           } split(/\&/,$sheet);
  886:        }
  887: # --------------------------------------------------------------- Cache and set
  888:        $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);  
  889:        &setformulas($safeeval,%f);
  890:     }
  891: }
  892: 
  893: # -------------------------------------------------------- Make new spreadsheet
  894: 
  895: sub makenewsheet {
  896:     my ($uname,$udom,$stype,$usymb)=@_;
  897:     my $safeeval=initsheet($stype);
  898:     $safeeval->reval(
  899:        '$uname="'.$uname.
  900:       '";$udom="'.$udom.
  901:       '";$uhome="'.&Apache::lonnet::homeserver($uname,$udom).
  902:       '";$sheettype="'.$stype.
  903:       '";$usymb="'.$usymb.
  904:       '";$csec="'.&Apache::lonnet::usection($udom,$uname,
  905:                                             $ENV{'request.course.id'}).
  906:       '";$cid="'.$ENV{'request.course.id'}.
  907:       '";$cfn="'.$ENV{'request.course.fn'}.
  908:       '";$cnum="'.$ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
  909:       '";$cdom="'.$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
  910:       '";$chome="'.$ENV{'course.'.$ENV{'request.course.id'}.'.home'}.'";');
  911:     return $safeeval;
  912: }
  913: 
  914: # ------------------------------------------------------------ Save spreadsheet
  915: 
  916: sub writesheet {
  917:   my ($safeeval,$makedef)=@_;
  918:   my $cid=&getcid($safeeval);
  919:   if (&Apache::lonnet::allowed('opa',$cid)) {
  920:     my %f=&getformulas($safeeval);
  921:     my $stype=&gettype($safeeval);
  922:     my $cnum=&getcnum($safeeval);
  923:     my $cdom=&getcdom($safeeval);
  924:     my $chome=&getchome($safeeval);
  925:     my $fn=&getfilename($safeeval);
  926: 
  927: # ------------------------------------------------------------- Cache new sheet
  928:     $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);    
  929: # ----------------------------------------------------------------- Write sheet
  930:     my $sheetdata='';
  931:     map {
  932:      unless ($f{$_} eq 'import') {
  933:        $sheetdata.=&Apache::lonnet::escape($_).'='.
  934: 	   &Apache::lonnet::escape($f{$_}).'&';
  935:      }
  936:     } keys %f;
  937:     $sheetdata=~s/\&$//;
  938:     my $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.$fn.':'.
  939:               $sheetdata,$chome);
  940:     if ($reply eq 'ok') {
  941:           $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.
  942:               $stype.'_spreadsheets:'.
  943:               &Apache::lonnet::escape($fn).'='.$ENV{'user.name'}.'@'.
  944:                                                $ENV{'user.domain'},
  945:               $chome);
  946:           if ($reply eq 'ok') {
  947:               if ($makedef) { 
  948:                 return &Apache::lonnet::reply('put:'.$cdom.':'.$cnum.
  949:                                 ':environment:spreadsheet_default_'.$stype.'='.
  950:                                 &Apache::lonnet::escape($fn),
  951:                                 $chome);
  952: 	      } else {
  953: 		  return $reply;
  954:     	      }
  955: 	   } else {
  956: 	       return $reply;
  957:            }
  958:       } else {
  959: 	  return $reply;
  960:       }
  961:   }
  962:   return 'unauthorized';
  963: }
  964: 
  965: # ----------------------------------------------- Make a temp copy of the sheet
  966: # "Modified workcopy" - interactive only
  967: #
  968: 
  969: sub tmpwrite {
  970:     my $safeeval=shift;
  971:     my $fn=$ENV{'user.name'}.'_'.
  972:            $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
  973:            &getfilename($safeeval);
  974:     $fn=~s/\W/\_/g;
  975:     $fn=$tmpdir.$fn.'.tmp';
  976:     my $fh;
  977:     if ($fh=Apache::File->new('>'.$fn)) {
  978: 	print $fh join("\n",&getformulas($safeeval));
  979:     }
  980: }
  981: 
  982: # ---------------------------------------------------------- Read the temp copy
  983: 
  984: sub tmpread {
  985:     my ($safeeval,$nfield,$nform)=@_;
  986:     my $fn=$ENV{'user.name'}.'_'.
  987:            $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
  988:            &getfilename($safeeval);
  989:     $fn=~s/\W/\_/g;
  990:     $fn=$tmpdir.$fn.'.tmp';
  991:     my $fh;
  992:     my %fo=();
  993:     if ($fh=Apache::File->new($fn)) {
  994:         my $name;
  995:         while ($name=<$fh>) {
  996: 	    chomp($name);
  997:             my $value=<$fh>;
  998:             chomp($value);
  999:             $fo{$name}=$value;
 1000:         }
 1001:     }
 1002:     if ($nform eq 'changesheet') {
 1003:         $fo{'A'.$nfield}=(split(/\_\_\&\&\&\_\_/,$fo{'A'.$nfield}))[0];
 1004:         unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
 1005: 	    $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
 1006:         }
 1007:     } else {
 1008:        if ($nfield) { $fo{$nfield}=$nform; }
 1009:     }
 1010:     &setformulas($safeeval,%fo);
 1011: }
 1012: 
 1013: # ================================================================== Parameters
 1014: # -------------------------------------------- Figure out a cascading parameter
 1015: #
 1016: # For this function to work
 1017: #
 1018: # * parmhash needs to be tied
 1019: # * courseopt and useropt need to be initialized for this user and course
 1020: #
 1021: 
 1022: sub parmval {
 1023:     my ($what,$safeeval)=@_;
 1024:     my $cid=&getcid($safeeval);
 1025:     my $csec=&getcsec($safeeval);
 1026:     my $uname=&getuname($safeeval);
 1027:     my $udom=&getudom($safeeval);
 1028:     my $symb=&getusymb($safeeval);
 1029: 
 1030:     unless ($symb) { return ''; }
 1031:     my $result='';
 1032: 
 1033:     my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
 1034: # ----------------------------------------------------- Cascading lookup scheme
 1035:        my $rwhat=$what;
 1036:        $what=~s/^parameter\_//;
 1037:        $what=~s/\_/\./;
 1038: 
 1039:        my $symbparm=$symb.'.'.$what;
 1040:        my $mapparm=$mapname.'___(all).'.$what;
 1041:        my $usercourseprefix=$uname.'_'.$udom.'_'.$cid;
 1042: 
 1043:        my $seclevel=
 1044:             $usercourseprefix.'.['.
 1045: 		$csec.'].'.$what;
 1046:        my $seclevelr=
 1047:             $usercourseprefix.'.['.
 1048: 		$csec.'].'.$symbparm;
 1049:        my $seclevelm=
 1050:             $usercourseprefix.'.['.
 1051: 		$csec.'].'.$mapparm;
 1052: 
 1053:        my $courselevel=
 1054:             $usercourseprefix.'.'.$what;
 1055:        my $courselevelr=
 1056:             $usercourseprefix.'.'.$symbparm;
 1057:        my $courselevelm=
 1058:             $usercourseprefix.'.'.$mapparm;
 1059: 
 1060: # ---------------------------------------------------------- fourth, check user
 1061:       
 1062:       if ($uname) { 
 1063: 
 1064:        if ($useropt{$courselevelr}) { return $useropt{$courselevelr}; }
 1065: 
 1066:        if ($useropt{$courselevelm}) { return $useropt{$courselevelm}; }
 1067: 
 1068:        if ($useropt{$courselevel}) { return $useropt{$courselevel}; }
 1069: 
 1070:       }
 1071: 
 1072: # --------------------------------------------------------- third, check course
 1073:      
 1074:        if ($csec) {
 1075:  
 1076:         if ($courseopt{$seclevelr}) { return $courseopt{$seclevelr}; }
 1077: 
 1078:         if ($courseopt{$seclevelm}) { return $courseopt{$seclevelm}; }  
 1079: 
 1080:         if ($courseopt{$seclevel}) { return $courseopt{$seclevel}; }
 1081:   
 1082:       }
 1083: 
 1084:        if ($courseopt{$courselevelr}) { return $courseopt{$courselevelr}; }
 1085: 
 1086:        if ($courseopt{$courselevelm}) { return $courseopt{$courselevelm}; }
 1087: 
 1088:        if ($courseopt{$courselevel}) { return $courseopt{$courselevel}; }
 1089: 
 1090: # ----------------------------------------------------- second, check map parms
 1091: 
 1092:        my $thisparm=$parmhash{$symbparm};
 1093:        if ($thisparm) { return $thisparm; }
 1094: 
 1095: # -------------------------------------------------------- first, check default
 1096: 
 1097:        return &Apache::lonnet::metadata($fn,$rwhat.'.default');
 1098:         
 1099: }
 1100: 
 1101: # ---------------------------------------------- Update rows for course listing
 1102: 
 1103: sub updateclasssheet {
 1104:     my $safeeval=shift;
 1105:     my $cnum=&getcnum($safeeval);
 1106:     my $cdom=&getcdom($safeeval);
 1107:     my $cid=&getcid($safeeval);
 1108:     my $chome=&getchome($safeeval);
 1109: 
 1110: # ---------------------------------------------- Read class list and row labels
 1111: 
 1112:     my $classlst=&Apache::lonnet::reply
 1113:                                  ('dump:'.$cdom.':'.$cnum.':classlist',$chome);
 1114:     my %currentlist=();
 1115:     my $now=time;
 1116:     unless ($classlst=~/^error\:/) {
 1117:         map {
 1118:             my ($name,$value)=split(/\=/,$_);
 1119:             my ($end,$start)=split(/\:/,&Apache::lonnet::unescape($value));
 1120:             my $active=1;
 1121:             if (($end) && ($now>$end)) { $active=0; }
 1122:             if ($active) {
 1123:                 my $rowlabel='';
 1124:                 $name=&Apache::lonnet::unescape($name);
 1125:                 my ($sname,$sdom)=split(/\:/,$name);
 1126:                 my $ssec=&Apache::lonnet::usection($sdom,$sname,$cid);
 1127:                 if ($ssec==-1) {
 1128:                     $rowlabel='<font color=red>Data not available: '.$name.
 1129: 			      '</font>';
 1130:                 } else {
 1131:                     my %reply=&Apache::lonnet::idrget($sdom,$sname);
 1132:                     my $reply=&Apache::lonnet::reply('get:'.$sdom.':'.$sname.
 1133: 		      ':environment:firstname&middlename&lastname&generation',
 1134:                       &Apache::lonnet::homeserver($sname,$sdom));
 1135:                     $rowlabel='<a href="/adm/studentcalc?uname='.$sname.
 1136:                               '&udom='.$sdom.'">'.
 1137:                               $ssec.'&nbsp;'.$reply{$sname}.'<br>';
 1138:                     map {
 1139:                         $rowlabel.=&Apache::lonnet::unescape($_).' ';
 1140:                     } split(/\&/,$reply);
 1141:                     $rowlabel.='</a>';
 1142:                 }
 1143: 		$currentlist{&Apache::lonnet::unescape($name)}=$rowlabel;
 1144:             }
 1145:         } split(/\&/,$classlst);
 1146: #
 1147: # -------------------- Find discrepancies between the course row table and this
 1148: #
 1149:         my %f=&getformulas($safeeval);
 1150:         my $changed=0;
 1151: 
 1152:         my $maxrow=0;
 1153:         my %existing=();
 1154: 
 1155: # ----------------------------------------------------------- Now obsolete rows
 1156: 	map {
 1157: 	    if ($_=~/^A(\d+)/) {
 1158:                 $maxrow=($1>$maxrow)?$1:$maxrow;
 1159:                 $existing{$f{$_}}=1;
 1160: 		unless ((defined($currentlist{$f{$_}})) || (!$1)) {
 1161: 		   $f{$_}='!!! Obsolete';
 1162:                    $changed=1;
 1163:                 }
 1164:             }
 1165:         } keys %f;
 1166: 
 1167: # -------------------------------------------------------- New and unknown keys
 1168:      
 1169:         map {
 1170:             unless ($existing{$_}) {
 1171: 		$changed=1;
 1172:                 $maxrow++;
 1173:                 $f{'A'.$maxrow}=$_;
 1174:             }
 1175:         } sort keys %currentlist;        
 1176:      
 1177:         if ($changed) { &setformulas($safeeval,%f); }
 1178: 
 1179:         &setmaxrow($safeeval,$maxrow);
 1180:         &setrowlabels($safeeval,%currentlist);
 1181: 
 1182:     } else {
 1183:         return 'Could not access course data';
 1184:     }
 1185: }
 1186: 
 1187: # ----------------------------------- Update rows for student and assess sheets
 1188: 
 1189: sub updatestudentassesssheet {
 1190:     my $safeeval=shift;
 1191:     my %bighash;
 1192:     my $stype=&gettype($safeeval);
 1193:     my %current=();
 1194:     unless ($updatedata{$ENV{'request.course.fn'}.'_'.$stype}) {
 1195: # -------------------------------------------------------------------- Tie hash
 1196:       if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 1197:                        &GDBM_READER,0640)) {
 1198: # --------------------------------------------------------- Get all assessments
 1199: 
 1200: 	my %allkeys=('timestamp' => 
 1201:                      'Timestamp of Last Transaction<br>timestamp');
 1202:         my %allassess=();
 1203: 
 1204:         my $adduserstr='';
 1205:         if ((&getuname($safeeval) ne $ENV{'user.name'}) ||
 1206:             (&getudom($safeeval) ne $ENV{'user.domain'})) {
 1207:             $adduserstr='&uname='.&getuname($safeeval).
 1208: 		'&udom='.&getudom($safeeval);
 1209:         }
 1210: 
 1211:         map {
 1212: 	    if ($_=~/^src\_(\d+)\.(\d+)$/) {
 1213: 	       my $mapid=$1;
 1214:                my $resid=$2;
 1215:                my $id=$mapid.'.'.$resid;
 1216:                my $srcf=$bighash{$_};
 1217:                if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
 1218:                  my $symb=
 1219:                      &Apache::lonnet::declutter($bighash{'map_id_'.$mapid}).
 1220: 			    '___'.$resid.'___'.
 1221: 			    &Apache::lonnet::declutter($srcf);
 1222: 		 $allassess{$symb}=
 1223: 	            '<a href="/adm/assesscalc?usymb='.$symb.$adduserstr.'">'.
 1224:                      $bighash{'title_'.$id}.'</a>';
 1225:                  if ($stype eq 'assesscalc') {
 1226:                    map {
 1227:                        if (($_=~/^stores\_(.*)/) || ($_=~/^parameter\_(.*)/)) {
 1228: 			  my $key=$_;
 1229:                           my $display=
 1230: 			      &Apache::lonnet::metadata($srcf,$key.'.display');
 1231:                           unless ($display) {
 1232:                               $display.=
 1233: 			         &Apache::lonnet::metadata($srcf,$key.'.name');
 1234:                           }
 1235:                           $display.='<br>'.$key;
 1236:                           $allkeys{$key}=$display;
 1237: 		       }
 1238:                    } split(/\,/,&Apache::lonnet::metadata($srcf,'keys'));
 1239: 	         }
 1240: 	      }
 1241: 	   }
 1242:         } keys %bighash;
 1243:         untie(%bighash);
 1244:     
 1245: #
 1246: # %allkeys has a list of storage and parameter displays by unikey
 1247: # %allassess has a list of all resource displays by symb
 1248: #
 1249: 
 1250:         if ($stype eq 'assesscalc') {
 1251: 	    %current=%allkeys;
 1252:         } elsif ($stype eq 'studentcalc') {
 1253:             %current=%allassess;
 1254:         }
 1255:         $updatedata{$ENV{'request.course.fn'}.'_'.$stype}=
 1256: 	    join('___;___',%current);
 1257:     } else {
 1258:         return 'Could not access course data';
 1259:     }
 1260: # ------------------------------------------------------ Get current from cache
 1261:     } else {
 1262:         %current=split(/\_\_\_\;\_\_\_/,
 1263: 		       $updatedata{$ENV{'request.course.fn'}.'_'.$stype});
 1264:     }
 1265: # -------------------- Find discrepancies between the course row table and this
 1266: #
 1267:         my %f=&getformulas($safeeval);
 1268:         my $changed=0;
 1269: 
 1270:         my $maxrow=0;
 1271:         my %existing=();
 1272: 
 1273: # ----------------------------------------------------------- Now obsolete rows
 1274: 	map {
 1275: 	    if ($_=~/^A(\d+)/) {
 1276:                 $maxrow=($1>$maxrow)?$1:$maxrow;
 1277:                 my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
 1278:                 $existing{$usy}=1;
 1279: 		unless ((defined($current{$usy})) || (!$1)) {
 1280: 		   $f{$_}='!!! Obsolete';
 1281:                    $changed=1;
 1282: 	        } elsif ($ufn) {
 1283: 		    $current{$usy}
 1284:                        =~s/assesscalc\?usymb\=/assesscalc\?ufn\=$ufn\&usymb\=/;
 1285:                 }
 1286:             }
 1287:         } keys %f;
 1288: 
 1289: # -------------------------------------------------------- New and unknown keys
 1290:      
 1291:         map {
 1292:             unless ($existing{$_}) {
 1293: 		$changed=1;
 1294:                 $maxrow++;
 1295:                 $f{'A'.$maxrow}=$_;
 1296:             }
 1297:         } keys %current;        
 1298:     
 1299:         if ($changed) { &setformulas($safeeval,%f); }
 1300: 
 1301:         &setmaxrow($safeeval,$maxrow);
 1302:         &setrowlabels($safeeval,%current);
 1303:  
 1304:         undef %current;
 1305:         undef %existing;
 1306: }
 1307: 
 1308: # ------------------------------------------------ Load data for one assessment
 1309: 
 1310: sub loadstudent {
 1311:     my $safeeval=shift;
 1312:     my %c=();
 1313:     my %f=&getformulas($safeeval);
 1314:     $cachedassess=&getuname($safeeval).':'.&getudom($safeeval);
 1315:     %cachedstores=();
 1316:     {
 1317:       my $reply=&Apache::lonnet::reply('dump:'.&getudom($safeeval).':'.
 1318:                                                &getuname($safeeval).':'.
 1319:                                                &getcid($safeeval),
 1320:                                                &getuhome($safeeval));
 1321:       unless ($reply=~/^error\:/) {
 1322:          map {
 1323:             my ($name,$value)=split(/\=/,$_);
 1324:             $cachedstores{&Apache::lonnet::unescape($name)}=
 1325: 	                  &Apache::lonnet::unescape($value);
 1326:          } split(/\&/,$reply);
 1327:       }
 1328:     }
 1329:     my @assessdata=();
 1330:     map {
 1331: 	if ($_=~/^A(\d+)/) {
 1332: 	   my $row=$1;
 1333:            unless (($f{$_}=~/^\!/) || ($row==0)) {
 1334: 	      my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
 1335: 	      @assessdata=&exportsheet(&getuname($safeeval),
 1336:                                        &getudom($safeeval),
 1337:                                        'assesscalc',$usy,$ufn);
 1338:               my $index=0;
 1339:               map {
 1340:                   if ($assessdata[$index]) {
 1341: 		     my $col=$_;
 1342: 		     if ($assessdata[$index]=~/\D/) {
 1343:                          $c{$col.$row}="'".$assessdata[$index]."'";
 1344:  		     } else {
 1345: 		         $c{$col.$row}=$assessdata[$index];
 1346: 		     }
 1347:                      unless ($col eq 'A') { 
 1348: 			 $f{$col.$row}='import';
 1349:                      }
 1350: 		  }
 1351:                   $index++;
 1352:               } ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1353:                  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
 1354: 	   }
 1355:         }
 1356:     } keys %f;
 1357:     $cachedassess='';
 1358:     undef %cachedstores;
 1359:     &setformulas($safeeval,%f);
 1360:     &setconstants($safeeval,%c);
 1361: }
 1362: 
 1363: # --------------------------------------------------- Load data for one student
 1364: 
 1365: sub loadcourse {
 1366:     my ($safeeval,$r)=@_;
 1367:     my %c=();
 1368:     my %f=&getformulas($safeeval);
 1369:     my $total=0;
 1370:     map {
 1371: 	if ($_=~/^A(\d+)/) {
 1372: 	    unless ($f{$_}=~/^\!/) { $total++; }
 1373:         }
 1374:     } keys %f;
 1375:     my $now=0;
 1376:     my $since=time;
 1377:     $r->print(<<ENDPOP);
 1378: <script>
 1379:     popwin=open('','popwin','width=400,height=100');
 1380:     popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
 1381:       '<h3>Spreadsheet Calculation Progress</h3>'+
 1382:       '<form name=popremain>'+
 1383:       '<input type=text size=35 name=remaining value=Starting></form>'+
 1384:       '</body></html>');
 1385:     popwin.document.close();
 1386: </script>
 1387: ENDPOP
 1388:     $r->rflush();
 1389:     map {
 1390: 	if ($_=~/^A(\d+)/) {
 1391: 	   my $row=$1;
 1392:            unless (($f{$_}=~/^\!/)  || ($row==0)) {
 1393: 	      my @studentdata=&exportsheet(split(/\:/,$f{$_}),
 1394:                                            'studentcalc');
 1395:               undef %userrdatas;
 1396:               $now++;
 1397:               $r->print('<script>popwin.document.popremain.remaining.value="'.
 1398:                   $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
 1399:                         ' secs remaining";</script>');
 1400:               $r->rflush(); 
 1401: 
 1402:               my $index=0;
 1403:               map {
 1404:                   if ($studentdata[$index]) {
 1405: 		     my $col=$_;
 1406: 		     if ($studentdata[$index]=~/\D/) {
 1407:                          $c{$col.$row}="'".$studentdata[$index]."'";
 1408:  		     } else {
 1409: 		         $c{$col.$row}=$studentdata[$index];
 1410: 		     }
 1411:                      unless ($col eq 'A') { 
 1412: 			 $f{$col.$row}='import';
 1413:                      }
 1414: 		  }
 1415:                   $index++;
 1416:               } ('A','B','C','D','E','F','G','H','I','J','K','L','M',
 1417:                  'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
 1418: 	   }
 1419:         }
 1420:     } keys %f;
 1421:     &setformulas($safeeval,%f);
 1422:     &setconstants($safeeval,%c);
 1423:     $r->print('<script>popwin.close()</script>');
 1424:     $r->rflush(); 
 1425: }
 1426: 
 1427: # ------------------------------------------------ Load data for one assessment
 1428: 
 1429: sub loadassessment {
 1430:     my $safeeval=shift;
 1431: 
 1432:     my $uhome=&getuhome($safeeval);
 1433:     my $uname=&getuname($safeeval);
 1434:     my $udom=&getudom($safeeval);
 1435:     my $symb=&getusymb($safeeval);
 1436:     my $cid=&getcid($safeeval);
 1437:     my $cnum=&getcnum($safeeval);
 1438:     my $cdom=&getcdom($safeeval);
 1439:     my $chome=&getchome($safeeval);
 1440: 
 1441:     my $namespace;
 1442:     unless ($namespace=$cid) { return ''; }
 1443: 
 1444: # ----------------------------------------------------------- Get stored values
 1445: 
 1446:    my %returnhash=();
 1447: 
 1448:    if ($cachedassess eq $uname.':'.$udom) {
 1449: #
 1450: # get data out of the dumped stores
 1451: # 
 1452: 
 1453:        my $version=$cachedstores{'version:'.$symb};
 1454:        my $scope;
 1455:        for ($scope=1;$scope<=$version;$scope++) {
 1456:            map {
 1457:                $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
 1458:            } split(/\:/,$cachedstores{$scope.':keys:'.$symb}); 
 1459:        }
 1460: 
 1461:    } else {
 1462: #
 1463: # restore individual
 1464: #
 1465: 
 1466:     my $answer=&Apache::lonnet::reply(
 1467:        "restore:$udom:$uname:".
 1468:        &Apache::lonnet::escape($namespace).":".
 1469:        &Apache::lonnet::escape($symb),$uhome);
 1470:     map {
 1471: 	my ($name,$value)=split(/\=/,$_);
 1472:         $returnhash{&Apache::lonnet::unescape($name)}=
 1473:                     &Apache::lonnet::unescape($value);
 1474:     } split(/\&/,$answer);
 1475:     my $version;
 1476:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 1477:        map {
 1478:           $returnhash{$_}=$returnhash{$version.':'.$_};
 1479:        } split(/\:/,$returnhash{$version.':keys'});
 1480:     }
 1481:    }
 1482: # ----------------------------- returnhash now has all stores for this resource
 1483: 
 1484: # ---------------------------- initialize coursedata and userdata for this user
 1485:     undef %courseopt;
 1486:     undef %useropt;
 1487: 
 1488:     my $userprefix=$uname.'_'.$udom.'_';
 1489: 
 1490:     unless ($uhome eq 'no_host') { 
 1491: # -------------------------------------------------------------- Get coursedata
 1492:       unless
 1493:         ((time-$courserdatas{$cid.'.last_cache'})<240) {
 1494:          my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
 1495:               ':resourcedata',$chome);
 1496:          if ($reply!~/^error\:/) {
 1497:             $courserdatas{$cid}=$reply;
 1498:             $courserdatas{$cid.'.last_cache'}=time;
 1499:          }
 1500:       }
 1501:       map {
 1502:          my ($name,$value)=split(/\=/,$_);
 1503:          $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
 1504:                     &Apache::lonnet::unescape($value);  
 1505:       } split(/\&/,$courserdatas{$cid});
 1506: # --------------------------------------------------- Get userdata (if present)
 1507:       unless
 1508:         ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
 1509:          my $reply=
 1510:        &Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
 1511:          if ($reply!~/^error\:/) {
 1512: 	     $userrdatas{$uname.'___'.$udom}=$reply;
 1513: 	     $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
 1514:          }
 1515:       }
 1516:       map {
 1517:          my ($name,$value)=split(/\=/,$_);
 1518:          $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
 1519: 	          &Apache::lonnet::unescape($value);
 1520:       } split(/\&/,$userrdatas{$uname.'___'.$udom});
 1521:     }
 1522: # ----------------- now courseopt, useropt initialized for this user and course
 1523: # (used by parmval)
 1524: 
 1525: #
 1526: # Load keys for this assessment only
 1527: #
 1528:     my %thisassess=();
 1529:     my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
 1530:     
 1531:     map {
 1532:         $thisassess{$_}=1;
 1533:     } split(/\,/,&Apache::lonnet::metadata($srcf,'keys'));
 1534: #
 1535: # Load parameters
 1536: #
 1537:    my %c=();
 1538: 
 1539:    if (tie(%parmhash,'GDBM_File',
 1540:            &getcfn($safeeval).'_parms.db',&GDBM_READER,0640)) {
 1541:     my %f=&getformulas($safeeval);
 1542:     map {
 1543: 	if ($_=~/^A/) {
 1544:             unless ($f{$_}=~/^\!/) {
 1545:   	       if ($f{$_}=~/^parameter/) {
 1546: 		if ($thisassess{$f{$_}}) {
 1547:                   my $val=&parmval($f{$_},$safeeval);
 1548:                   $c{$_}=$val;
 1549:                   $c{$f{$_}}=$val;
 1550: 	        }
 1551: 	       } else {
 1552: 		  my $key=$f{$_};
 1553:                   my $ckey=$key;
 1554:                   $key=~s/^stores\_/resource\./;
 1555:                   $key=~s/\_/\./;
 1556:  	          $c{$_}=$returnhash{$key};
 1557:                   $c{$ckey}=$returnhash{$key};
 1558: 	       }
 1559: 	   }
 1560:         }
 1561:     } keys %f;
 1562:     untie(%parmhash);
 1563:    }
 1564:    &setconstants($safeeval,%c);
 1565: }
 1566: 
 1567: # --------------------------------------------------------- Various form fields
 1568: 
 1569: sub textfield {
 1570:     my ($title,$name,$value)=@_;
 1571:     return "\n<p><b>$title:</b><br>".
 1572:            '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
 1573: }
 1574: 
 1575: sub hiddenfield {
 1576:     my ($name,$value)=@_;
 1577:     return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
 1578: }
 1579: 
 1580: sub selectbox {
 1581:     my ($title,$name,$value,%options)=@_;
 1582:     my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
 1583:     map {
 1584:         $selout.='<option value="'.$_.'"';
 1585:         if ($_ eq $value) { $selout.=' selected'; }
 1586:         $selout.='>'.$options{$_}.'</option>';
 1587:     } sort keys %options;
 1588:     return $selout.'</select>';
 1589: }
 1590: 
 1591: # =============================================== Update information in a sheet
 1592: #
 1593: # Add new users or assessments, etc.
 1594: #
 1595: 
 1596: sub updatesheet {
 1597:     my $safeeval=shift;
 1598:     my $stype=&gettype($safeeval);
 1599:     if ($stype eq 'classcalc') {
 1600: 	return &updateclasssheet($safeeval);
 1601:     } else {
 1602:         return &updatestudentassesssheet($safeeval);
 1603:     }
 1604: }
 1605: 
 1606: # =================================================== Load the rows for a sheet
 1607: #
 1608: # Import the data for rows
 1609: #
 1610: 
 1611: sub loadrows {
 1612:     my ($safeeval,$r)=@_;
 1613:     my $stype=&gettype($safeeval);
 1614:     if ($stype eq 'classcalc') {
 1615: 	&loadcourse($safeeval,$r);
 1616:     } elsif ($stype eq 'studentcalc') {
 1617:         &loadstudent($safeeval);
 1618:     } else {
 1619:         &loadassessment($safeeval);
 1620:     }
 1621: }
 1622: 
 1623: # ======================================================= Forced recalculation?
 1624: 
 1625: sub checkthis {
 1626:     my ($keyname,$time)=@_;
 1627:     return ($time<$expiredates{$keyname});
 1628: }
 1629: sub forcedrecalc {
 1630:     my ($uname,$udom,$stype,$usymb)=@_;
 1631:     my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 1632:     my $time=$oldsheets{$key.'.time'};
 1633:     if ($ENV{'form.forcerecalc'}) { return 1; }
 1634:     unless ($time) { return 1; }
 1635:     if ($stype eq 'assesscalc') {
 1636:         my $map=(split(/\_\_\_/,$usymb))[0];
 1637:         if (&checkthis('::assesscalc:',$time) ||
 1638:             &checkthis('::assesscalc:'.$map,$time) ||
 1639:             &checkthis('::assesscalc:'.$usymb,$time) ||
 1640:             &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
 1641:             &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
 1642:             &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
 1643:             return 1;
 1644:         } 
 1645:     } else {
 1646:         if (&checkthis('::studentcalc:',$time) || 
 1647:             &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
 1648: 	    return 1;
 1649:         }
 1650:     }
 1651:     return 0; 
 1652: }
 1653: 
 1654: # ============================================================== Export handler
 1655: #
 1656: # Non-interactive call from with program
 1657: #
 1658: 
 1659: sub exportsheet {
 1660:  my ($uname,$udom,$stype,$usymb,$fn)=@_;
 1661:  my @exportarr=();
 1662: #
 1663: # Check if cached
 1664: #
 1665: 
 1666:  my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 1667:  my $found='';
 1668: 
 1669:  if ($oldsheets{$key}) {
 1670:      map {
 1671:          my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 1672:          if ($name eq $fn) {
 1673: 	     $found=$value;
 1674:          }
 1675:      } split(/\_\_\_\&\_\_\_/,$oldsheets{$key});
 1676:  }
 1677: 
 1678:  unless ($found) {
 1679:      &cachedssheets($uname,$udom,&Apache::lonnet::homeserver($uname,$udom));
 1680:      if ($oldsheets{$key}) {
 1681:         map {
 1682:             my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 1683:             if ($name eq $fn) {
 1684: 	        $found=$value;
 1685:             }
 1686:         } split(/\_\_\_\&\_\_\_/,$oldsheets{$key});
 1687:      }
 1688:  }
 1689: #
 1690: # Check if still valid
 1691: #
 1692:  if ($found) {
 1693:      if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
 1694: 	 $found='';
 1695:      }
 1696:  }
 1697:  
 1698:  if ($found) {
 1699: #
 1700: # Return what was cached
 1701: #
 1702:      @exportarr=split(/\_\_\_\;\_\_\_/,$found);
 1703: 
 1704:  } else {
 1705: #
 1706: # Not cached
 1707: #        
 1708: 
 1709:     my $thissheet=&makenewsheet($uname,$udom,$stype,$usymb);
 1710:     &readsheet($thissheet,$fn);
 1711:     &updatesheet($thissheet);
 1712:     &loadrows($thissheet);
 1713:     &calcsheet($thissheet); 
 1714:     @exportarr=&exportdata($thissheet);
 1715: #
 1716: # Store now
 1717: #
 1718:     my $cid=$ENV{'request.course.id'}; 
 1719:     my $current='';
 1720:     if ($stype eq 'studentcalc') {
 1721:        $current=&Apache::lonnet::reply('get:'.
 1722:                                      $ENV{'course.'.$cid.'.domain'}.':'.
 1723:                                      $ENV{'course.'.$cid.'.num'}.
 1724: 				     ':nohist_calculatedsheets:'.
 1725:                                      &Apache::lonnet::escape($key),
 1726:                                      $ENV{'course.'.$cid.'.home'});
 1727:     } else {
 1728:        $current=&Apache::lonnet::reply('get:'.
 1729:                                      &getudom($thissheet).':'.
 1730:                                      &getuname($thissheet).
 1731: 				     ':nohist_calculatedsheets_'.
 1732:                                      $ENV{'request.course.id'}.':'.
 1733:                                      &Apache::lonnet::escape($key),
 1734:                                      &getuhome($thissheet));
 1735: 
 1736:     }
 1737:     my %currentlystored=();
 1738:     unless ($current=~/^error\:/) {
 1739:        map {
 1740:            my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
 1741:            $currentlystored{$name}=$value;
 1742:        } split(/\_\_\_\&\_\_\_/,&Apache::lonnet::unescape($current));
 1743:     }
 1744:     $currentlystored{$fn}=join('___;___',@exportarr);
 1745: 
 1746:     my $newstore='';
 1747:     map {
 1748:         if ($newstore) { $newstore.='___&___'; }
 1749:         $newstore.=$_.'___=___'.$currentlystored{$_};
 1750:     } keys %currentlystored;
 1751:     my $now=time;
 1752:     if ($stype eq 'studentcalc') {
 1753:        &Apache::lonnet::reply('put:'.
 1754:                          $ENV{'course.'.$cid.'.domain'}.':'.
 1755:                          $ENV{'course.'.$cid.'.num'}.
 1756: 			 ':nohist_calculatedsheets:'.
 1757:                          &Apache::lonnet::escape($key).'='.
 1758: 			 &Apache::lonnet::escape($newstore).'&'.
 1759:                          &Apache::lonnet::escape($key).'.time='.$now,
 1760:                          $ENV{'course.'.$cid.'.home'});
 1761:    } else {
 1762:        &Apache::lonnet::reply('put:'.
 1763:                          &getudom($thissheet).':'.
 1764:                          &getuname($thissheet).
 1765: 			 ':nohist_calculatedsheets_'.
 1766:                          $ENV{'request.course.id'}.':'.
 1767:                          &Apache::lonnet::escape($key).'='.
 1768: 			 &Apache::lonnet::escape($newstore).'&'.
 1769:                          &Apache::lonnet::escape($key).'.time='.$now,
 1770:                          &getuhome($thissheet));
 1771:    }
 1772:  }
 1773:  return @exportarr;
 1774: }
 1775: # ============================================================ Expiration Dates
 1776: #
 1777: # Load previously cached student spreadsheets for this course
 1778: #
 1779: 
 1780: sub expirationdates {
 1781:     undef %expiredates;
 1782:     my $cid=$ENV{'request.course.id'};
 1783:     my $reply=&Apache::lonnet::reply('dump:'.
 1784: 				     $ENV{'course.'.$cid.'.domain'}.':'.
 1785:                                      $ENV{'course.'.$cid.'.num'}.
 1786: 				     ':nohist_expirationdates',
 1787:                                      $ENV{'course.'.$cid.'.home'});
 1788:     unless ($reply=~/^error\:/) {
 1789: 	map {
 1790:             my ($name,$value)=split(/\=/,$_);
 1791:             $expiredates{&Apache::lonnet::unescape($name)}
 1792:                         =&Apache::lonnet::unescape($value);
 1793:         } split(/\&/,$reply);
 1794:     }
 1795: }
 1796: 
 1797: # ===================================================== Calculated sheets cache
 1798: #
 1799: # Load previously cached student spreadsheets for this course
 1800: #
 1801: 
 1802: sub cachedcsheets {
 1803:     my $cid=$ENV{'request.course.id'};
 1804:     my $reply=&Apache::lonnet::reply('dump:'.
 1805: 				     $ENV{'course.'.$cid.'.domain'}.':'.
 1806:                                      $ENV{'course.'.$cid.'.num'}.
 1807: 				     ':nohist_calculatedsheets',
 1808:                                      $ENV{'course.'.$cid.'.home'});
 1809:     unless ($reply=~/^error\:/) {
 1810: 	map {
 1811:             my ($name,$value)=split(/\=/,$_);
 1812:             $oldsheets{&Apache::lonnet::unescape($name)}
 1813:                       =&Apache::lonnet::unescape($value);
 1814:         } split(/\&/,$reply);
 1815:     }
 1816: }
 1817: 
 1818: # ===================================================== Calculated sheets cache
 1819: #
 1820: # Load previously cached assessment spreadsheets for this student
 1821: #
 1822: 
 1823: sub cachedssheets {
 1824:   my ($sname,$sdom,$shome)=@_;
 1825:   unless (($loadedcaches{$sname.'_'.$sdom}) || ($shome eq 'no_host')) {
 1826:     my $cid=$ENV{'request.course.id'};
 1827:     my $reply=&Apache::lonnet::reply('dump:'.$sdom.':'.$sname.
 1828: 			             ':nohist_calculatedsheets_'.
 1829:                                       $ENV{'request.course.id'},
 1830:                                      $shome);
 1831:     unless ($reply=~/^error\:/) {
 1832: 	map {
 1833:             my ($name,$value)=split(/\=/,$_);
 1834:             $oldsheets{&Apache::lonnet::unescape($name)}
 1835:                       =&Apache::lonnet::unescape($value);
 1836:         } split(/\&/,$reply);
 1837:     }
 1838:     $loadedcaches{$sname.'_'.$sdom}=1;
 1839:   }
 1840: }
 1841: 
 1842: # ===================================================== Calculated sheets cache
 1843: #
 1844: # Load previously cached assessment spreadsheets for this student
 1845: #
 1846: 
 1847: # ================================================================ Main handler
 1848: #
 1849: # Interactive call to screen
 1850: #
 1851: #
 1852: 
 1853: 
 1854: sub handler {
 1855:     my $r=shift;
 1856: 
 1857:     if ($r->header_only) {
 1858:       $r->content_type('text/html');
 1859:       $r->send_http_header;
 1860:       return OK;
 1861:     }
 1862: 
 1863: # ---------------------------------------------------- Global directory configs
 1864: 
 1865: $includedir=$r->dir_config('lonIncludes');
 1866: $tmpdir=$r->dir_config('lonDaemons').'/tmp/';
 1867: 
 1868: # ----------------------------------------------------- Needs to be in a course
 1869: 
 1870:   if ($ENV{'request.course.fn'}) { 
 1871: 
 1872: # --------------------------- Get query string for limited number of parameters
 1873: 
 1874:     map {
 1875:        my ($name, $value) = split(/=/,$_);
 1876:        $value =~ tr/+/ /;
 1877:        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 1878:        if (($name eq 'uname') || ($name eq 'udom') || 
 1879:            ($name eq 'usymb') || ($name eq 'ufn')) {
 1880:            unless ($ENV{'form.'.$name}) {
 1881:               $ENV{'form.'.$name}=$value;
 1882: 	   }
 1883:        }
 1884:     } (split(/&/,$ENV{'QUERY_STRING'}));
 1885: 
 1886: # -------------------------------------- Interactive loading of specific sheet?
 1887:     if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
 1888: 	$ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
 1889:     }
 1890: # ------------------------------------------- Nothing there? Must be login user
 1891: 
 1892:     my $aname;
 1893:     my $adom;
 1894: 
 1895:     unless ($ENV{'form.uname'}) {
 1896: 	$aname=$ENV{'user.name'};
 1897:         $adom=$ENV{'user.domain'};
 1898:     } else {
 1899:         $aname=$ENV{'form.uname'};
 1900:         $adom=$ENV{'form.udom'};
 1901:     }
 1902: 
 1903: # ------------------------------------------------------------------- Open page
 1904: 
 1905:     $r->content_type('text/html');
 1906:     $r->header_out('Cache-control','no-cache');
 1907:     $r->header_out('Pragma','no-cache');
 1908:     $r->send_http_header;
 1909: 
 1910: # --------------------------------------------------------------- Screen output
 1911: 
 1912:     $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
 1913:     $r->print(<<ENDSCRIPT);
 1914: <script language="JavaScript">
 1915: 
 1916:     function celledit(cn,cf) {
 1917:         var cnf=prompt(cn,cf);
 1918: 	if (cnf!=null) {
 1919: 	    document.sheet.unewfield.value=cn;
 1920:             document.sheet.unewformula.value=cnf;
 1921:             document.sheet.submit();
 1922:         }
 1923:     }
 1924: 
 1925:     function changesheet(cn) {
 1926: 	document.sheet.unewfield.value=cn;
 1927:         document.sheet.unewformula.value='changesheet';
 1928:         document.sheet.submit();
 1929:     }
 1930: 
 1931: </script>
 1932: ENDSCRIPT
 1933:     $r->print('</head><body bgcolor="#FFFFFF">'.
 1934:        '<img align=right src=/adm/lonIcons/lonlogos.gif>'.
 1935:        '<h1>LON-CAPA Spreadsheet</h1>'.
 1936:        '<form action="'.$r->uri.'" name=sheet method=post>'.
 1937:        &hiddenfield('uname',$ENV{'form.uname'}).
 1938:        &hiddenfield('udom',$ENV{'form.udom'}).
 1939:        &hiddenfield('usymb',$ENV{'form.usymb'}).
 1940:        &hiddenfield('unewfield','').
 1941:        &hiddenfield('unewformula',''));
 1942: 
 1943: # ---------------------- Make sure that this gets out, even if user hits "stop"
 1944: 
 1945:     $r->rflush();
 1946: 
 1947: # ---------------------------------------------------------------- Full recalc?
 1948: 
 1949: 
 1950:     if ($ENV{'form.forcerecalc'}) {
 1951: 	$r->print('<h4>Completely Recalculating Sheet ...</h4>');
 1952:         undef %spreadsheets;
 1953:         undef %courserdatas;
 1954:         undef %userrdatas;
 1955:         undef %defaultsheets;
 1956:         undef %updatedata;
 1957:    }
 1958:  
 1959: # ---------------------------------------- Read new sheet or modified worksheet
 1960: 
 1961:     $r->uri=~/\/(\w+)$/;
 1962: 
 1963:     my $asheet=&makenewsheet($aname,$adom,$1,$ENV{'form.usymb'});
 1964: 
 1965: # ------------------------ If a new formula had been entered, go from work copy
 1966: 
 1967:     if ($ENV{'form.unewfield'}) {
 1968:         $r->print('<h2>Modified Workcopy</h2>');
 1969:         $ENV{'form.unewformula'}=~s/\'/\"/g;
 1970:         $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
 1971:                   $ENV{'form.unewformula'}.'<p>');
 1972:         &setfilename($asheet,$ENV{'form.ufn'});
 1973: 	&tmpread($asheet,
 1974:                  $ENV{'form.unewfield'},$ENV{'form.unewformula'});
 1975: 
 1976:      } elsif ($ENV{'form.saveas'}) {
 1977:         &setfilename($asheet,$ENV{'form.ufn'});
 1978: 	&tmpread($asheet);
 1979:     } else {
 1980:         &readsheet($asheet,$ENV{'form.ufn'});
 1981:     }
 1982: 
 1983: # -------------------------------------------------- Print out user information
 1984: 
 1985:     unless (&gettype($asheet) eq 'classcalc') {
 1986:         $r->print('<p><b>User:</b> '.&getuname($asheet).
 1987:                   '<br><b>Domain:</b> '.&getudom($asheet));
 1988:         if (&getcsec($asheet) eq '-1') {
 1989:            $r->print('<h3><font color=red>'.
 1990:                      'Not a student in this course</font></h3>');
 1991:         } else {
 1992:            $r->print('<br><b>Section/Group:</b> '.&getcsec($asheet));
 1993:         }
 1994:     }
 1995: 
 1996: # ---------------------------------------------------------------- Course title
 1997: 
 1998:     $r->print('<h1>'.
 1999:             $ENV{'course.'.$ENV{'request.course.id'}.'.description'}.
 2000:              '</h1><h3>'.localtime().'</h3>');
 2001: 
 2002: # ---------------------------------------------------- See if user can see this
 2003: 
 2004:     if ((&gettype($asheet) eq 'classcalc') || 
 2005:         (&getuname($asheet) ne $ENV{'user.name'}) ||
 2006:         (&getudom($asheet) ne $ENV{'user.domain'})) {
 2007:         unless (&Apache::lonnet::allowed('vgr',&getcid($asheet))) {
 2008: 	    $r->print(
 2009:            '<h1>Access Permission Denied</h1></form></body></html>');
 2010:             return OK;
 2011:         }
 2012:     }
 2013: 
 2014: # ---------------------------------------------------------- Additional options
 2015: 
 2016:     $r->print(
 2017:  '<input type=submit name=forcerecalc value="Completely Recalculate Sheet"><p>'
 2018: 		 );
 2019:     if (&gettype($asheet) eq 'assesscalc') {
 2020:        $r->print ('<p><font size=+2><a href="/adm/studentcalc?uname='.
 2021:                                                &getuname($asheet).
 2022:                                                '&udom='.&getudom($asheet).
 2023:                   '">Level up: Student Sheet</a></font><p>');
 2024:     }
 2025:     
 2026:     if ((&gettype($asheet) eq 'studentcalc') && 
 2027:         (&Apache::lonnet::allowed('vgr',&getcid($asheet)))) {
 2028:        $r->print (
 2029:                    '<p><font size=+2><a href="/adm/classcalc">'.
 2030:                    'Level up: Course Sheet</a></font><p>');
 2031:     }
 2032:     
 2033: 
 2034: # ----------------------------------------------------------------- Save dialog
 2035: 
 2036: 
 2037:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2038:         my $fname=$ENV{'form.ufn'};
 2039:         $fname=~s/\_[^\_]+$//;
 2040:         if ($fname eq 'default') { $fname='course_default'; }
 2041:         $r->print('<input type=submit name=saveas value="Save as ...">'.
 2042:               '<input type=text size=20 name=newfn value="'.$fname.
 2043:               '"> (make default: <input type=checkbox name="makedefufn">)<p>');
 2044:     }
 2045: 
 2046:     $r->print(&hiddenfield('ufn',&getfilename($asheet)));
 2047: 
 2048: # ----------------------------------------------------------------- Load dialog
 2049:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2050: 	$r->print('<p><input type=submit name=load value="Load ...">'.
 2051:                   '<select name="loadthissheet">'.
 2052:                   '<option name="default">Default</option>');
 2053:         map {
 2054: 	    $r->print('<option name="'.$_.'"');
 2055:             if ($ENV{'form.ufn'} eq $_) {
 2056:                $r->print(' selected');
 2057:             }
 2058:             $r->print('>'.$_.'</option>');
 2059:         } &othersheets($asheet,&gettype($asheet));
 2060:         $r->print('</select><p>');
 2061:         if (&gettype($asheet) eq 'studentcalc') {
 2062: 	    &setothersheets($asheet,&othersheets($asheet,'assesscalc'));
 2063:         }
 2064:     }
 2065: 
 2066: # --------------------------------------------------------------- Cached sheets
 2067: 
 2068:     &expirationdates();
 2069: 
 2070:     undef %oldsheets;
 2071:     undef %loadedcaches;
 2072: 
 2073:     if (&gettype($asheet) eq 'classcalc') {
 2074:         $r->print("Loading previously calculated student sheets ...<br>\n");
 2075:         $r->rflush();
 2076:         &cachedcsheets();
 2077:     } elsif (&gettype($asheet) eq 'studentcalc') {
 2078:         $r->print("Loading previously calculated assessment sheets ...<br>\n");
 2079:         $r->rflush();
 2080:         &cachedssheets(&getuname($asheet),&getudom($asheet),
 2081:                        &getuhome($asheet));
 2082:     }
 2083: 
 2084: # ----------------------------------------------------- Update sheet, load rows
 2085: 
 2086:     $r->print("Loaded sheet(s), updating rows ...<br>\n");
 2087:     $r->rflush();
 2088: 
 2089:     &updatesheet($asheet);
 2090: 
 2091:     $r->print("Updated rows, loading row data ...<br>\n");
 2092:     $r->rflush();
 2093: 
 2094:     &loadrows($asheet,$r);
 2095: 
 2096:     $r->print("Loaded row data, calculating sheet ...<br>\n");
 2097:     $r->rflush();
 2098: 
 2099:     my $calcoutput=&calcsheet($asheet);
 2100:     $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
 2101: 
 2102: # ---------------------------------------------------- See if something to save
 2103: 
 2104:     if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
 2105:         my $fname='';
 2106: 	if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
 2107:             $fname=~s/\W/\_/g;
 2108:             if ($fname eq 'default') { $fname='course_default'; }
 2109:             $fname.='_'.&gettype($asheet);
 2110:             &setfilename($asheet,$fname);
 2111:             $ENV{'form.ufn'}=$fname;
 2112: 	    $r->print('<p>Saving spreadsheet: '.
 2113:                          &writesheet($asheet,$ENV{'form.makedefufn'}).'<p>');
 2114: 	}
 2115:     }
 2116: 
 2117: # ------------------------------------------------ Write the modified worksheet
 2118: 
 2119:    $r->print('<b>Current sheet:</b> '.&getfilename($asheet).'<p>');
 2120: 
 2121:    &tmpwrite($asheet);
 2122: 
 2123:     if (&gettype($asheet) eq 'studentcalc') {
 2124: 	$r->print('<br>Show rows with empty A column: ');
 2125:     } else {
 2126:         $r->print('<br>Show empty rows: ');
 2127:     } 
 2128:     $r->print('<input type=checkbox name=showall onClick="submit()"');
 2129:     if ($ENV{'form.showall'}) { $r->print(' checked'); }
 2130:     $r->print('>');
 2131: 
 2132: # ------------------------------------------------------------- Print out sheet
 2133: 
 2134:     &outsheet($r,$asheet);
 2135:     $r->print('</form></body></html>');
 2136: 
 2137: # ------------------------------------------------------------------------ Done
 2138:   } else {
 2139: # ----------------------------- Not in a course, or not allowed to modify parms
 2140:       $ENV{'user.error.msg'}=
 2141:         $r->uri.":opa:0:0:Cannot modify spreadsheet";
 2142:       return HTTP_NOT_ACCEPTABLE; 
 2143:   }
 2144:     return OK;
 2145: 
 2146: }
 2147: 
 2148: 1;
 2149: __END__

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