File:  [LON-CAPA] / loncom / interface / Attic / lonspreadsheet.pm
Revision 1.58: download - view: text, annotated - select for diffs
Sat Jul 21 23:58:31 2001 UTC (22 years, 10 months ago) by www
Branches: MAIN
CVS tags: HEAD
Remove debug output

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

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