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