File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.69: download - view: text, annotated - select for diffs
Wed Oct 17 18:35:17 2001 UTC (22 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
Also restore stores correctly for part.responseid

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

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