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