File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.66: download - view: text, annotated - select for diffs
Tue Oct 16 09:53:50 2001 UTC (22 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Spreadsheet needs \w-only names for internal calculations

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

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