File:
[LON-CAPA] /
loncom /
interface /
Attic /
lonspreadsheet.pm
Revision
1.104:
download - view:
text,
annotated -
select for diffs
Fri Aug 30 19:47:47 2002 UTC (21 years, 11 months ago) by
matthew
Branches:
MAIN
CVS tags:
HEAD
Many changes that should have been checked in one at a time....
Replaced %v with %sheet_values.
Many indentation and whitespace changes.
Some changes in logic.
No new features have been added, but tests have been done to exercise the
code. Nevertheless, this should *not* be included in 0.5a.
1: #
2: # $Id: lonspreadsheet.pm,v 1.104 2002/08/30 19:47:47 matthew Exp $
3: #
4: # Copyright Michigan State University Board of Trustees
5: #
6: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
7: #
8: # LON-CAPA is free software; you can redistribute it and/or modify
9: # it under the terms of the GNU General Public License as published by
10: # the Free Software Foundation; either version 2 of the License, or
11: # (at your option) any later version.
12: #
13: # LON-CAPA is distributed in the hope that it will be useful,
14: # but WITHOUT ANY WARRANTY; without even the implied warranty of
15: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16: # GNU General Public License for more details.
17: #
18: # You should have received a copy of the GNU General Public License
19: # along with LON-CAPA; if not, write to the Free Software
20: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21: #
22: # /home/httpd/html/adm/gpl.txt
23: #
24: # http://www.lon-capa.org/
25: #
26: # The LearningOnline Network with CAPA
27: # Spreadsheet/Grades Display Handler
28: #
29: # 11/11,11/15,11/27,12/04,12/05,12/06,12/07,
30: # 12/08,12/09,12/11,12/12,12/15,12/16,12/18,12/19,12/30,
31: # 01/01/01,02/01,03/01,19/01,20/01,22/01,
32: # 03/05,03/08,03/10,03/12,03/13,03/15,03/17,
33: # 03/19,03/20,03/21,03/27,04/05,04/09,
34: # 07/09,07/14,07/21,09/01,09/10,9/11,9/12,9/13,9/14,9/17,
35: # 10/16,10/17,10/20,11/05,11/28,12/27 Gerd Kortemeyer
36: # 01/14/02 Matthew
37: # 02/04/02 Matthew
38:
39: # POD required stuff:
40:
41: =head1 NAME
42:
43: lonspreadsheet
44:
45: =head1 SYNOPSIS
46:
47: Spreadsheet interface to internal LON-CAPA data
48:
49: =head1 DESCRIPTION
50:
51: Lonspreadsheet provides course coordinators the ability to manage their
52: students grades online. The students are able to view their own grades, but
53: not the grades of their peers. The spreadsheet is highly customizable,
54: offering the ability to use Perl code to manipulate data, as well as many
55: built-in functions.
56:
57:
58: =head2 Functions available to user of lonspreadsheet
59:
60: =over 4
61:
62: =cut
63:
64: package Apache::lonspreadsheet;
65:
66: use strict;
67: use Safe;
68: use Safe::Hole;
69: use Opcode;
70: use Apache::lonnet;
71: use Apache::Constants qw(:common :http);
72: use GDBM_File;
73: use HTML::TokeParser;
74: use Apache::lonhtmlcommon;
75: #
76: # Caches for previously calculated spreadsheets
77: #
78:
79: my %oldsheets;
80: my %loadedcaches;
81: my %expiredates;
82:
83: #
84: # Cache for stores of an individual user
85: #
86:
87: my $cachedassess;
88: my %cachedstores;
89:
90: #
91: # These cache hashes need to be independent of user, resource and course
92: # (user and course can/should be in the keys)
93: #
94:
95: my %spreadsheets;
96: my %courserdatas;
97: my %userrdatas;
98: my %defaultsheets;
99: my %updatedata;
100:
101: #
102: # These global hashes are dependent on user, course and resource,
103: # and need to be initialized every time when a sheet is calculated
104: #
105: my %courseopt;
106: my %useropt;
107: my %parmhash;
108:
109: #
110: # Some hashes for stats on timing and performance
111: #
112:
113: my %starttimes;
114: my %usedtimes;
115: my %numbertimes;
116:
117: # Stuff that only the screen handler can know
118:
119: my $includedir;
120: my $tmpdir;
121:
122: # =============================================================================
123: # ===================================== Implements an instance of a spreadsheet
124:
125: sub initsheet {
126: my $safeeval = new Safe(shift);
127: my $safehole = new Safe::Hole;
128: $safeeval->permit("entereval");
129: $safeeval->permit(":base_math");
130: $safeeval->permit("sort");
131: $safeeval->deny(":base_io");
132: $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
133: $safeeval->share('$@');
134: my $code=<<'ENDDEFS';
135: # ---------------------------------------------------- Inside of the safe space
136:
137: #
138: # f: formulas
139: # t: intermediate format (variable references expanded)
140: # v: output values
141: # c: preloaded constants (A-column)
142: # rl: row label
143: # os: other spreadsheets (for student spreadsheet only)
144:
145: undef %sheet_values;
146: undef %t;
147: undef %f;
148: undef %c;
149: undef %rowlabel;
150: undef @os;
151:
152: $maxrow = 0;
153: $sheettype = '';
154:
155: # filename/reference of the sheet
156: $filename = '';
157:
158: # user data
159: $uname = '';
160: $uhome = '';
161: $udom = '';
162:
163: # course data
164:
165: $csec = '';
166: $chome= '';
167: $cnum = '';
168: $cdom = '';
169: $cid = '';
170: $cfn = '';
171:
172: # symb
173:
174: $usymb = '';
175:
176: # error messages
177: $errormsg = '';
178:
179: sub mask {
180: my ($lower,$upper)=@_;
181:
182: $lower=~/([A-Za-z]|\*)(\d+|\*)/;
183: my $la=$1;
184: my $ld=$2;
185:
186: $upper=~/([A-Za-z]|\*)(\d+|\*)/;
187: my $ua=$1;
188: my $ud=$2;
189: my $alpha='';
190: my $num='';
191:
192: if (($la eq '*') || ($ua eq '*')) {
193: $alpha='[A-Za-z]';
194: } else {
195: if (($la=~/[A-Z]/) && ($ua=~/[A-Z]/) ||
196: ($la=~/[a-z]/) && ($ua=~/[a-z]/)) {
197: $alpha='['.$la.'-'.$ua.']';
198: } else {
199: $alpha='['.$la.'-Za-'.$ua.']';
200: }
201: }
202:
203: if (($ld eq '*') || ($ud eq '*')) {
204: $num='\d+';
205: } else {
206: if (length($ld)!=length($ud)) {
207: $num.='(';
208: foreach ($ld=~m/\d/g) {
209: $num.='['.$_.'-9]';
210: }
211: if (length($ud)-length($ld)>1) {
212: $num.='|\d{'.(length($ld)+1).','.(length($ud)-1).'}';
213: }
214: $num.='|';
215: foreach ($ud=~m/\d/g) {
216: $num.='[0-'.$_.']';
217: }
218: $num.=')';
219: } else {
220: my @lda=($ld=~m/\d/g);
221: my @uda=($ud=~m/\d/g);
222: my $i; $j=0; $notdone=1;
223: for ($i=0;($i<=$#lda)&&($notdone);$i++) {
224: if ($lda[$i]==$uda[$i]) {
225: $num.=$lda[$i];
226: $j=$i;
227: } else {
228: $notdone=0;
229: }
230: }
231: if ($j<$#lda-1) {
232: $num.='('.$lda[$j+1];
233: for ($i=$j+2;$i<=$#lda;$i++) {
234: $num.='['.$lda[$i].'-9]';
235: }
236: if ($uda[$j+1]-$lda[$j+1]>1) {
237: $num.='|['.($lda[$j+1]+1).'-'.($uda[$j+1]-1).']\d{'.
238: ($#lda-$j-1).'}';
239: }
240: $num.='|'.$uda[$j+1];
241: for ($i=$j+2;$i<=$#uda;$i++) {
242: $num.='[0-'.$uda[$i].']';
243: }
244: $num.=')';
245: } else {
246: if ($lda[$#lda]!=$uda[$#uda]) {
247: $num.='['.$lda[$#lda].'-'.$uda[$#uda].']';
248: }
249: }
250: }
251: }
252: return '^'.$alpha.$num."\$";
253: }
254:
255: #-------------------------------------------------------
256:
257: =item UWCALC(hashname,modules,units,date)
258:
259: returns the proportion of the module
260: weights not previously completed by the student.
261:
262: =over 4
263:
264: =item hashname
265:
266: name of the hash the module dates have been inserted into
267:
268: =item modules
269:
270: reference to a cell which contains a comma deliminated list of modules
271: covered by the assignment.
272:
273: =item units
274:
275: reference to a cell which contains a comma deliminated list of module
276: weights with respect to the assignment
277:
278: =item date
279:
280: reference to a cell which contains the date the assignment was completed.
281:
282: =back
283:
284: =cut
285:
286: #-------------------------------------------------------
287: sub UWCALC {
288: my ($hashname,$modules,$units,$date) = @_;
289: my @Modules = split(/,/,$modules);
290: my @Units = split(/,/,$units);
291: my $total_weight;
292: foreach (@Units) {
293: $total_weight += $_;
294: }
295: my $usum=0;
296: for (my $i=0; $i<=$#Modules; $i++) {
297: if (&HASH($hashname,$Modules[$i]) eq $date) {
298: $usum += $Units[$i];
299: }
300: }
301: return $usum/$total_weight;
302: }
303:
304: #-------------------------------------------------------
305:
306: =item CDLSUM(list)
307:
308: returns the sum of the elements in a cell which contains
309: a Comma Deliminate List of numerical values.
310: 'list' is a reference to a cell which contains a comma deliminated list.
311:
312: =cut
313:
314: #-------------------------------------------------------
315: sub CDLSUM {
316: my ($list)=@_;
317: my $sum;
318: foreach (split/,/,$list) {
319: $sum += $_;
320: }
321: return $sum;
322: }
323:
324: #-------------------------------------------------------
325:
326: =item CDLITEM(list,index)
327:
328: returns the item at 'index' in a Comma Deliminated List.
329:
330: =over 4
331:
332: =item list
333:
334: reference to a cell which contains a comma deliminated list.
335:
336: =item index
337:
338: the Perl index of the item requested (first element in list has
339: an index of 0)
340:
341: =back
342:
343: =cut
344:
345: #-------------------------------------------------------
346: sub CDLITEM {
347: my ($list,$index)=@_;
348: my @Temp = split/,/,$list;
349: return $Temp[$index];
350: }
351:
352: #-------------------------------------------------------
353:
354: =item CDLHASH(name,key,value)
355:
356: loads a comma deliminated list of keys into
357: the hash 'name', all with a value of 'value'.
358:
359: =over 4
360:
361: =item name
362:
363: name of the hash.
364:
365: =item key
366:
367: (a pointer to) a comma deliminated list of keys.
368:
369: =item value
370:
371: a single value to be entered for each key.
372:
373: =back
374:
375: =cut
376:
377: #-------------------------------------------------------
378: sub CDLHASH {
379: my ($name,$key,$value)=@_;
380: my @Keys;
381: my @Values;
382: # Check to see if we have multiple $key values
383: if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
384: my $keymask = &mask($key);
385: # Assume the keys are addresses
386: my @Temp = grep /$keymask/,keys(%sheet_values);
387: @Keys = $sheet_values{@Temp};
388: } else {
389: $Keys[0]= $key;
390: }
391: my @Temp;
392: foreach $key (@Keys) {
393: @Temp = (@Temp, split/,/,$key);
394: }
395: @Keys = @Temp;
396: if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
397: my $valmask = &mask($value);
398: my @Temp = grep /$valmask/,keys(%sheet_values);
399: @Values =$sheet_values{@Temp};
400: } else {
401: $Values[0]= $value;
402: }
403: $value = $Values[0];
404: # Add values to hash
405: for (my $i = 0; $i<=$#Keys; $i++) {
406: my $key = $Keys[$i];
407: if (! exists ($hashes{$name}->{$key})) {
408: $hashes{$name}->{$key}->[0]=$value;
409: } else {
410: my @Temp = sort(@{$hashes{$name}->{$key}},$value);
411: $hashes{$name}->{$key} = \@Temp;
412: }
413: }
414: return "hash '$name' updated";
415: }
416:
417: #-------------------------------------------------------
418:
419: =item GETHASH(name,key,index)
420:
421: returns the element in hash 'name'
422: reference by the key 'key', at index 'index' in the values list.
423:
424: =cut
425:
426: #-------------------------------------------------------
427: sub GETHASH {
428: my ($name,$key,$index)=@_;
429: if (! defined($index)) {
430: $index = 0;
431: }
432: if ($key =~ /^[A-z]\d+$/) {
433: $key = $sheet_values{$key};
434: }
435: return $hashes{$name}->{$key}->[$index];
436: }
437:
438: #-------------------------------------------------------
439:
440: =item CLEARHASH(name)
441:
442: clears all the values from the hash 'name'
443:
444: =item CLEARHASH(name,key)
445:
446: clears all the values from the hash 'name' associated with the given key.
447:
448: =cut
449:
450: #-------------------------------------------------------
451: sub CLEARHASH {
452: my ($name,$key)=@_;
453: if (defined($key)) {
454: if (exists($hashes{$name}->{$key})) {
455: $hashes{$name}->{$key}=undef;
456: return "hash '$name' key '$key' cleared";
457: }
458: } else {
459: if (exists($hashes{$name})) {
460: $hashes{$name}=undef;
461: return "hash '$name' cleared";
462: }
463: }
464: return "Error in clearing hash";
465: }
466:
467: #-------------------------------------------------------
468:
469: =item HASH(name,key,value)
470:
471: loads values into an internal hash. If a key
472: already has a value associated with it, the values are sorted numerically.
473:
474: =item HASH(name,key)
475:
476: returns the 0th value in the hash 'name' associated with 'key'.
477:
478: =cut
479:
480: #-------------------------------------------------------
481: sub HASH {
482: my ($name,$key,$value)=@_;
483: my @Keys;
484: undef @Keys;
485: my @Values;
486: # Check to see if we have multiple $key values
487: if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
488: my $keymask = &mask($key);
489: # Assume the keys are addresses
490: my @Temp = grep /$keymask/,keys(%sheet_values);
491: @Keys = $sheet_values{@Temp};
492: } else {
493: $Keys[0]= $key;
494: }
495: # If $value is empty, return the first value associated
496: # with the first key.
497: if (! $value) {
498: return $hashes{$name}->{$Keys[0]}->[0];
499: }
500: # Check to see if we have multiple $value(s)
501: if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
502: my $valmask = &mask($value);
503: my @Temp = grep /$valmask/,keys(%sheet_values);
504: @Values =$sheet_values{@Temp};
505: } else {
506: $Values[0]= $value;
507: }
508: # Add values to hash
509: for (my $i = 0; $i<=$#Keys; $i++) {
510: my $key = $Keys[$i];
511: my $value = ($i<=$#Values ? $Values[$i] : $Values[0]);
512: if (! exists ($hashes{$name}->{$key})) {
513: $hashes{$name}->{$key}->[0]=$value;
514: } else {
515: my @Temp = sort(@{$hashes{$name}->{$key}},$value);
516: $hashes{$name}->{$key} = \@Temp;
517: }
518: }
519: return $Values[-1];
520: }
521:
522: #-------------------------------------------------------
523:
524: =item NUM(range)
525:
526: returns the number of items in the range.
527:
528: =cut
529:
530: #-------------------------------------------------------
531: sub NUM {
532: my $mask=mask(@_);
533: my $num= $#{@{grep(/$mask/,keys(%sheet_values))}}+1;
534: return $num;
535: }
536:
537: sub BIN {
538: my ($low,$high,$lower,$upper)=@_;
539: my $mask=mask($lower,$upper);
540: my $num=0;
541: foreach (grep /$mask/,keys(%sheet_values)) {
542: if (($sheet_values{$_}>=$low) && ($sheet_values{$_}<=$high)) {
543: $num++;
544: }
545: }
546: return $num;
547: }
548:
549:
550: #-------------------------------------------------------
551:
552: =item SUM(range)
553:
554: returns the sum of items in the range.
555:
556: =cut
557:
558: #-------------------------------------------------------
559: sub SUM {
560: my $mask=mask(@_);
561: my $sum=0;
562: foreach (grep /$mask/,keys(%sheet_values)) {
563: $sum+=$sheet_values{$_};
564: }
565: return $sum;
566: }
567:
568: #-------------------------------------------------------
569:
570: =item MEAN(range)
571:
572: compute the average of the items in the range.
573:
574: =cut
575:
576: #-------------------------------------------------------
577: sub MEAN {
578: my $mask=mask(@_);
579: my $sum=0; my $num=0;
580: foreach (grep /$mask/,keys(%sheet_values)) {
581: $sum+=$sheet_values{$_};
582: $num++;
583: }
584: if ($num) {
585: return $sum/$num;
586: } else {
587: return undef;
588: }
589: }
590:
591: #-------------------------------------------------------
592:
593: =item STDDEV(range)
594:
595: compute the standard deviation of the items in the range.
596:
597: =cut
598:
599: #-------------------------------------------------------
600: sub STDDEV {
601: my $mask=mask(@_);
602: my $sum=0; my $num=0;
603: foreach (grep /$mask/,keys(%sheet_values)) {
604: $sum+=$sheet_values{$_};
605: $num++;
606: }
607: unless ($num>1) { return undef; }
608: my $mean=$sum/$num;
609: $sum=0;
610: foreach (grep /$mask/,keys(%sheet_values)) {
611: $sum+=($sheet_values{$_}-$mean)**2;
612: }
613: return sqrt($sum/($num-1));
614: }
615:
616: #-------------------------------------------------------
617:
618: =item PROD(range)
619:
620: compute the product of the items in the range.
621:
622: =cut
623:
624: #-------------------------------------------------------
625: sub PROD {
626: my $mask=mask(@_);
627: my $prod=1;
628: foreach (grep /$mask/,keys(%sheet_values)) {
629: $prod*=$sheet_values{$_};
630: }
631: return $prod;
632: }
633:
634: #-------------------------------------------------------
635:
636: =item MAX(range)
637:
638: compute the maximum of the items in the range.
639:
640: =cut
641:
642: #-------------------------------------------------------
643: sub MAX {
644: my $mask=mask(@_);
645: my $max='-';
646: foreach (grep /$mask/,keys(%sheet_values)) {
647: unless ($max) { $max=$sheet_values{$_}; }
648: if (($sheet_values{$_}>$max) || ($max eq '-')) { $max=$sheet_values{$_}; }
649: }
650: return $max;
651: }
652:
653: #-------------------------------------------------------
654:
655: =item MIN(range)
656:
657: compute the minimum of the items in the range.
658:
659: =cut
660:
661: #-------------------------------------------------------
662: sub MIN {
663: my $mask=mask(@_);
664: my $min='-';
665: foreach (grep /$mask/,keys(%sheet_values)) {
666: unless ($max) { $max=$sheet_values{$_}; }
667: if (($sheet_values{$_}<$min) || ($min eq '-')) {
668: $min=$sheet_values{$_};
669: }
670: }
671: return $min;
672: }
673:
674: #-------------------------------------------------------
675:
676: =item SUMMAX(num,lower,upper)
677:
678: compute the sum of the largest 'num' items in the range from
679: 'lower' to 'upper'
680:
681: =cut
682:
683: #-------------------------------------------------------
684: sub SUMMAX {
685: my ($num,$lower,$upper)=@_;
686: my $mask=mask($lower,$upper);
687: my @inside=();
688: foreach (grep /$mask/,keys(%sheet_values)) {
689: push (@inside,$sheet_values{$_});
690: }
691: @inside=sort(@inside);
692: my $sum=0; my $i;
693: for ($i=$#inside;(($i>$#inside-$num) && ($i>=0));$i--) {
694: $sum+=$inside[$i];
695: }
696: return $sum;
697: }
698:
699: #-------------------------------------------------------
700:
701: =item SUMMIN(num,lower,upper)
702:
703: compute the sum of the smallest 'num' items in the range from
704: 'lower' to 'upper'
705:
706: =cut
707:
708: #-------------------------------------------------------
709: sub SUMMIN {
710: my ($num,$lower,$upper)=@_;
711: my $mask=mask($lower,$upper);
712: my @inside=();
713: foreach (grep /$mask/,keys(%sheet_values)) {
714: $inside[$#inside+1]=$sheet_values{$_};
715: }
716: @inside=sort(@inside);
717: my $sum=0; my $i;
718: for ($i=0;(($i<$num) && ($i<=$#inside));$i++) {
719: $sum+=$inside[$i];
720: }
721: return $sum;
722: }
723:
724: #-------------------------------------------------------
725:
726: =item MINPARM(parametername)
727:
728: Returns the minimum value of the parameters matching the parametername.
729: parametername should be a string such as 'duedate'.
730:
731: =cut
732:
733: #-------------------------------------------------------
734: sub MINPARM {
735: my ($expression) = @_;
736: my $min = undef;
737: study($expression);
738: foreach $parameter (keys(%c)) {
739: next if ($parameter !~ /$expression/);
740: if ((! defined($min)) || ($min > $c{$parameter})) {
741: $min = $c{$parameter}
742: }
743: }
744: return $min;
745: }
746:
747: #-------------------------------------------------------
748:
749: =item MAXPARM(parametername)
750:
751: Returns the maximum value of the parameters matching the input parameter name.
752: parametername should be a string such as 'duedate'.
753:
754: =cut
755:
756: #-------------------------------------------------------
757: sub MAXPARM {
758: my ($expression) = @_;
759: my $max = undef;
760: study($expression);
761: foreach $parameter (keys(%c)) {
762: next if ($parameter !~ /$expression/);
763: if ((! defined($min)) || ($max < $c{$parameter})) {
764: $max = $c{$parameter}
765: }
766: }
767: return $max;
768: }
769:
770: #--------------------------------------------------------
771: sub expandnamed {
772: my $expression=shift;
773: if ($expression=~/^\&/) {
774: my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/);
775: my @vars=split(/\W+/,$formula);
776: my %values=();
777: undef %values;
778: foreach ( @vars ) {
779: my $varname=$_;
780: if ($varname=~/\D/) {
781: $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
782: $varname=~s/$var/\(\\w\+\)/g;
783: foreach (keys(%c)) {
784: if ($_=~/$varname/) {
785: $values{$1}=1;
786: }
787: }
788: }
789: }
790: if ($func eq 'EXPANDSUM') {
791: my $result='';
792: foreach (keys(%values)) {
793: my $thissum=$formula;
794: $thissum=~s/$var/$_/g;
795: $result.=$thissum.'+';
796: }
797: $result=~s/\+$//;
798: return $result;
799: } else {
800: return 0;
801: }
802: } else {
803: # it is not a function, so it is a parameter name
804: # We should do the following:
805: # 1. Take the list of parameter names
806: # 2. look through the list for ones that match the parameter we want
807: # 3. If there are no collisions, return the one that matches
808: # 4. If there is a collision, return 'bad parameter name error'
809: my $returnvalue = '';
810: my @matches = ();
811: $#matches = -1;
812: study $expression;
813: foreach $parameter (keys(%c)) {
814: push @matches,$parameter if ($parameter =~ /$expression/);
815: }
816: if ($#matches == 0) {
817: $returnvalue = '$c{\''.$matches[0].'\'}';
818: } elsif ($#matches > 0) {
819: # more than one match. Look for a concise one
820: $returnvalue = "'non-unique parameter name : $expression'";
821: foreach (@matches) {
822: if (/^$expression$/) {
823: $returnvalue = '$c{\''.$_.'\'}';
824: }
825: }
826: } else {
827: $returnvalue = "'bad parameter name : $expression'";
828: }
829: return $returnvalue;
830: }
831: }
832:
833: sub sett {
834: %t=();
835: my $pattern='';
836: if ($sheettype eq 'assesscalc') {
837: $pattern='A';
838: } else {
839: $pattern='[A-Z]';
840: }
841: # Deal with the template row
842: foreach (keys(%f)) {
843: next if ($_!~/template\_(\w)/);
844: my $col=$1;
845: next if ($col=~/^$pattern/);
846: foreach (keys(%f)) {
847: next if ($_!~/A(\d+)/);
848: my $trow=$1;
849: next if (! $trow);
850: # Get the name of this cell
851: my $lb=$col.$trow;
852: # Grab the template declaration
853: $t{$lb}=$f{'template_'.$col};
854: # Replace '#' with the row number
855: $t{$lb}=~s/\#/$trow/g;
856: # Replace '....' with ','
857: $t{$lb}=~s/\.\.+/\,/g;
858: # Replace 'A0' with the value from 'A0'
859: $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
860: # Replace parameters
861: $t{$lb}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
862: }
863: }
864: # Deal with the normal cells
865: foreach (keys(%f)) {
866: if (($f{$_}) && ($_!~/template\_/)) {
867: my $matches=($_=~/^$pattern(\d+)/);
868: if (($matches) && ($1)) {
869: unless ($f{$_}=~/^\!/) {
870: $t{$_}=$c{$_};
871: }
872: } else {
873: $t{$_}=$f{$_};
874: $t{$_}=~s/\.\.+/\,/g;
875: $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
876: $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
877: }
878: }
879: }
880: # For inserted lines, [B-Z] is also valid
881: unless ($sheettype eq 'assesscalc') {
882: foreach (keys(%f)) {
883: if ($_=~/[B-Z](\d+)/) {
884: if ($f{'A'.$1}=~/^[\~\-]/) {
885: $t{$_}=$f{$_};
886: $t{$_}=~s/\.\.+/\,/g;
887: $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
888: $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
889: }
890: }
891: }
892: }
893: # For some reason 'A0' gets special treatment... This seems superfluous
894: # but I imagine it is here for a reason.
895: $t{'A0'}=$f{'A0'};
896: $t{'A0'}=~s/\.\.+/\,/g;
897: $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
898: $t{'A0'}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
899: }
900:
901: sub calc {
902: undef %sheet_values;
903: &sett();
904: my $notfinished=1;
905: my $lastcalc='';
906: my $depth=0;
907: while ($notfinished) {
908: $notfinished=0;
909: foreach (keys(%t)) {
910: my $old=$sheet_values{$_};
911: $sheet_values{$_}=eval $t{$_};
912: if ($@) {
913: undef %sheet_values;
914: return $_.': '.$@;
915: }
916: if ($sheet_values{$_} ne $old) { $notfinished=1; $lastcalc=$_; }
917: }
918: $depth++;
919: if ($depth>100) {
920: undef %sheet_values;
921: return $lastcalc.': Maximum calculation depth exceeded';
922: }
923: }
924: return '';
925: }
926:
927: sub templaterow {
928: my @cols=();
929: $cols[0]='<b><font size=+1>Template</font></b>';
930: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
931: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
932: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
933: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
934: my $fm=$f{'template_'.$_};
935: $fm=~s/[\'\"]/\&\#34;/g;
936: push(@cols,"'template_$_','$fm'".'___eq___'.$fm);
937: }
938: return @cols;
939: }
940:
941: #
942: # This is actually used for the student spreadsheet, not the assessment sheet
943: # Do not be fooled by the name!
944: #
945: sub outrowassess {
946: # $n is the current row number
947: my $n=shift;
948: my @cols=();
949: if ($n) {
950: my ($usy,$ufn)=split(/__&&&\__/,$f{'A'.$n});
951: if ($rowlabel{$usy}) {
952: $cols[0]=$rowlabel{$usy}.'<br>'.
953: '<select name="sel_'.$n.'" onChange="changesheet('.$n.')">'.
954: '<option name="default">Default</option>';
955: } else {
956: $cols[0]='';
957: }
958: foreach (@os) {
959: $cols[0].='<option name="'.$_.'"';
960: if ($ufn eq $_) {
961: $cols[0].=' selected';
962: }
963: $cols[0].='>'.$_.'</option>';
964: }
965: $cols[0].='</select>';
966: } else {
967: $cols[0]='<b><font size=+1>Export</font></b>';
968: }
969: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
970: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
971: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
972: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
973: my $fm=$f{$_.$n};
974: $fm=~s/[\'\"]/\&\#34;/g;
975: push(@cols,"'$_$n','$fm'".'___eq___'.$sheet_values{$_.$n});
976: }
977: return @cols;
978: }
979:
980: sub outrow {
981: my $n=shift;
982: my @cols=();
983: if ($n) {
984: $cols[0]=$rowlabel{$f{'A'.$n}};
985: } else {
986: $cols[0]='<b><font size=+1>Export</font></b>';
987: }
988: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
989: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
990: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
991: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
992: my $fm=$f{$_.$n};
993: $fm=~s/[\'\"]/\&\#34;/g;
994: push(@cols,"'$_$n','$fm'".'___eq___'.$sheet_values{$_.$n});
995: }
996: return @cols;
997: }
998:
999: sub exportrowa {
1000: my @exportarray=();
1001: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1002: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1003: push(@exportarray,$sheet_values{$_.'0'});
1004: }
1005: return @exportarray;
1006: }
1007:
1008: # ------------------------------------------- End of "Inside of the safe space"
1009: ENDDEFS
1010: $safeeval->reval($code);
1011: return $safeeval;
1012: }
1013:
1014: # ------------------------------------------------ Add or change formula values
1015:
1016: sub setformulas {
1017: my ($safeeval,%f)=@_;
1018: %{$safeeval->varglob('f')}=%f;
1019: }
1020:
1021: # ------------------------------------------------ Add or change formula values
1022:
1023: sub setconstants {
1024: my ($safeeval,%c)=@_;
1025: %{$safeeval->varglob('c')}=%c;
1026: }
1027:
1028: # --------------------------------------------- Set names of other spreadsheets
1029:
1030: sub setothersheets {
1031: my ($safeeval,@os)=@_;
1032: @{$safeeval->varglob('os')}=@os;
1033: }
1034:
1035: # ------------------------------------------------ Add or change formula values
1036:
1037: sub setrowlabels {
1038: my ($safeeval,%rowlabel)=@_;
1039: %{$safeeval->varglob('rowlabel')}=%rowlabel;
1040: }
1041:
1042: # ------------------------------------------------------- Calculate spreadsheet
1043:
1044: sub calcsheet {
1045: my $safeeval=shift;
1046: return $safeeval->reval('&calc();');
1047: }
1048:
1049: # ------------------------------------------------------------------ Get values
1050:
1051: sub getvalues {
1052: my $safeeval=shift;
1053: return $safeeval->reval('%sheet_values');
1054: }
1055:
1056: # ---------------------------------------------------------------- Get formulas
1057:
1058: sub getformulas {
1059: my $safeeval=shift;
1060: return %{$safeeval->varglob('f')};
1061: }
1062:
1063: # ----------------------------------------------------- Get value of $f{'A'.$n}
1064:
1065: sub getfa {
1066: my ($safeeval,$n)=@_;
1067: return $safeeval->reval('$f{"A'.$n.'"}');
1068: }
1069:
1070: # -------------------------------------------------------------------- Get type
1071:
1072: sub gettype {
1073: my $safeeval=shift;
1074: return $safeeval->reval('$sheettype');
1075: }
1076:
1077: # ------------------------------------------------------------------ Set maxrow
1078:
1079: sub setmaxrow {
1080: my ($safeeval,$row)=@_;
1081: $safeeval->reval('$maxrow='.$row.';');
1082: }
1083:
1084: # ------------------------------------------------------------------ Get maxrow
1085:
1086: sub getmaxrow {
1087: my $safeeval=shift;
1088: return $safeeval->reval('$maxrow');
1089: }
1090:
1091: # ---------------------------------------------------------------- Set filename
1092:
1093: sub setfilename {
1094: my ($safeeval,$fn)=@_;
1095: $safeeval->reval('$filename="'.$fn.'";');
1096: }
1097:
1098: # ---------------------------------------------------------------- Get filename
1099:
1100: sub getfilename {
1101: my $safeeval=shift;
1102: return $safeeval->reval('$filename');
1103: }
1104:
1105: # --------------------------------------------------------------- Get course ID
1106:
1107: sub getcid {
1108: my $safeeval=shift;
1109: return $safeeval->reval('$cid');
1110: }
1111:
1112: # --------------------------------------------------------- Get course filename
1113:
1114: sub getcfn {
1115: my $safeeval=shift;
1116: return $safeeval->reval('$cfn');
1117: }
1118:
1119: # ----------------------------------------------------------- Get course number
1120:
1121: sub getcnum {
1122: my $safeeval=shift;
1123: return $safeeval->reval('$cnum');
1124: }
1125:
1126: # ------------------------------------------------------------- Get course home
1127:
1128: sub getchome {
1129: my $safeeval=shift;
1130: return $safeeval->reval('$chome');
1131: }
1132:
1133: # ----------------------------------------------------------- Get course domain
1134:
1135: sub getcdom {
1136: my $safeeval=shift;
1137: return $safeeval->reval('$cdom');
1138: }
1139:
1140: # ---------------------------------------------------------- Get course section
1141:
1142: sub getcsec {
1143: my $safeeval=shift;
1144: return $safeeval->reval('$csec');
1145: }
1146:
1147: # --------------------------------------------------------------- Get user name
1148:
1149: sub getuname {
1150: my $safeeval=shift;
1151: return $safeeval->reval('$uname');
1152: }
1153:
1154: # ------------------------------------------------------------- Get user domain
1155:
1156: sub getudom {
1157: my $safeeval=shift;
1158: return $safeeval->reval('$udom');
1159: }
1160:
1161: # --------------------------------------------------------------- Get user home
1162:
1163: sub getuhome {
1164: my $safeeval=shift;
1165: return $safeeval->reval('$uhome');
1166: }
1167:
1168: # -------------------------------------------------------------------- Get symb
1169:
1170: sub getusymb {
1171: my $safeeval=shift;
1172: return $safeeval->reval('$usymb');
1173: }
1174:
1175: # ------------------------------------------------------------- Export of A-row
1176:
1177: sub exportdata {
1178: my $safeeval=shift;
1179: return $safeeval->reval('&exportrowa()');
1180: }
1181:
1182:
1183: # ========================================================== End of Spreadsheet
1184: # =============================================================================
1185:
1186: #
1187: # Procedures for screen output
1188: #
1189: # --------------------------------------------- Produce output row n from sheet
1190:
1191: sub rown {
1192: my ($safeeval,$n)=@_;
1193: my $defaultbg;
1194: my $rowdata='';
1195: my $dataflag=0;
1196: unless ($n eq '-') {
1197: $defaultbg=((($n-1)/5)==int(($n-1)/5))?'#E0E0':'#FFFF';
1198: } else {
1199: $defaultbg='#E0FF';
1200: }
1201: unless ($ENV{'form.showcsv'}) {
1202: $rowdata.="\n<tr><td><b><font size=+1>$n</font></b></td>";
1203: } else {
1204: $rowdata.="\n".'"'.$n.'"';
1205: }
1206: my $showf=0;
1207: my $proc;
1208: my $maxred=1;
1209: my $sheettype=&gettype($safeeval);
1210: if ($sheettype eq 'studentcalc') {
1211: $proc='&outrowassess';
1212: $maxred=26;
1213: } else {
1214: $proc='&outrow';
1215: }
1216: if ($sheettype eq 'assesscalc') {
1217: $maxred=1;
1218: } else {
1219: $maxred=26;
1220: }
1221: if (&getfa($safeeval,$n)=~/^[\~\-]/) { $maxred=1; }
1222: if ($n eq '-') {
1223: $proc='&templaterow';
1224: $n=-1;
1225: $dataflag=1;
1226: }
1227: foreach ($safeeval->reval($proc.'('.$n.')')) {
1228: my $bgcolor=$defaultbg.((($showf-1)/5==int(($showf-1)/5))?'99':'DD');
1229: my ($fm,$vl)=split(/\_\_\_eq\_\_\_/,$_);
1230: if ((($vl ne '') || ($vl eq '0')) &&
1231: (($showf==1) || ($sheettype ne 'studentcalc'))) { $dataflag=1; }
1232: if ($showf==0) { $vl=$_; }
1233: unless ($ENV{'form.showcsv'}) {
1234: if ($showf<=$maxred) { $bgcolor='#FFDDDD'; }
1235: if (($n==0) && ($showf<=26)) { $bgcolor='#CCCCFF'; }
1236: if (($showf>$maxred) || ((!$n) && ($showf>0))) {
1237: if ($vl eq '') {
1238: $vl='<font size=+2 color='.$bgcolor.'>#</font>';
1239: }
1240: $rowdata.=
1241: '<td bgcolor='.$bgcolor.'><a href="javascript:celledit('.$fm.');">'.$vl.
1242: '</a></td>';
1243: } else {
1244: $rowdata.='<td bgcolor='.$bgcolor.'> '.$vl.' </td>';
1245: }
1246: } else {
1247: $rowdata.=',"'.$vl.'"';
1248: }
1249: $showf++;
1250: } # End of foreach($safeval...)
1251: if ($ENV{'form.showall'} || ($dataflag)) {
1252: return $rowdata.($ENV{'form.showcsv'}?'':'</tr>');
1253: } else {
1254: return '';
1255: }
1256: }
1257:
1258: # ------------------------------------------------------------- Print out sheet
1259:
1260: sub outsheet {
1261: my ($r,$safeeval)=@_;
1262: my $maxred;
1263: my $realm;
1264: if (&gettype($safeeval) eq 'assesscalc') {
1265: $maxred=1;
1266: $realm='Assessment';
1267: } elsif (&gettype($safeeval) eq 'studentcalc') {
1268: $maxred=26;
1269: $realm='User';
1270: } else {
1271: $maxred=26;
1272: $realm='Course';
1273: }
1274: my $maxyellow=52-$maxred;
1275: my $tabledata;
1276: unless ($ENV{'form.showcsv'}) {
1277: $tabledata=
1278: '<table border=2><tr><th colspan=2 rowspan=2><font size=+2>'.
1279: $realm.'</font></th>'.
1280: '<td bgcolor=#FFDDDD colspan='.$maxred.
1281: '><b><font size=+1>Import</font></b></td>'.
1282: '<td colspan='.$maxyellow.
1283: '><b><font size=+1>Calculations</font></b></td></tr><tr>';
1284: my $showf=0;
1285: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1286: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
1287: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
1288: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1289: $showf++;
1290: if ($showf<=$maxred) {
1291: $tabledata.='<td bgcolor="#FFDDDD">';
1292: } else {
1293: $tabledata.='<td>';
1294: }
1295: $tabledata.="<b><font size=+1>$_</font></b></td>";
1296: }
1297: $tabledata.='</tr>'.&rown($safeeval,'-').&rown($safeeval,0);
1298: } else { $tabledata='<pre>'; }
1299:
1300: $r->print($tabledata);
1301:
1302: my $row;
1303: my $maxrow=&getmaxrow($safeeval);
1304:
1305: my @sortby=();
1306: my @sortidx=();
1307: for ($row=1;$row<=$maxrow;$row++) {
1308: $sortby[$row-1]=$safeeval->reval('$f{"A'.$row.'"}');
1309: $sortidx[$row-1]=$row-1;
1310: }
1311: @sortidx=sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1312: my $what='Student';
1313: if (&gettype($safeeval) eq 'assesscalc') {
1314: $what='Item';
1315: } elsif (&gettype($safeeval) eq 'studentcalc') {
1316: $what='Assessment';
1317: }
1318:
1319: my $n=0;
1320: for ($row=0;$row<$maxrow;$row++) {
1321: my $thisrow=&rown($safeeval,$sortidx[$row]+1);
1322: if ($thisrow) {
1323: if (($n/25==int($n/25)) && (!$ENV{'form.showcsv'})) {
1324: $r->print("</table>\n<br>\n");
1325: $r->rflush();
1326: $r->print('<table border=2><tr><td> <td>'.$what.'</td>');
1327: $r->print('<td>'.join('</td><td>',
1328: (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
1329: 'abcdefghijklmnopqrstuvwxyz'))).
1330: "</td></tr>\n");
1331: }
1332: $n++;
1333: $r->print($thisrow);
1334: }
1335: }
1336: $r->print($ENV{'form.showcsv'}?'</pre>':'</table>');
1337: }
1338:
1339: #
1340: # ----------------------------------------------- Read list of available sheets
1341: #
1342: sub othersheets {
1343: my ($safeeval,$stype)=@_;
1344: #
1345: my $cnum = &getcnum($safeeval);
1346: my $cdom = &getcdom($safeeval);
1347: my $chome = &getchome($safeeval);
1348: #
1349: my @alternatives=();
1350: my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
1351: my ($tmp) = keys(%results);
1352: unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1353: @alternatives = sort (keys(%results));
1354: }
1355: return @alternatives;
1356: }
1357:
1358:
1359: #
1360: # -------------------------------------- Parse a spreadsheet
1361: #
1362: sub parse_sheet {
1363: # $sheetxml is a scalar reference or a scalar
1364: my ($sheetxml) = @_;
1365: if (! ref($sheetxml)) {
1366: my $tmp = $sheetxml;
1367: $sheetxml = \$tmp;
1368: }
1369: my %f;
1370: my $parser=HTML::TokeParser->new($sheetxml);
1371: my $token;
1372: while ($token=$parser->get_token) {
1373: if ($token->[0] eq 'S') {
1374: if ($token->[1] eq 'field') {
1375: $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
1376: $parser->get_text('/field');
1377: }
1378: if ($token->[1] eq 'template') {
1379: $f{'template_'.$token->[2]->{'col'}}=
1380: $parser->get_text('/template');
1381: }
1382: }
1383: }
1384: return \%f;
1385: }
1386:
1387: #
1388: # -------------------------------------- Read spreadsheet formulas for a course
1389: #
1390:
1391: sub readsheet {
1392: my ($safeeval,$fn)=@_;
1393: my $stype = &gettype($safeeval);
1394: my $cnum = &getcnum($safeeval);
1395: my $cdom = &getcdom($safeeval);
1396: my $chome = &getchome($safeeval);
1397:
1398: if (! defined($fn)) {
1399: # There is no filename. Look for defaults in course and global, cache
1400: unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
1401: my %tmphash = &Apache::lonnet::get('environment',
1402: ['spreadsheet_default_'.$stype],
1403: $cdom,$cnum);
1404: my ($tmp) = keys(%tmphash);
1405: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1406: $fn = 'default_'.$stype;
1407: } else {
1408: $fn = $tmphash{'spreadsheet_default_'.$stype};
1409: }
1410: unless (($fn) && ($fn!~/^error\:/)) {
1411: $fn='default_'.$stype;
1412: }
1413: $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn;
1414: }
1415: }
1416: # $fn now has a value
1417: &setfilename($safeeval,$fn);
1418: # see if sheet is cached
1419: my $fstring='';
1420: if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
1421: &setformulas($safeeval,split(/\_\_\_\;\_\_\_/,$fstring));
1422: } else {
1423: # Not cached, need to read
1424: my %f=();
1425: if ($fn=~/^default\_/) {
1426: my $sheetxml='';
1427: my $fh;
1428: my $dfn=$fn;
1429: $dfn=~s/\_/\./g;
1430: if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
1431: $sheetxml=join('',<$fh>);
1432: } else {
1433: $sheetxml='<field row="0" col="A">"Error"</field>';
1434: }
1435: %f=%{&parse_sheet(\$sheetxml)};
1436: } elsif($fn=~/\/*\.spreadsheet$/) {
1437: my $sheetxml=&Apache::lonnet::getfile
1438: (&Apache::lonnet::filelocation('',$fn));
1439: if ($sheetxml == -1) {
1440: $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
1441: .$fn.'"</field>';
1442: }
1443: %f=%{&parse_sheet(\$sheetxml)};
1444: } else {
1445: my $sheet='';
1446: my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
1447: my ($tmp) = keys(%tmphash);
1448: unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1449: foreach (keys(%tmphash)) {
1450: $f{$_}=$tmphash{$_};
1451: }
1452: }
1453: }
1454: # Cache and set
1455: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
1456: &setformulas($safeeval,%f);
1457: }
1458: }
1459:
1460: # -------------------------------------------------------- Make new spreadsheet
1461:
1462: sub makenewsheet {
1463: my ($uname,$udom,$stype,$usymb)=@_;
1464: my $safeeval=initsheet($stype);
1465: $safeeval->reval(
1466: '$uname="'.$uname.
1467: '";$udom="'.$udom.
1468: '";$uhome="'.&Apache::lonnet::homeserver($uname,$udom).
1469: '";$sheettype="'.$stype.
1470: '";$usymb="'.$usymb.
1471: '";$csec="'.&Apache::lonnet::usection($udom,$uname,
1472: $ENV{'request.course.id'}).
1473: '";$cid="'.$ENV{'request.course.id'}.
1474: '";$cfn="'.$ENV{'request.course.fn'}.
1475: '";$cnum="'.$ENV{'course.'.$ENV{'request.course.id'}.'.num'}.
1476: '";$cdom="'.$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}.
1477: '";$chome="'.$ENV{'course.'.$ENV{'request.course.id'}.'.home'}.'";');
1478: return $safeeval;
1479: }
1480:
1481: # ------------------------------------------------------------ Save spreadsheet
1482:
1483: sub writesheet {
1484: my ($safeeval,$makedef)=@_;
1485: my $cid=&getcid($safeeval);
1486: if (&Apache::lonnet::allowed('opa',$cid)) {
1487: my %f=&getformulas($safeeval);
1488: my $stype=&gettype($safeeval);
1489: my $cnum=&getcnum($safeeval);
1490: my $cdom=&getcdom($safeeval);
1491: my $chome=&getchome($safeeval);
1492: my $fn=&getfilename($safeeval);
1493: # Cache new sheet
1494: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
1495: # Write sheet
1496: my $sheetdata='';
1497: foreach (keys(%f)) {
1498: unless ($f{$_} eq 'import') {
1499: $sheetdata.=&Apache::lonnet::escape($_).'='.
1500: &Apache::lonnet::escape($f{$_}).'&';
1501: }
1502: }
1503: $sheetdata=~s/\&$//;
1504: my $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.$fn.':'.
1505: $sheetdata,$chome);
1506: if ($reply eq 'ok') {
1507: $reply=&Apache::lonnet::reply('put:'.$cdom.':'.$cnum.':'.
1508: $stype.'_spreadsheets:'.
1509: &Apache::lonnet::escape($fn).
1510: '='.$ENV{'user.name'}.'@'.
1511: $ENV{'user.domain'},
1512: $chome);
1513: if ($reply eq 'ok') {
1514: if ($makedef) {
1515: return &Apache::lonnet::reply('put:'.$cdom.':'.$cnum.
1516: ':environment:'.
1517: 'spreadsheet_default_'.
1518: $stype.'='.
1519: &Apache::lonnet::escape($fn),
1520: $chome);
1521: }
1522: return $reply;
1523: }
1524: return $reply;
1525: }
1526: return $reply;
1527: }
1528: return 'unauthorized';
1529: }
1530:
1531: # ----------------------------------------------- Make a temp copy of the sheet
1532: # "Modified workcopy" - interactive only
1533: #
1534:
1535: sub tmpwrite {
1536: my $safeeval=shift;
1537: my $fn=$ENV{'user.name'}.'_'.
1538: $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
1539: &getfilename($safeeval);
1540: $fn=~s/\W/\_/g;
1541: $fn=$tmpdir.$fn.'.tmp';
1542: my $fh;
1543: if ($fh=Apache::File->new('>'.$fn)) {
1544: print $fh join("\n",&getformulas($safeeval));
1545: }
1546: }
1547:
1548: # ---------------------------------------------------------- Read the temp copy
1549:
1550: sub tmpread {
1551: my ($safeeval,$nfield,$nform)=@_;
1552: my $fn=$ENV{'user.name'}.'_'.
1553: $ENV{'user.domain'}.'_spreadsheet_'.&getusymb($safeeval).'_'.
1554: &getfilename($safeeval);
1555: $fn=~s/\W/\_/g;
1556: $fn=$tmpdir.$fn.'.tmp';
1557: my $fh;
1558: my %fo=();
1559: my $countrows=0;
1560: if ($fh=Apache::File->new($fn)) {
1561: my $name;
1562: while ($name=<$fh>) {
1563: chomp($name);
1564: my $value=<$fh>;
1565: chomp($value);
1566: $fo{$name}=$value;
1567: if ($name=~/^A(\d+)$/) {
1568: if ($1>$countrows) {
1569: $countrows=$1;
1570: }
1571: }
1572: }
1573: }
1574: if ($nform eq 'changesheet') {
1575: $fo{'A'.$nfield}=(split(/\_\_\&\&\&\_\_/,$fo{'A'.$nfield}))[0];
1576: unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
1577: $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
1578: }
1579: } elsif ($nfield eq 'insertrow') {
1580: $countrows++;
1581: my $newrow=substr('000000'.$countrows,-7);
1582: if ($nform eq 'top') {
1583: $fo{'A'.$countrows}='--- '.$newrow;
1584: } else {
1585: $fo{'A'.$countrows}='~~~ '.$newrow;
1586: }
1587: } else {
1588: if ($nfield) { $fo{$nfield}=$nform; }
1589: }
1590: &setformulas($safeeval,%fo);
1591: }
1592:
1593: ##################################################
1594: ##################################################
1595:
1596: =pod
1597:
1598: =item &parmval()
1599:
1600: Determine the value of a parameter.
1601:
1602: Inputs: $what, the parameter needed, $safeeval, the safe space
1603:
1604: Returns: The value of a parameter, or '' if none.
1605:
1606: This function cascades through the possible levels searching for a value for
1607: a parameter. The levels are checked in the following order:
1608: user, course (at section level and course level), map, and lonnet::metadata.
1609: This function uses %parmhash, which must be tied prior to calling it.
1610: This function also requires %courseopt and %useropt to be initialized for
1611: this user and course.
1612:
1613: =cut
1614:
1615: ##################################################
1616: ##################################################
1617: sub parmval {
1618: my ($what,$safeeval)=@_;
1619: my $symb = &getusymb($safeeval);
1620: unless ($symb) { return ''; }
1621: #
1622: my $cid = &getcid($safeeval);
1623: my $csec = &getcsec($safeeval);
1624: my $uname = &getuname($safeeval);
1625: my $udom = &getudom($safeeval);
1626: my $result='';
1627: #
1628: my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
1629: # Cascading lookup scheme
1630: my $rwhat=$what;
1631: $what =~ s/^parameter\_//;
1632: $what =~ s/\_([^\_]+)$/\.$1/;
1633: #
1634: my $symbparm = $symb.'.'.$what;
1635: my $mapparm = $mapname.'___(all).'.$what;
1636: my $usercourseprefix = $uname.'_'.$udom.'_'.$cid;
1637: #
1638: my $seclevel = $usercourseprefix.'.['.$csec.'].'.$what;
1639: my $seclevelr = $usercourseprefix.'.['.$csec.'].'.$symbparm;
1640: my $seclevelm = $usercourseprefix.'.['.$csec.'].'.$mapparm;
1641: #
1642: my $courselevel = $usercourseprefix.'.'.$what;
1643: my $courselevelr = $usercourseprefix.'.'.$symbparm;
1644: my $courselevelm = $usercourseprefix.'.'.$mapparm;
1645: # fourth, check user
1646: if ($uname) {
1647: return $useropt{$courselevelr} if ($useropt{$courselevelr});
1648: return $useropt{$courselevelm} if ($useropt{$courselevelm});
1649: return $useropt{$courselevel} if ($useropt{$courselevel});
1650: }
1651: # third, check course
1652: if ($csec) {
1653: return $courseopt{$seclevelr} if ($courseopt{$seclevelr});
1654: return $courseopt{$seclevelm} if ($courseopt{$seclevelm});
1655: return $courseopt{$seclevel} if ($courseopt{$seclevel});
1656: }
1657: #
1658: return $courseopt{$courselevelr} if ($courseopt{$courselevelr});
1659: return $courseopt{$courselevelm} if ($courseopt{$courselevelm});
1660: return $courseopt{$courselevel} if ($courseopt{$courselevel});
1661: # second, check map parms
1662: my $thisparm = $parmhash{$symbparm};
1663: return $thisparm if ($thisparm);
1664: # first, check default
1665: return &Apache::lonnet::metadata($fn,$rwhat.'.default');
1666: }
1667:
1668: # ---------------------------------------------- Update rows for course listing
1669: sub updateclasssheet {
1670: my $safeeval=shift;
1671: my $cnum=&getcnum($safeeval);
1672: my $cdom=&getcdom($safeeval);
1673: my $cid=&getcid($safeeval);
1674: my $chome=&getchome($safeeval);
1675: #
1676: # Read class list and row labels
1677: my %classlist;
1678: my @tmp = &Apache::lonnet::dump('classlist',$cdom,$cnum);
1679: if ($tmp[0] !~ /^error/) {
1680: %classlist = @tmp;
1681: } else {
1682: return 'Could not access course data';
1683: }
1684: undef @tmp;
1685: #
1686: my %currentlist=();
1687: my $now=time;
1688: foreach my $student (keys(%classlist)) {
1689: my ($end,$start)=split(/\:/,$classlist{$student});
1690: my $active=1;
1691: $active = 0 if (($end) && ($now>$end));
1692: $active = 1 if ($ENV{'form.Status'} eq 'Any');
1693: $active = !$active if ($ENV{'form.Status'} eq 'Expired');
1694: if ($active) {
1695: my $rowlabel='';
1696: my ($studentName,$studentDomain)=split(/\:/,$student);
1697: my $studentSection=&Apache::lonnet::usection($studentDomain,
1698: $studentName,$cid);
1699: if ($studentSection==-1) {
1700: unless ($ENV{'form.showcsv'}) {
1701: $rowlabel='<font color=red>Data not available: '.
1702: $studentName.'</font>';
1703: } else {
1704: $rowlabel='ERROR","'.$studentName.
1705: '","Data not available","","","';
1706: }
1707: } else {
1708: my %reply=&Apache::lonnet::idrget($studentDomain,$studentName);
1709: my %studentInformation=&Apache::lonnet::get
1710: ('environment',
1711: ['lastname','generation','firstname','middlename','id'],
1712: $studentDomain,$studentName);
1713: if (! $ENV{'form.showcsv'}) {
1714: $rowlabel='<a href="/adm/studentcalc?uname='.$studentName.
1715: '&udom='.$studentDomain.'">'.
1716: $studentSection.' ';
1717: foreach ('id','firstname','middlename',
1718: 'lastname','generation'){
1719: $rowlabel.=$studentInformation{$_}." ";
1720: }
1721: $rowlabel.='</a>';
1722: } else {
1723: $rowlabel= '"'.join('","',
1724: ($studentSection,
1725: $studentInformation{'id'},
1726: $studentInformation{'firstname'},
1727: $studentInformation{'middlename'},
1728: $studentInformation{'lastname'},
1729: $studentInformation{'generation'})
1730: ).'"';
1731: }
1732: }
1733: $currentlist{$student}=$rowlabel;
1734: } # end of if ($active)
1735: } # end of foreach my $student (keys(%classlist))
1736: #
1737: # Find discrepancies between the course row table and this
1738: #
1739: my %f=&getformulas($safeeval);
1740: my $changed=0;
1741: #
1742: my $maxrow=0;
1743: my %existing=();
1744: #
1745: # Now obsolete rows
1746: foreach (keys(%f)) {
1747: if ($_=~/^A(\d+)/) {
1748: $maxrow=($1>$maxrow)?$1:$maxrow;
1749: $existing{$f{$_}}=1;
1750: unless ((defined($currentlist{$f{$_}})) || (!$1) ||
1751: ($f{$_}=~/^(\~\~\~|\-\-\-)/)) {
1752: $f{$_}='!!! Obsolete';
1753: $changed=1;
1754: }
1755: }
1756: }
1757: #
1758: # New and unknown keys
1759: foreach (sort keys(%currentlist)) {
1760: unless ($existing{$_}) {
1761: $changed=1;
1762: $maxrow++;
1763: $f{'A'.$maxrow}=$_;
1764: }
1765: }
1766: if ($changed) { &setformulas($safeeval,%f); }
1767: #
1768: &setmaxrow($safeeval,$maxrow);
1769: &setrowlabels($safeeval,%currentlist);
1770: }
1771:
1772: # ----------------------------------- Update rows for student and assess sheets
1773: sub updatestudentassesssheet {
1774: my $safeeval=shift;
1775: my %bighash;
1776: my $stype=&gettype($safeeval);
1777: my %current=();
1778: if ($updatedata{$ENV{'request.course.fn'}.'_'.$stype}) {
1779: %current=split(/\_\_\_\;\_\_\_/,
1780: $updatedata{$ENV{'request.course.fn'}.'_'.$stype});
1781: } else {
1782: # Tie hash
1783: tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
1784: &GDBM_READER(),0640);
1785: if (! tied(%bighash)) {
1786: return 'Could not access course data';
1787: }
1788: # Get all assessments
1789: my %allkeys=('timestamp' =>
1790: 'Timestamp of Last Transaction<br>timestamp',
1791: 'subnumber' =>
1792: 'Number of Submissions<br>subnumber',
1793: 'tutornumber' =>
1794: 'Number of Tutor Responses<br>tutornumber',
1795: 'totalpoints' =>
1796: 'Total Points Granted<br>totalpoints');
1797: my $adduserstr='';
1798: if ((&getuname($safeeval) ne $ENV{'user.name'}) ||
1799: (&getudom($safeeval) ne $ENV{'user.domain'})) {
1800: $adduserstr='&uname='.&getuname($safeeval).
1801: '&udom='.&getudom($safeeval);
1802: }
1803: my %allassess =
1804: ('_feedback' =>'<a href="/adm/assesscalc?usymb=_feedback'.
1805: $adduserstr.'">Feedback</a>',
1806: '_evaluation' =>'<a href="/adm/assesscalc?usymb=_evaluation'.
1807: $adduserstr.'">Evaluation</a>',
1808: '_tutoring' =>'<a href="/adm/assesscalc?usymb=_tutoring'.
1809: $adduserstr.'">Tutoring</a>',
1810: '_discussion' =>'<a href="/adm/assesscalc?usymb=_discussion'.
1811: $adduserstr.'">Discussion</a>'
1812: );
1813: foreach (keys(%bighash)) {
1814: next if ($_!~/^src\_(\d+)\.(\d+)$/);
1815: my $mapid=$1;
1816: my $resid=$2;
1817: my $id=$mapid.'.'.$resid;
1818: my $srcf=$bighash{$_};
1819: if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
1820: my $symb=
1821: &Apache::lonnet::declutter($bighash{'map_id_'.$mapid}).
1822: '___'.$resid.'___'.&Apache::lonnet::declutter($srcf);
1823: $allassess{$symb}=
1824: '<a href="/adm/assesscalc?usymb='.$symb.$adduserstr.'">'.
1825: $bighash{'title_'.$id}.'</a>';
1826: next if ($stype ne 'assesscalc');
1827: foreach my $key (split(/\,/,
1828: &Apache::lonnet::metadata($srcf,'keys')
1829: )) {
1830: next if ($key !~ /^(stores|parameter)_/);
1831: my $display=
1832: &Apache::lonnet::metadata($srcf,$key.'.display');
1833: unless ($display) {
1834: $display.=
1835: &Apache::lonnet::metadata($srcf,$key.'.name');
1836: }
1837: $display.='<br>'.$key;
1838: $allkeys{$key}=$display;
1839: } # end of foreach
1840: }
1841: } # end of foreach (keys(%bighash))
1842: untie(%bighash);
1843: #
1844: # %allkeys has a list of storage and parameter displays by unikey
1845: # %allassess has a list of all resource displays by symb
1846: #
1847: if ($stype eq 'assesscalc') {
1848: %current=%allkeys;
1849: } elsif ($stype eq 'studentcalc') {
1850: %current=%allassess;
1851: }
1852: $updatedata{$ENV{'request.course.fn'}.'_'.$stype}=
1853: join('___;___',%current);
1854: # Get current from cache
1855: }
1856: # Find discrepancies between the course row table and this
1857: #
1858: my %f=&getformulas($safeeval);
1859: my $changed=0;
1860:
1861: my $maxrow=0;
1862: my %existing=();
1863: # Now obsolete rows
1864: foreach (keys(%f)) {
1865: next if ($_!~/^A(\d+)/);
1866: $maxrow=($1>$maxrow)?$1:$maxrow;
1867: my ($usy,$ufn)=split(/\_\_\&\&\&\_\_/,$f{$_});
1868: $existing{$usy}=1;
1869: unless ((defined($current{$usy})) || (!$1) ||
1870: ($f{$_}=~/^(\~\~\~|\-\-\-)/)){
1871: $f{$_}='!!! Obsolete';
1872: $changed=1;
1873: } elsif ($ufn) {
1874: $current{$usy}
1875: =~s/assesscalc\?usymb\=/assesscalc\?ufn\=$ufn\&usymb\=/;
1876: }
1877: }
1878: # New and unknown keys
1879: foreach (keys(%current)) {
1880: unless ($existing{$_}) {
1881: $changed=1;
1882: $maxrow++;
1883: $f{'A'.$maxrow}=$_;
1884: }
1885: }
1886: if ($changed) { &setformulas($safeeval,%f); }
1887: &setmaxrow($safeeval,$maxrow);
1888: &setrowlabels($safeeval,%current);
1889: #
1890: undef %current;
1891: undef %existing;
1892: }
1893:
1894: # ------------------------------------------------ Load data for one assessment
1895:
1896: sub loadstudent {
1897: my $safeeval=shift;
1898: my %c=();
1899: my %f=&getformulas($safeeval);
1900: $cachedassess=&getuname($safeeval).':'.&getudom($safeeval);
1901: # Get ALL the student preformance data
1902: my @tmp = &Apache::lonnet::dump(&getcid($safeeval),
1903: &getudom($safeeval),
1904: &getuname($safeeval),
1905: undef);
1906: if ($tmp[0] !~ /^error:/) {
1907: %cachedstores = @tmp;
1908: }
1909: undef @tmp;
1910: #
1911: my @assessdata=();
1912: foreach (keys(%f)) {
1913: next if ($_!~/^A(\d+)/);
1914: my $row=$1;
1915: next if (($f{$_}=~/^[\!\~\-]/) || ($row==0));
1916: my ($usy,$ufn)=split(/__&&&\__/,$f{$_});
1917: @assessdata=&exportsheet(&getuname($safeeval),
1918: &getudom($safeeval),
1919: 'assesscalc',$usy,$ufn);
1920: my $index=0;
1921: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1922: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1923: if ($assessdata[$index]) {
1924: my $col=$_;
1925: if ($assessdata[$index]=~/\D/) {
1926: $c{$col.$row}="'".$assessdata[$index]."'";
1927: } else {
1928: $c{$col.$row}=$assessdata[$index];
1929: }
1930: unless ($col eq 'A') {
1931: $f{$col.$row}='import';
1932: }
1933: }
1934: $index++;
1935: }
1936: }
1937: $cachedassess='';
1938: undef %cachedstores;
1939: &setformulas($safeeval,%f);
1940: &setconstants($safeeval,%c);
1941: }
1942:
1943: # --------------------------------------------------- Load data for one student
1944:
1945: sub loadcourse {
1946: my ($safeeval,$r)=@_;
1947: my %c=();
1948: my %f=&getformulas($safeeval);
1949: my $total=0;
1950: foreach (keys(%f)) {
1951: if ($_=~/^A(\d+)/) {
1952: unless ($f{$_}=~/^[\!\~\-]/) { $total++; }
1953: }
1954: }
1955: my $now=0;
1956: my $since=time;
1957: $r->print(<<ENDPOP);
1958: <script>
1959: popwin=open('','popwin','width=400,height=100');
1960: popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
1961: '<h3>Spreadsheet Calculation Progress</h3>'+
1962: '<form name=popremain>'+
1963: '<input type=text size=35 name=remaining value=Starting></form>'+
1964: '</body></html>');
1965: popwin.document.close();
1966: </script>
1967: ENDPOP
1968: $r->rflush();
1969: foreach (keys(%f)) {
1970: next if ($_!~/^A(\d+)/);
1971: my $row=$1;
1972: next if (($f{$_}=~/^[\!\~\-]/) || ($row==0));
1973: my @studentdata=&exportsheet(split(/\:/,$f{$_}),
1974: 'studentcalc');
1975: undef %userrdatas;
1976: $now++;
1977: $r->print('<script>popwin.document.popremain.remaining.value="'.
1978: $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
1979: ' secs remaining";</script>');
1980: $r->rflush();
1981: #
1982: my $index=0;
1983: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1984: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1985: if ($studentdata[$index]) {
1986: my $col=$_;
1987: if ($studentdata[$index]=~/\D/) {
1988: $c{$col.$row}="'".$studentdata[$index]."'";
1989: } else {
1990: $c{$col.$row}=$studentdata[$index];
1991: }
1992: unless ($col eq 'A') {
1993: $f{$col.$row}='import';
1994: }
1995: $index++;
1996: }
1997: }
1998: }
1999: &setformulas($safeeval,%f);
2000: &setconstants($safeeval,%c);
2001: $r->print('<script>popwin.close()</script>');
2002: $r->rflush();
2003: }
2004:
2005: # ------------------------------------------------ Load data for one assessment
2006:
2007: sub loadassessment {
2008: my $safeeval=shift;
2009:
2010: my $uhome = &getuhome($safeeval);
2011: my $uname = &getuname($safeeval);
2012: my $udom = &getudom($safeeval);
2013: my $symb = &getusymb($safeeval);
2014: my $cid = &getcid($safeeval);
2015: my $cnum = &getcnum($safeeval);
2016: my $cdom = &getcdom($safeeval);
2017: my $chome = &getchome($safeeval);
2018:
2019: my $namespace;
2020: unless ($namespace=$cid) { return ''; }
2021: # Get stored values
2022: my %returnhash=();
2023: if ($cachedassess eq $uname.':'.$udom) {
2024: #
2025: # get data out of the dumped stores
2026: #
2027: my $version=$cachedstores{'version:'.$symb};
2028: my $scope;
2029: for ($scope=1;$scope<=$version;$scope++) {
2030: foreach (split(/\:/,$cachedstores{$scope.':keys:'.$symb})) {
2031: $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
2032: }
2033: }
2034: } else {
2035: #
2036: # restore individual
2037: #
2038: my $answer=&Apache::lonnet::reply(
2039: "restore:$udom:$uname:".
2040: &Apache::lonnet::escape($namespace).":".
2041: &Apache::lonnet::escape($symb),$uhome);
2042: foreach (split(/\&/,$answer)) {
2043: my ($name,$value)=split(/\=/,$_);
2044: $returnhash{&Apache::lonnet::unescape($name)}=
2045: &Apache::lonnet::unescape($value);
2046: }
2047: my $version;
2048: for ($version=1;$version<=$returnhash{'version'};$version++) {
2049: foreach (split(/\:/,$returnhash{$version.':keys'})) {
2050: $returnhash{$_}=$returnhash{$version.':'.$_};
2051: }
2052: }
2053: }
2054: # returnhash now has all stores for this resource
2055: # convert all "_" to "." to be able to use libraries, multiparts, etc
2056: my @oldkeys=keys %returnhash;
2057:
2058: foreach (@oldkeys) {
2059: my $name=$_;
2060: my $value=$returnhash{$_};
2061: delete $returnhash{$_};
2062: $name=~s/\_/\./g;
2063: $returnhash{$name}=$value;
2064: }
2065: # initialize coursedata and userdata for this user
2066: undef %courseopt;
2067: undef %useropt;
2068:
2069: my $userprefix=$uname.'_'.$udom.'_';
2070:
2071: unless ($uhome eq 'no_host') {
2072: # Get coursedata
2073: unless
2074: ((time-$courserdatas{$cid.'.last_cache'})<240) {
2075: my $reply=&Apache::lonnet::reply('dump:'.$cdom.':'.$cnum.
2076: ':resourcedata',$chome);
2077: if ($reply!~/^error\:/) {
2078: $courserdatas{$cid}=$reply;
2079: $courserdatas{$cid.'.last_cache'}=time;
2080: }
2081: }
2082: foreach (split(/\&/,$courserdatas{$cid})) {
2083: my ($name,$value)=split(/\=/,$_);
2084: $courseopt{$userprefix.&Apache::lonnet::unescape($name)}=
2085: &Apache::lonnet::unescape($value);
2086: }
2087: # Get userdata (if present)
2088: unless
2089: ((time-$userrdatas{$uname.'___'.$udom.'.last_cache'})<240) {
2090: my $reply=
2091: &Apache::lonnet::reply('dump:'.$udom.':'.$uname.':resourcedata',$uhome);
2092: if ($reply!~/^error\:/) {
2093: $userrdatas{$uname.'___'.$udom}=$reply;
2094: $userrdatas{$uname.'___'.$udom.'.last_cache'}=time;
2095: }
2096: }
2097: foreach (split(/\&/,$userrdatas{$uname.'___'.$udom})) {
2098: my ($name,$value)=split(/\=/,$_);
2099: $useropt{$userprefix.&Apache::lonnet::unescape($name)}=
2100: &Apache::lonnet::unescape($value);
2101: }
2102: }
2103: # now courseopt, useropt initialized for this user and course
2104: # (used by parmval)
2105: #
2106: # Load keys for this assessment only
2107: #
2108: my %thisassess=();
2109: my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
2110: foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
2111: $thisassess{$_}=1;
2112: }
2113: #
2114: # Load parameters
2115: #
2116: my %c=();
2117: if (tie(%parmhash,'GDBM_File',
2118: &getcfn($safeeval).'_parms.db',&GDBM_READER(),0640)) {
2119: my %f=&getformulas($safeeval);
2120: foreach (keys(%f)) {
2121: next if ($_!~/^A/);
2122: next if ($f{$_}=~/^[\!\~\-]/);
2123: if ($f{$_}=~/^parameter/) {
2124: if ($thisassess{$f{$_}}) {
2125: my $val=&parmval($f{$_},$safeeval);
2126: $c{$_}=$val;
2127: $c{$f{$_}}=$val;
2128: }
2129: } else {
2130: my $key=$f{$_};
2131: my $ckey=$key;
2132: $key=~s/^stores\_/resource\./;
2133: $key=~s/\_/\./g;
2134: $c{$_}=$returnhash{$key};
2135: $c{$ckey}=$returnhash{$key};
2136: }
2137: }
2138: untie(%parmhash);
2139: }
2140: &setconstants($safeeval,%c);
2141: }
2142:
2143: # --------------------------------------------------------- Various form fields
2144:
2145: sub textfield {
2146: my ($title,$name,$value)=@_;
2147: return "\n<p><b>$title:</b><br>".
2148: '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
2149: }
2150:
2151: sub hiddenfield {
2152: my ($name,$value)=@_;
2153: return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
2154: }
2155:
2156: sub selectbox {
2157: my ($title,$name,$value,%options)=@_;
2158: my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
2159: foreach (sort keys(%options)) {
2160: $selout.='<option value="'.$_.'"';
2161: if ($_ eq $value) { $selout.=' selected'; }
2162: $selout.='>'.$options{$_}.'</option>';
2163: }
2164: return $selout.'</select>';
2165: }
2166:
2167: # =============================================== Update information in a sheet
2168: #
2169: # Add new users or assessments, etc.
2170: #
2171:
2172: sub updatesheet {
2173: my $safeeval=shift;
2174: my $stype=&gettype($safeeval);
2175: if ($stype eq 'classcalc') {
2176: return &updateclasssheet($safeeval);
2177: } else {
2178: return &updatestudentassesssheet($safeeval);
2179: }
2180: }
2181:
2182: # =================================================== Load the rows for a sheet
2183: #
2184: # Import the data for rows
2185: #
2186:
2187: sub loadrows {
2188: my ($safeeval,$r)=@_;
2189: my $stype=&gettype($safeeval);
2190: if ($stype eq 'classcalc') {
2191: &loadcourse($safeeval,$r);
2192: } elsif ($stype eq 'studentcalc') {
2193: &loadstudent($safeeval);
2194: } else {
2195: &loadassessment($safeeval);
2196: }
2197: }
2198:
2199: # ======================================================= Forced recalculation?
2200:
2201: sub checkthis {
2202: my ($keyname,$time)=@_;
2203: return ($time<$expiredates{$keyname});
2204: }
2205:
2206: sub forcedrecalc {
2207: my ($uname,$udom,$stype,$usymb)=@_;
2208: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2209: my $time=$oldsheets{$key.'.time'};
2210: if ($ENV{'form.forcerecalc'}) { return 1; }
2211: unless ($time) { return 1; }
2212: if ($stype eq 'assesscalc') {
2213: my $map=(split(/\_\_\_/,$usymb))[0];
2214: if (&checkthis('::assesscalc:',$time) ||
2215: &checkthis('::assesscalc:'.$map,$time) ||
2216: &checkthis('::assesscalc:'.$usymb,$time) ||
2217: &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
2218: &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
2219: &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
2220: return 1;
2221: }
2222: } else {
2223: if (&checkthis('::studentcalc:',$time) ||
2224: &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
2225: return 1;
2226: }
2227: }
2228: return 0;
2229: }
2230:
2231: # ============================================================== Export handler
2232: #
2233: # Non-interactive call from with program
2234: #
2235:
2236: sub exportsheet {
2237: my ($uname,$udom,$stype,$usymb,$fn)=@_;
2238: my @exportarr=();
2239: if (($usymb=~/^\_(\w+)/) && (!$fn)) {
2240: $fn='default_'.$1;
2241: }
2242: #
2243: # Check if cached
2244: #
2245: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2246: my $found='';
2247: if ($oldsheets{$key}) {
2248: foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
2249: my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
2250: if ($name eq $fn) {
2251: $found=$value;
2252: }
2253: }
2254: }
2255: unless ($found) {
2256: &cachedssheets($uname,$udom,&Apache::lonnet::homeserver($uname,$udom));
2257: if ($oldsheets{$key}) {
2258: foreach (split(/\_\_\_\&\_\_\_/,$oldsheets{$key})) {
2259: my ($name,$value)=split(/\_\_\_\=\_\_\_/,$_);
2260: if ($name eq $fn) {
2261: $found=$value;
2262: }
2263: }
2264: }
2265: }
2266: #
2267: # Check if still valid
2268: #
2269: if ($found) {
2270: if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
2271: $found='';
2272: }
2273: }
2274: if ($found) {
2275: #
2276: # Return what was cached
2277: #
2278: @exportarr=split(/\_\_\_\;\_\_\_/,$found);
2279: } else {
2280: #
2281: # Not cached
2282: #
2283: my $thissheet=&makenewsheet($uname,$udom,$stype,$usymb);
2284: &readsheet($thissheet,$fn);
2285: &updatesheet($thissheet);
2286: &loadrows($thissheet);
2287: &calcsheet($thissheet);
2288: @exportarr=&exportdata($thissheet);
2289: #
2290: # Store now
2291: #
2292: my $cid=$ENV{'request.course.id'};
2293: my $current='';
2294: if ($stype eq 'studentcalc') {
2295: $current=&Apache::lonnet::reply('get:'.
2296: $ENV{'course.'.$cid.'.domain'}.':'.
2297: $ENV{'course.'.$cid.'.num'}.
2298: ':nohist_calculatedsheets:'.
2299: &Apache::lonnet::escape($key),
2300: $ENV{'course.'.$cid.'.home'});
2301: } else {
2302: $current=&Apache::lonnet::reply('get:'.
2303: &getudom($thissheet).':'.
2304: &getuname($thissheet).
2305: ':nohist_calculatedsheets_'.
2306: $ENV{'request.course.id'}.':'.
2307: &Apache::lonnet::escape($key),
2308: &getuhome($thissheet));
2309: }
2310: my %currentlystored=();
2311: unless ($current=~/^error\:/) {
2312: foreach (split(/___&\___/,&Apache::lonnet::unescape($current))) {
2313: my ($name,$value)=split(/___=___/,$_);
2314: $currentlystored{$name}=$value;
2315: }
2316: }
2317: $currentlystored{$fn}=join('___;___',@exportarr);
2318: #
2319: my $newstore='';
2320: foreach (keys(%currentlystored)) {
2321: if ($newstore) { $newstore.='___&___'; }
2322: $newstore.=$_.'___=___'.$currentlystored{$_};
2323: }
2324: my $now=time;
2325: if ($stype eq 'studentcalc') {
2326: &Apache::lonnet::reply('put:'.
2327: $ENV{'course.'.$cid.'.domain'}.':'.
2328: $ENV{'course.'.$cid.'.num'}.
2329: ':nohist_calculatedsheets:'.
2330: &Apache::lonnet::escape($key).'='.
2331: &Apache::lonnet::escape($newstore).'&'.
2332: &Apache::lonnet::escape($key).'.time='.$now,
2333: $ENV{'course.'.$cid.'.home'});
2334: } else {
2335: &Apache::lonnet::reply('put:'.
2336: &getudom($thissheet).':'.
2337: &getuname($thissheet).
2338: ':nohist_calculatedsheets_'.
2339: $ENV{'request.course.id'}.':'.
2340: &Apache::lonnet::escape($key).'='.
2341: &Apache::lonnet::escape($newstore).'&'.
2342: &Apache::lonnet::escape($key).'.time='.$now,
2343: &getuhome($thissheet));
2344: }
2345: }
2346: return @exportarr;
2347: }
2348:
2349: # ============================================================ Expiration Dates
2350: #
2351: # Load previously cached student spreadsheets for this course
2352: #
2353: sub expirationdates {
2354: undef %expiredates;
2355: my $cid=$ENV{'request.course.id'};
2356: my $reply=&Apache::lonnet::reply('dump:'.
2357: $ENV{'course.'.$cid.'.domain'}.':'.
2358: $ENV{'course.'.$cid.'.num'}.
2359: ':nohist_expirationdates',
2360: $ENV{'course.'.$cid.'.home'});
2361: unless ($reply=~/^error\:/) {
2362: foreach (split(/\&/,$reply)) {
2363: my ($name,$value)=split(/\=/,$_);
2364: $expiredates{&Apache::lonnet::unescape($name)}
2365: =&Apache::lonnet::unescape($value);
2366: }
2367: }
2368: }
2369:
2370: # ===================================================== Calculated sheets cache
2371: #
2372: # Load previously cached student spreadsheets for this course
2373: #
2374:
2375: sub cachedcsheets {
2376: my $cid=$ENV{'request.course.id'};
2377: my $reply=&Apache::lonnet::reply('dump:'.
2378: $ENV{'course.'.$cid.'.domain'}.':'.
2379: $ENV{'course.'.$cid.'.num'}.
2380: ':nohist_calculatedsheets',
2381: $ENV{'course.'.$cid.'.home'});
2382: unless ($reply=~/^error\:/) {
2383: foreach ( split(/\&/,$reply)) {
2384: my ($name,$value)=split(/\=/,$_);
2385: $oldsheets{&Apache::lonnet::unescape($name)}
2386: =&Apache::lonnet::unescape($value);
2387: }
2388: }
2389: }
2390:
2391: # ===================================================== Calculated sheets cache
2392: #
2393: # Load previously cached assessment spreadsheets for this student
2394: #
2395:
2396: sub cachedssheets {
2397: my ($sname,$sdom,$shome)=@_;
2398: unless (($loadedcaches{$sname.'_'.$sdom}) || ($shome eq 'no_host')) {
2399: my $cid=$ENV{'request.course.id'};
2400: my $reply=&Apache::lonnet::reply('dump:'.$sdom.':'.$sname.
2401: ':nohist_calculatedsheets_'.
2402: $ENV{'request.course.id'},
2403: $shome);
2404: unless ($reply=~/^error\:/) {
2405: foreach ( split(/\&/,$reply)) {
2406: my ($name,$value)=split(/\=/,$_);
2407: $oldsheets{&Apache::lonnet::unescape($name)}
2408: =&Apache::lonnet::unescape($value);
2409: }
2410: }
2411: $loadedcaches{$sname.'_'.$sdom}=1;
2412: }
2413: }
2414:
2415: # ===================================================== Calculated sheets cache
2416: #
2417: # Load previously cached assessment spreadsheets for this student
2418: #
2419:
2420: # ================================================================ Main handler
2421: #
2422: # Interactive call to screen
2423: #
2424: #
2425:
2426:
2427: sub handler {
2428: my $r=shift;
2429: if ($r->header_only) {
2430: $r->content_type('text/html');
2431: $r->send_http_header;
2432: return OK;
2433: }
2434: # Global directory configs
2435: $includedir=$r->dir_config('lonIncludes');
2436: $tmpdir=$r->dir_config('lonDaemons').'/tmp/';
2437: # Needs to be in a course
2438: if ($ENV{'request.course.fn'}) {
2439: # Get query string for limited number of parameters
2440: &Apache::loncommon::get_unprocessed_cgi
2441: ($ENV{'QUERY_STRING'},['uname','udom','usymb','ufn']);
2442: if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'})) {
2443: $ENV{'form.ufn'}='default_'.$1;
2444: }
2445: # Interactive loading of specific sheet?
2446: if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
2447: $ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
2448: }
2449: # Nothing there? Must be login user
2450: my $aname;
2451: my $adom;
2452:
2453: unless ($ENV{'form.uname'}) {
2454: $aname=$ENV{'user.name'};
2455: $adom=$ENV{'user.domain'};
2456: } else {
2457: $aname=$ENV{'form.uname'};
2458: $adom=$ENV{'form.udom'};
2459: }
2460: # Open page
2461: $r->content_type('text/html');
2462: $r->header_out('Cache-control','no-cache');
2463: $r->header_out('Pragma','no-cache');
2464: $r->send_http_header;
2465: # Screen output
2466: $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
2467: $r->print(<<ENDSCRIPT);
2468: <script language="JavaScript">
2469:
2470: function celledit(cn,cf) {
2471: var cnf=prompt(cn,cf);
2472: if (cnf!=null) {
2473: document.sheet.unewfield.value=cn;
2474: document.sheet.unewformula.value=cnf;
2475: document.sheet.submit();
2476: }
2477: }
2478:
2479: function changesheet(cn) {
2480: document.sheet.unewfield.value=cn;
2481: document.sheet.unewformula.value='changesheet';
2482: document.sheet.submit();
2483: }
2484:
2485: function insertrow(cn) {
2486: document.sheet.unewfield.value='insertrow';
2487: document.sheet.unewformula.value=cn;
2488: document.sheet.submit();
2489: }
2490:
2491: </script>
2492: ENDSCRIPT
2493: $r->print('</head>'.&Apache::loncommon::bodytag('Grades Spreadsheet').
2494: '<form action="'.$r->uri.'" name=sheet method=post>'.
2495: &hiddenfield('uname',$ENV{'form.uname'}).
2496: &hiddenfield('udom',$ENV{'form.udom'}).
2497: &hiddenfield('usymb',$ENV{'form.usymb'}).
2498: &hiddenfield('unewfield','').
2499: &hiddenfield('unewformula',''));
2500: # Send this out right away
2501: $r->rflush();
2502: # Full recalc?
2503: if ($ENV{'form.forcerecalc'}) {
2504: $r->print('<h4>Completely Recalculating Sheet ...</h4>');
2505: undef %spreadsheets;
2506: undef %courserdatas;
2507: undef %userrdatas;
2508: undef %defaultsheets;
2509: undef %updatedata;
2510: }
2511: # Read new sheet or modified worksheet
2512: $r->uri=~/\/(\w+)$/;
2513: my $asheet=&makenewsheet($aname,$adom,$1,$ENV{'form.usymb'});
2514: # If a new formula had been entered, go from work copy
2515: if ($ENV{'form.unewfield'}) {
2516: $r->print('<h2>Modified Workcopy</h2>');
2517: $ENV{'form.unewformula'}=~s/\'/\"/g;
2518: $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
2519: $ENV{'form.unewformula'}.'<p>');
2520: &setfilename($asheet,$ENV{'form.ufn'});
2521: &tmpread($asheet,
2522: $ENV{'form.unewfield'},$ENV{'form.unewformula'});
2523:
2524: } elsif ($ENV{'form.saveas'}) {
2525: &setfilename($asheet,$ENV{'form.ufn'});
2526: &tmpread($asheet);
2527: } else {
2528: &readsheet($asheet,$ENV{'form.ufn'});
2529: }
2530: # Print out user information
2531: unless (&gettype($asheet) eq 'classcalc') {
2532: $r->print('<p><b>User:</b> '.&getuname($asheet).
2533: '<br><b>Domain:</b> '.&getudom($asheet));
2534: if (&getcsec($asheet) eq '-1') {
2535: $r->print('<h3><font color=red>'.
2536: 'Not a student in this course</font></h3>');
2537: } else {
2538: $r->print('<br><b>Section/Group:</b> '.&getcsec($asheet));
2539: }
2540: if ($ENV{'form.usymb'}) {
2541: $r->print('<br><b>Assessment:</b> <tt>'.
2542: $ENV{'form.usymb'}.'</tt>');
2543: }
2544: }
2545: # See if user can see this
2546: if ((&gettype($asheet) eq 'classcalc') ||
2547: (&getuname($asheet) ne $ENV{'user.name'}) ||
2548: (&getudom($asheet) ne $ENV{'user.domain'})) {
2549: unless (&Apache::lonnet::allowed('vgr',&getcid($asheet))) {
2550: $r->print('<h1>Access Permission Denied</h1>'.
2551: '</form></body></html>');
2552: return OK;
2553: }
2554: }
2555: # Additional options
2556: $r->print(
2557: '<input type=submit name=forcerecalc value="Completely Recalculate Sheet"><p>'
2558: );
2559: if (&gettype($asheet) eq 'assesscalc') {
2560: $r->print ('<p><font size=+2><a href="/adm/studentcalc?uname='.
2561: &getuname($asheet).'&udom='.&getudom($asheet).'">'.
2562: 'Level up: Student Sheet</a></font><p>');
2563: }
2564: if ((&gettype($asheet) eq 'studentcalc') &&
2565: (&Apache::lonnet::allowed('vgr',&getcid($asheet)))) {
2566: $r->print (
2567: '<p><font size=+2><a href="/adm/classcalc">'.
2568: 'Level up: Course Sheet</a></font><p>');
2569: }
2570: # Save dialog
2571: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
2572: my $fname=$ENV{'form.ufn'};
2573: $fname=~s/\_[^\_]+$//;
2574: if ($fname eq 'default') { $fname='course_default'; }
2575: $r->print
2576: ('<input type=submit name=saveas value="Save as ...">'.
2577: '<input type=text size=20 name=newfn value="'.$fname.'">'.
2578: '(make default: <input type=checkbox name="makedefufn">)<p>');
2579: }
2580: $r->print(&hiddenfield('ufn',&getfilename($asheet)));
2581: # Load dialog
2582: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
2583: $r->print('<p><input type=submit name=load value="Load ...">'.
2584: '<select name="loadthissheet">'.
2585: '<option name="default">Default</option>');
2586: foreach (&othersheets($asheet,&gettype($asheet))) {
2587: $r->print('<option name="'.$_.'"');
2588: if ($ENV{'form.ufn'} eq $_) {
2589: $r->print(' selected');
2590: }
2591: $r->print('>'.$_.'</option>');
2592: }
2593: $r->print('</select><p>');
2594: if (&gettype($asheet) eq 'studentcalc') {
2595: &setothersheets($asheet,&othersheets($asheet,'assesscalc'));
2596: }
2597: }
2598: # Cached sheets
2599: &expirationdates();
2600: undef %oldsheets;
2601: undef %loadedcaches;
2602: if (&gettype($asheet) eq 'classcalc') {
2603: $r->print
2604: ("Loading previously calculated student sheets ...<br>\n");
2605: $r->rflush();
2606: &cachedcsheets();
2607: } elsif (&gettype($asheet) eq 'studentcalc') {
2608: $r->print
2609: ("Loading previously calculated assessment sheets ...<br>\n");
2610: $r->rflush();
2611: &cachedssheets(&getuname($asheet),&getudom($asheet),
2612: &getuhome($asheet));
2613: }
2614: # Update sheet, load rows
2615: $r->print("Loaded sheet(s), updating rows ...<br>\n");
2616: $r->rflush();
2617: #
2618: &updatesheet($asheet);
2619: $r->print("Updated rows, loading row data ...<br>\n");
2620: $r->rflush();
2621: #
2622: &loadrows($asheet,$r);
2623: $r->print("Loaded row data, calculating sheet ...<br>\n");
2624: $r->rflush();
2625: #
2626: my $calcoutput=&calcsheet($asheet);
2627: $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
2628: # See if something to save
2629: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
2630: my $fname='';
2631: if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
2632: $fname=~s/\W/\_/g;
2633: if ($fname eq 'default') { $fname='course_default'; }
2634: $fname.='_'.&gettype($asheet);
2635: &setfilename($asheet,$fname);
2636: $ENV{'form.ufn'}=$fname;
2637: $r->print('<p>Saving spreadsheet: '.
2638: &writesheet($asheet,$ENV{'form.makedefufn'}).'<p>');
2639: }
2640: }
2641: #Write the modified worksheet
2642:
2643: $r->print('<b>Current sheet:</b> '.&getfilename($asheet).'<p>');
2644:
2645: &tmpwrite($asheet);
2646:
2647: if (&gettype($asheet) eq 'studentcalc') {
2648: $r->print('<br>Show rows with empty A column: ');
2649: } else {
2650: $r->print('<br>Show empty rows: ');
2651: }
2652:
2653: $r->print(&hiddenfield('userselhidden','true').
2654: '<input type=checkbox name=showall onClick="submit()"');
2655:
2656: if ($ENV{'form.showall'}) {
2657: $r->print(' checked');
2658: } else {
2659: unless ($ENV{'form.userselhidden'}) {
2660: unless
2661: ($ENV{'course.'.$ENV{'request.course.id'}.'.hideemptyrows'} eq 'yes') {
2662: $r->print(' checked');
2663: $ENV{'form.showall'}=1;
2664: }
2665: }
2666: }
2667: $r->print('>');
2668:
2669: if (&gettype($asheet) eq 'classcalc') {
2670: $r->print(
2671: ' Output CSV format: <input type=checkbox name=showcsv onClick="submit()"');
2672: if ($ENV{'form.showcsv'}) { $r->print(' checked'); }
2673: $r->print('>');
2674: }
2675:
2676: # ------------------------------------------------------------------ Insertrows
2677: $r->print(' Student Status: '.
2678: &Apache::lonhtmlcommon::StatusOptions
2679: ($ENV{'form.Status'},'sheet'));
2680:
2681: $r->print(<<ENDINSERTBUTTONS);
2682: <br>
2683: <input type='button' onClick='insertrow("top");'
2684: value='Insert Row Top'>
2685: <input type='button' onClick='insertrow("bottom");'
2686: value='Insert Row Bottom'><br>
2687: ENDINSERTBUTTONS
2688:
2689: # ------------------------------------------------------------- Print out sheet
2690:
2691: &outsheet($r,$asheet);
2692: $r->print('</form></body></html>');
2693:
2694: # ------------------------------------------------------------------------ Done
2695: } else {
2696: # ----------------------------- Not in a course, or not allowed to modify parms
2697: $ENV{'user.error.msg'}=
2698: $r->uri.":opa:0:0:Cannot modify spreadsheet";
2699: return HTTP_NOT_ACCEPTABLE;
2700: }
2701: return OK;
2702:
2703: }
2704:
2705: 1;
2706: __END__
2707:
2708:
2709:
2710:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>