File:
[LON-CAPA] /
loncom /
interface /
Attic /
lonspreadsheet.pm
Revision
1.142:
download - view:
text,
annotated -
select for diffs
Tue Nov 19 19:20:50 2002 UTC (21 years, 7 months ago) by
matthew
Branches:
MAIN
CVS tags:
HEAD
Fixes Bug 426 by implementing sorting the the student and course
spreadsheet views. Students are sorted alphabetically by full name
(lastname generation, firstname middlename).
Resources are sorted by containing sequence or symb as required.
1: #
2: # $Id: lonspreadsheet.pm,v 1.142 2002/11/19 19:20:50 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 Apache::Constants qw(:common :http);
57: use Apache::lonnet;
58: use Apache::lonhtmlcommon;
59: use Apache::loncoursedata;
60: use Apache::File();
61: use Safe;
62: use Safe::Hole;
63: use Opcode;
64: use GDBM_File;
65: use HTML::TokeParser;
66: use Spreadsheet::WriteExcel;
67:
68: #
69: # Caches for coursewide information
70: #
71: my %Section;
72:
73: #
74: # Caches for previously calculated spreadsheets
75: #
76:
77: my %oldsheets;
78: my %loadedcaches;
79: my %expiredates;
80:
81: #
82: # Cache for stores of an individual user
83: #
84:
85: my $cachedassess;
86: my %cachedstores;
87:
88: #
89: # These cache hashes need to be independent of user, resource and course
90: # (user and course can/should be in the keys)
91: #
92:
93: my %spreadsheets;
94: my %courserdatas;
95: my %userrdatas;
96: my %defaultsheets;
97: my %rowlabel_cache;
98:
99: #
100: # These global hashes are dependent on user, course and resource,
101: # and need to be initialized every time when a sheet is calculated
102: #
103: my %courseopt;
104: my %useropt;
105: my %parmhash;
106:
107: #
108: # Some hashes for stats on timing and performance
109: #
110:
111: my %starttimes;
112: my %usedtimes;
113: my %numbertimes;
114:
115: # Stuff that only the screen handler can know
116:
117: my $includedir;
118: my $tmpdir;
119:
120: # =============================================================================
121: # ===================================== Implements an instance of a spreadsheet
122:
123: ##
124: ## mask - used to reside in the safe space.
125: ##
126: sub mask {
127: my ($lower,$upper)=@_;
128: $upper = $lower if (! defined($upper));
129: #
130: my ($la,$ld) = ($lower=~/([A-Za-z]|\*)(\d+|\*)/);
131: my ($ua,$ud) = ($upper=~/([A-Za-z]|\*)(\d+|\*)/);
132: #
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[-1]!=$uda[-1]) {
192: $num.='['.$lda[-1].'-'.$uda[-1].']';
193: }
194: }
195: }
196: }
197: return '^'.$alpha.$num."\$";
198: }
199:
200: sub initsheet {
201: my $safeeval = new Safe(shift);
202: my $safehole = new Safe::Hole;
203: $safeeval->permit("entereval");
204: $safeeval->permit(":base_math");
205: $safeeval->permit("sort");
206: $safeeval->deny(":base_io");
207: $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
208: $safehole->wrap(\&Apache::lonspreadsheet::mask,$safeeval,'&mask');
209: $safeeval->share('$@');
210: my $code=<<'ENDDEFS';
211: # ---------------------------------------------------- Inside of the safe space
212:
213: #
214: # f: formulas
215: # t: intermediate format (variable references expanded)
216: # v: output values
217: # c: preloaded constants (A-column)
218: # rl: row label
219: # os: other spreadsheets (for student spreadsheet only)
220:
221: undef %sheet_values; # Holds the (computed, final) values for the sheet
222: # This is only written to by &calc, the spreadsheet computation routine.
223: # It is read by many functions
224: undef %t; # Holds the values of the spreadsheet temporarily. Set in &sett,
225: # which does the translation of strings like C5 into the value in C5.
226: # Used in &calc - %t holds the values that are actually eval'd.
227: undef %f; # Holds the formulas for each cell. This is the users
228: # (spreadsheet authors) data for each cell.
229: # set by &setformulas and returned by &getformulas
230: # &setformulas is called by &readsheet, &tmpread, &updateclasssheet,
231: # &updatestudentassesssheet, &loadstudent, &loadcourse
232: # &getformulas is called by &writesheet, &tmpwrite, &updateclasssheet,
233: # &updatestudentassesssheet, &loadstudent, &loadcourse, &loadassessment,
234: undef %c; # Holds the constants for a sheet. In the assessment
235: # sheets, this is the A column. Used in &MINPARM, &MAXPARM, &expandnamed,
236: # &sett, and &setconstants. There is no &getconstants.
237: # &setconstants is called by &loadstudent, &loadcourse, &load assessment,
238: undef @os; # Holds the names of other spreadsheets - this is used to specify
239: # the spreadsheets that are available for the assessment sheet.
240: # Set by &setothersheets. &setothersheets is called by &handler. A
241: # related subroutine is &othersheets.
242: #$errorlog = '';
243:
244: $maxrow = 0;
245: $sheettype = '';
246:
247: # filename/reference of the sheet
248: $filename = '';
249:
250: # user data
251: $uname = '';
252: $uhome = '';
253: $udom = '';
254:
255: # course data
256:
257: $csec = '';
258: $chome= '';
259: $cnum = '';
260: $cdom = '';
261: $cid = '';
262: $coursefilename = '';
263:
264: # symb
265:
266: $usymb = '';
267:
268: # error messages
269: $errormsg = '';
270:
271:
272: #-------------------------------------------------------
273:
274: =item UWCALC(hashname,modules,units,date)
275:
276: returns the proportion of the module
277: weights not previously completed by the student.
278:
279: =over 4
280:
281: =item hashname
282:
283: name of the hash the module dates have been inserted into
284:
285: =item modules
286:
287: reference to a cell which contains a comma deliminated list of modules
288: covered by the assignment.
289:
290: =item units
291:
292: reference to a cell which contains a comma deliminated list of module
293: weights with respect to the assignment
294:
295: =item date
296:
297: reference to a cell which contains the date the assignment was completed.
298:
299: =back
300:
301: =cut
302:
303: #-------------------------------------------------------
304: sub UWCALC {
305: my ($hashname,$modules,$units,$date) = @_;
306: my @Modules = split(/,/,$modules);
307: my @Units = split(/,/,$units);
308: my $total_weight;
309: foreach (@Units) {
310: $total_weight += $_;
311: }
312: my $usum=0;
313: for (my $i=0; $i<=$#Modules; $i++) {
314: if (&HASH($hashname,$Modules[$i]) eq $date) {
315: $usum += $Units[$i];
316: }
317: }
318: return $usum/$total_weight;
319: }
320:
321: #-------------------------------------------------------
322:
323: =item CDLSUM(list)
324:
325: returns the sum of the elements in a cell which contains
326: a Comma Deliminate List of numerical values.
327: 'list' is a reference to a cell which contains a comma deliminated list.
328:
329: =cut
330:
331: #-------------------------------------------------------
332: sub CDLSUM {
333: my ($list)=@_;
334: my $sum;
335: foreach (split/,/,$list) {
336: $sum += $_;
337: }
338: return $sum;
339: }
340:
341: #-------------------------------------------------------
342:
343: =item CDLITEM(list,index)
344:
345: returns the item at 'index' in a Comma Deliminated List.
346:
347: =over 4
348:
349: =item list
350:
351: reference to a cell which contains a comma deliminated list.
352:
353: =item index
354:
355: the Perl index of the item requested (first element in list has
356: an index of 0)
357:
358: =back
359:
360: =cut
361:
362: #-------------------------------------------------------
363: sub CDLITEM {
364: my ($list,$index)=@_;
365: my @Temp = split/,/,$list;
366: return $Temp[$index];
367: }
368:
369: #-------------------------------------------------------
370:
371: =item CDLHASH(name,key,value)
372:
373: loads a comma deliminated list of keys into
374: the hash 'name', all with a value of 'value'.
375:
376: =over 4
377:
378: =item name
379:
380: name of the hash.
381:
382: =item key
383:
384: (a pointer to) a comma deliminated list of keys.
385:
386: =item value
387:
388: a single value to be entered for each key.
389:
390: =back
391:
392: =cut
393:
394: #-------------------------------------------------------
395: sub CDLHASH {
396: my ($name,$key,$value)=@_;
397: my @Keys;
398: my @Values;
399: # Check to see if we have multiple $key values
400: if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
401: my $keymask = &mask($key);
402: # Assume the keys are addresses
403: my @Temp = grep /$keymask/,keys(%sheet_values);
404: @Keys = $sheet_values{@Temp};
405: } else {
406: $Keys[0]= $key;
407: }
408: my @Temp;
409: foreach $key (@Keys) {
410: @Temp = (@Temp, split/,/,$key);
411: }
412: @Keys = @Temp;
413: if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
414: my $valmask = &mask($value);
415: my @Temp = grep /$valmask/,keys(%sheet_values);
416: @Values =$sheet_values{@Temp};
417: } else {
418: $Values[0]= $value;
419: }
420: $value = $Values[0];
421: # Add values to hash
422: for (my $i = 0; $i<=$#Keys; $i++) {
423: my $key = $Keys[$i];
424: if (! exists ($hashes{$name}->{$key})) {
425: $hashes{$name}->{$key}->[0]=$value;
426: } else {
427: my @Temp = sort(@{$hashes{$name}->{$key}},$value);
428: $hashes{$name}->{$key} = \@Temp;
429: }
430: }
431: return "hash '$name' updated";
432: }
433:
434: #-------------------------------------------------------
435:
436: =item GETHASH(name,key,index)
437:
438: returns the element in hash 'name'
439: reference by the key 'key', at index 'index' in the values list.
440:
441: =cut
442:
443: #-------------------------------------------------------
444: sub GETHASH {
445: my ($name,$key,$index)=@_;
446: if (! defined($index)) {
447: $index = 0;
448: }
449: if ($key =~ /^[A-z]\d+$/) {
450: $key = $sheet_values{$key};
451: }
452: return $hashes{$name}->{$key}->[$index];
453: }
454:
455: #-------------------------------------------------------
456:
457: =item CLEARHASH(name)
458:
459: clears all the values from the hash 'name'
460:
461: =item CLEARHASH(name,key)
462:
463: clears all the values from the hash 'name' associated with the given key.
464:
465: =cut
466:
467: #-------------------------------------------------------
468: sub CLEARHASH {
469: my ($name,$key)=@_;
470: if (defined($key)) {
471: if (exists($hashes{$name}->{$key})) {
472: $hashes{$name}->{$key}=undef;
473: return "hash '$name' key '$key' cleared";
474: }
475: } else {
476: if (exists($hashes{$name})) {
477: $hashes{$name}=undef;
478: return "hash '$name' cleared";
479: }
480: }
481: return "Error in clearing hash";
482: }
483:
484: #-------------------------------------------------------
485:
486: =item HASH(name,key,value)
487:
488: loads values into an internal hash. If a key
489: already has a value associated with it, the values are sorted numerically.
490:
491: =item HASH(name,key)
492:
493: returns the 0th value in the hash 'name' associated with 'key'.
494:
495: =cut
496:
497: #-------------------------------------------------------
498: sub HASH {
499: my ($name,$key,$value)=@_;
500: my @Keys;
501: undef @Keys;
502: my @Values;
503: # Check to see if we have multiple $key values
504: if ($key =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
505: my $keymask = &mask($key);
506: # Assume the keys are addresses
507: my @Temp = grep /$keymask/,keys(%sheet_values);
508: @Keys = $sheet_values{@Temp};
509: } else {
510: $Keys[0]= $key;
511: }
512: # If $value is empty, return the first value associated
513: # with the first key.
514: if (! $value) {
515: return $hashes{$name}->{$Keys[0]}->[0];
516: }
517: # Check to see if we have multiple $value(s)
518: if ($value =~ /[A-z](\-[A-z])?\d+(\-\d+)?/) {
519: my $valmask = &mask($value);
520: my @Temp = grep /$valmask/,keys(%sheet_values);
521: @Values =$sheet_values{@Temp};
522: } else {
523: $Values[0]= $value;
524: }
525: # Add values to hash
526: for (my $i = 0; $i<=$#Keys; $i++) {
527: my $key = $Keys[$i];
528: my $value = ($i<=$#Values ? $Values[$i] : $Values[0]);
529: if (! exists ($hashes{$name}->{$key})) {
530: $hashes{$name}->{$key}->[0]=$value;
531: } else {
532: my @Temp = sort(@{$hashes{$name}->{$key}},$value);
533: $hashes{$name}->{$key} = \@Temp;
534: }
535: }
536: return $Values[-1];
537: }
538:
539: #-------------------------------------------------------
540:
541: =item NUM(range)
542:
543: returns the number of items in the range.
544:
545: =cut
546:
547: #-------------------------------------------------------
548: sub NUM {
549: my $mask=mask(@_);
550: my $num= $#{@{grep(/$mask/,keys(%sheet_values))}}+1;
551: return $num;
552: }
553:
554: sub BIN {
555: my ($low,$high,$lower,$upper)=@_;
556: my $mask=mask($lower,$upper);
557: my $num=0;
558: foreach (grep /$mask/,keys(%sheet_values)) {
559: if (($sheet_values{$_}>=$low) && ($sheet_values{$_}<=$high)) {
560: $num++;
561: }
562: }
563: return $num;
564: }
565:
566:
567: #-------------------------------------------------------
568:
569: =item SUM(range)
570:
571: returns the sum of items in the range.
572:
573: =cut
574:
575: #-------------------------------------------------------
576: sub SUM {
577: my $mask=mask(@_);
578: my $sum=0;
579: foreach (grep /$mask/,keys(%sheet_values)) {
580: $sum+=$sheet_values{$_};
581: }
582: return $sum;
583: }
584:
585: #-------------------------------------------------------
586:
587: =item MEAN(range)
588:
589: compute the average of the items in the range.
590:
591: =cut
592:
593: #-------------------------------------------------------
594: sub MEAN {
595: my $mask=mask(@_);
596: my $sum=0;
597: my $num=0;
598: foreach (grep /$mask/,keys(%sheet_values)) {
599: $sum+=$sheet_values{$_};
600: $num++;
601: }
602: if ($num) {
603: return $sum/$num;
604: } else {
605: return undef;
606: }
607: }
608:
609: #-------------------------------------------------------
610:
611: =item STDDEV(range)
612:
613: compute the standard deviation of the items in the range.
614:
615: =cut
616:
617: #-------------------------------------------------------
618: sub STDDEV {
619: my $mask=mask(@_);
620: my $sum=0; my $num=0;
621: foreach (grep /$mask/,keys(%sheet_values)) {
622: $sum+=$sheet_values{$_};
623: $num++;
624: }
625: unless ($num>1) { return undef; }
626: my $mean=$sum/$num;
627: $sum=0;
628: foreach (grep /$mask/,keys(%sheet_values)) {
629: $sum+=($sheet_values{$_}-$mean)**2;
630: }
631: return sqrt($sum/($num-1));
632: }
633:
634: #-------------------------------------------------------
635:
636: =item PROD(range)
637:
638: compute the product of the items in the range.
639:
640: =cut
641:
642: #-------------------------------------------------------
643: sub PROD {
644: my $mask=mask(@_);
645: my $prod=1;
646: foreach (grep /$mask/,keys(%sheet_values)) {
647: $prod*=$sheet_values{$_};
648: }
649: return $prod;
650: }
651:
652: #-------------------------------------------------------
653:
654: =item MAX(range)
655:
656: compute the maximum of the items in the range.
657:
658: =cut
659:
660: #-------------------------------------------------------
661: sub MAX {
662: my $mask=mask(@_);
663: my $max='-';
664: foreach (grep /$mask/,keys(%sheet_values)) {
665: unless ($max) { $max=$sheet_values{$_}; }
666: if (($sheet_values{$_}>$max) || ($max eq '-')) { $max=$sheet_values{$_}; }
667: }
668: return $max;
669: }
670:
671: #-------------------------------------------------------
672:
673: =item MIN(range)
674:
675: compute the minimum of the items in the range.
676:
677: =cut
678:
679: #-------------------------------------------------------
680: sub MIN {
681: my $mask=mask(@_);
682: my $min='-';
683: foreach (grep /$mask/,keys(%sheet_values)) {
684: unless ($max) { $max=$sheet_values{$_}; }
685: if (($sheet_values{$_}<$min) || ($min eq '-')) {
686: $min=$sheet_values{$_};
687: }
688: }
689: return $min;
690: }
691:
692: #-------------------------------------------------------
693:
694: =item SUMMAX(num,lower,upper)
695:
696: compute the sum of the largest 'num' items in the range from
697: 'lower' to 'upper'
698:
699: =cut
700:
701: #-------------------------------------------------------
702: sub SUMMAX {
703: my ($num,$lower,$upper)=@_;
704: my $mask=mask($lower,$upper);
705: my @inside=();
706: foreach (grep /$mask/,keys(%sheet_values)) {
707: push (@inside,$sheet_values{$_});
708: }
709: @inside=sort(@inside);
710: my $sum=0; my $i;
711: for ($i=$#inside;(($i>$#inside-$num) && ($i>=0));$i--) {
712: $sum+=$inside[$i];
713: }
714: return $sum;
715: }
716:
717: #-------------------------------------------------------
718:
719: =item SUMMIN(num,lower,upper)
720:
721: compute the sum of the smallest 'num' items in the range from
722: 'lower' to 'upper'
723:
724: =cut
725:
726: #-------------------------------------------------------
727: sub SUMMIN {
728: my ($num,$lower,$upper)=@_;
729: my $mask=mask($lower,$upper);
730: my @inside=();
731: foreach (grep /$mask/,keys(%sheet_values)) {
732: $inside[$#inside+1]=$sheet_values{$_};
733: }
734: @inside=sort(@inside);
735: my $sum=0; my $i;
736: for ($i=0;(($i<$num) && ($i<=$#inside));$i++) {
737: $sum+=$inside[$i];
738: }
739: return $sum;
740: }
741:
742: #-------------------------------------------------------
743:
744: =item MINPARM(parametername)
745:
746: Returns the minimum value of the parameters matching the parametername.
747: parametername should be a string such as 'duedate'.
748:
749: =cut
750:
751: #-------------------------------------------------------
752: sub MINPARM {
753: my ($expression) = @_;
754: my $min = undef;
755: study($expression);
756: foreach $parameter (keys(%c)) {
757: next if ($parameter !~ /$expression/);
758: if ((! defined($min)) || ($min > $c{$parameter})) {
759: $min = $c{$parameter}
760: }
761: }
762: return $min;
763: }
764:
765: #-------------------------------------------------------
766:
767: =item MAXPARM(parametername)
768:
769: Returns the maximum value of the parameters matching the input parameter name.
770: parametername should be a string such as 'duedate'.
771:
772: =cut
773:
774: #-------------------------------------------------------
775: sub MAXPARM {
776: my ($expression) = @_;
777: my $max = undef;
778: study($expression);
779: foreach $parameter (keys(%c)) {
780: next if ($parameter !~ /$expression/);
781: if ((! defined($min)) || ($max < $c{$parameter})) {
782: $max = $c{$parameter}
783: }
784: }
785: return $max;
786: }
787:
788: #--------------------------------------------------------
789: sub expandnamed {
790: my $expression=shift;
791: if ($expression=~/^\&/) {
792: my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/);
793: my @vars=split(/\W+/,$formula);
794: my %values=();
795: undef %values;
796: foreach ( @vars ) {
797: my $varname=$_;
798: if ($varname=~/\D/) {
799: $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
800: $varname=~s/$var/\(\\w\+\)/g;
801: foreach (keys(%c)) {
802: if ($_=~/$varname/) {
803: $values{$1}=1;
804: }
805: }
806: }
807: }
808: if ($func eq 'EXPANDSUM') {
809: my $result='';
810: foreach (keys(%values)) {
811: my $thissum=$formula;
812: $thissum=~s/$var/$_/g;
813: $result.=$thissum.'+';
814: }
815: $result=~s/\+$//;
816: return $result;
817: } else {
818: return 0;
819: }
820: } else {
821: # it is not a function, so it is a parameter name
822: # We should do the following:
823: # 1. Take the list of parameter names
824: # 2. look through the list for ones that match the parameter we want
825: # 3. If there are no collisions, return the one that matches
826: # 4. If there is a collision, return 'bad parameter name error'
827: my $returnvalue = '';
828: my @matches = ();
829: $#matches = -1;
830: study $expression;
831: foreach $parameter (keys(%c)) {
832: push @matches,$parameter if ($parameter =~ /$expression/);
833: }
834: if (scalar(@matches) == 0) {
835: $returnvalue = 'unmatched parameter: '.$parameter;
836: } elsif (scalar(@matches) == 1) {
837: $returnvalue = '$c{\''.$matches[0].'\'}';
838: } elsif (scalar(@matches) > 0) {
839: # more than one match. Look for a concise one
840: $returnvalue = "'non-unique parameter name : $expression'";
841: foreach (@matches) {
842: if (/^$expression$/) {
843: $returnvalue = '$c{\''.$_.'\'}';
844: }
845: }
846: } else {
847: # There was a negative number of matches, which indicates
848: # something is wrong with reality. Better warn the user.
849: $returnvalue = 'bizzare parameter: '.$parameter;
850: }
851: return $returnvalue;
852: }
853: }
854:
855: sub sett {
856: %t=();
857: my $pattern='';
858: if ($sheettype eq 'assesscalc') {
859: $pattern='A';
860: } else {
861: $pattern='[A-Z]';
862: }
863: # Deal with the template row
864: foreach (keys(%f)) {
865: next if ($_!~/template\_(\w)/);
866: my $col=$1;
867: next if ($col=~/^$pattern/);
868: foreach (keys(%f)) {
869: next if ($_!~/A(\d+)/);
870: my $trow=$1;
871: next if (! $trow);
872: # Get the name of this cell
873: my $lb=$col.$trow;
874: # Grab the template declaration
875: $t{$lb}=$f{'template_'.$col};
876: # Replace '#' with the row number
877: $t{$lb}=~s/\#/$trow/g;
878: # Replace '....' with ','
879: $t{$lb}=~s/\.\.+/\,/g;
880: # Replace 'A0' with the value from 'A0'
881: $t{$lb}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
882: # Replace parameters
883: $t{$lb}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
884: }
885: }
886: # Deal with the normal cells
887: foreach (keys(%f)) {
888: if (exists($f{$_}) && ($_!~/template\_/)) {
889: my $matches=($_=~/^$pattern(\d+)/);
890: if (($matches) && ($1)) {
891: unless ($f{$_}=~/^\!/) {
892: $t{$_}=$c{$_};
893: }
894: } else {
895: $t{$_}=$f{$_};
896: $t{$_}=~s/\.\.+/\,/g;
897: $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
898: $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
899: }
900: }
901: }
902: # For inserted lines, [B-Z] is also valid
903: unless ($sheettype eq 'assesscalc') {
904: foreach (keys(%f)) {
905: if ($_=~/[B-Z](\d+)/) {
906: if ($f{'A'.$1}=~/^[\~\-]/) {
907: $t{$_}=$f{$_};
908: $t{$_}=~s/\.\.+/\,/g;
909: $t{$_}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
910: $t{$_}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
911: }
912: }
913: }
914: }
915: # For some reason 'A0' gets special treatment... This seems superfluous
916: # but I imagine it is here for a reason.
917: $t{'A0'}=$f{'A0'};
918: $t{'A0'}=~s/\.\.+/\,/g;
919: $t{'A0'}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
920: $t{'A0'}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.&expandnamed($2)/ge;
921: }
922:
923: sub calc {
924: undef %sheet_values;
925: &sett();
926: my $notfinished=1;
927: my $lastcalc='';
928: my $depth=0;
929: while ($notfinished) {
930: $notfinished=0;
931: foreach (keys(%t)) {
932: #$errorlog .= "$_:".$t{$_};
933: my $old=$sheet_values{$_};
934: $sheet_values{$_}=eval $t{$_};
935: if ($@) {
936: undef %sheet_values;
937: return $_.': '.$@;
938: }
939: if ($sheet_values{$_} ne $old) { $notfinished=1; $lastcalc=$_; }
940: #$errorlog .= ":".$sheet_values{$_}."\n";
941: }
942: $depth++;
943: if ($depth>100) {
944: undef %sheet_values;
945: return $lastcalc.': Maximum calculation depth exceeded';
946: }
947: }
948: return '';
949: }
950:
951: # ------------------------------------------- End of "Inside of the safe space"
952: ENDDEFS
953: $safeeval->reval($code);
954: return $safeeval;
955: }
956:
957: #
958: #
959: #
960: sub templaterow {
961: my $sheet = shift;
962: my @cols=();
963: my $rowlabel = 'Template';
964: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
965: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
966: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
967: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
968: my $fm=$sheet->{'f'}->{'template_'.$_};
969: $fm=~s/[\'\"]/\&\#34;/g;
970: push(@cols,{ name => 'template_'.$_,
971: formula => $fm,
972: value => $fm });
973: }
974: return ($rowlabel,@cols);
975: }
976:
977: sub outrowassess {
978: # $n is the current row number
979: my ($sheet,$n) = @_;
980: my @cols=();
981: my $rowlabel='';
982: if ($n) {
983: my ($usy,$ufn)=split(/__&&&\__/,$sheet->{'f'}->{'A'.$n});
984: if (exists($sheet->{'rowlabel'}->{$usy})) {
985: $rowlabel = $sheet->{'rowlabel'}->{$usy};
986: } else {
987: $rowlabel = '';
988: }
989: } else {
990: $rowlabel = 'Export';
991: }
992: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
993: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
994: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
995: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
996: my $fm=$sheet->{'f'}->{$_.$n};
997: $fm=~s/[\'\"]/\&\#34;/g;
998: push(@cols,{ name => $_.$n,
999: formula => $fm,
1000: value => $sheet->{'values'}->{$_.$n}});
1001: }
1002: return ($rowlabel,@cols);
1003: }
1004:
1005: sub outrow {
1006: my ($sheet,$n)=@_;
1007: my @cols=();
1008: my $rowlabel;
1009: if ($n) {
1010: $rowlabel = $sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$n}};
1011: } else {
1012: if ($sheet->{'sheettype'} eq 'classcalc') {
1013: $rowlabel = 'Summary';
1014: } else {
1015: $rowlabel = 'Export';
1016: }
1017: }
1018: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1019: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
1020: 'a','b','c','d','e','f','g','h','i','j','k','l','m',
1021: 'n','o','p','q','r','s','t','u','v','w','x','y','z') {
1022: my $fm=$sheet->{'f'}->{$_.$n};
1023: $fm=~s/[\'\"]/\&\#34;/g;
1024: push(@cols,{ name => $_.$n,
1025: formula => $fm,
1026: value => $sheet->{'values'}->{$_.$n}});
1027: }
1028: return ($rowlabel,@cols);
1029: }
1030:
1031: # ------------------------------------------------ Add or change formula values
1032: sub setformulas {
1033: my ($sheet)=shift;
1034: %{$sheet->{'safe'}->varglob('f')}=%{$sheet->{'f'}};
1035: }
1036:
1037: # ------------------------------------------------ Add or change formula values
1038: sub setconstants {
1039: my ($sheet)=shift;
1040: my ($constants) = @_;
1041: if (! ref($constants)) {
1042: my %tmp = @_;
1043: $constants = \%tmp;
1044: }
1045: $sheet->{'constants'} = $constants;
1046: return %{$sheet->{'safe'}->varglob('c')}=%{$sheet->{'constants'}};
1047: }
1048:
1049: # --------------------------------------------- Set names of other spreadsheets
1050: sub setothersheets {
1051: my $sheet = shift;
1052: my @othersheets = @_;
1053: $sheet->{'othersheets'} = \@othersheets;
1054: @{$sheet->{'safe'}->varglob('os')}=@othersheets;
1055: return;
1056: }
1057:
1058: # ------------------------------------------------ Add or change formula values
1059: sub setrowlabels {
1060: my $sheet=shift;
1061: my ($rowlabel) = @_;
1062: if (! ref($rowlabel)) {
1063: my %tmp = @_;
1064: $rowlabel = \%tmp;
1065: }
1066: $sheet->{'rowlabel'}=$rowlabel;
1067: }
1068:
1069: # ------------------------------------------------------- Calculate spreadsheet
1070: sub calcsheet {
1071: my $sheet=shift;
1072: my $result = $sheet->{'safe'}->reval('&calc();');
1073: %{$sheet->{'values'}} = %{$sheet->{'safe'}->varglob('sheet_values')};
1074: return $result;
1075: }
1076:
1077: # ---------------------------------------------------------------- Get formulas
1078: # Return a copy of the formulas
1079: sub getformulas {
1080: my $sheet = shift;
1081: return %{$sheet->{'safe'}->varglob('f')};
1082: }
1083:
1084: sub geterrorlog {
1085: my $sheet = shift;
1086: return ${$sheet->{'safe'}->varglob('errorlog')};
1087: }
1088:
1089: sub gettitle {
1090: my $sheet = shift;
1091: if ($sheet->{'sheettype'} eq 'classcalc') {
1092: return $sheet->{'coursedesc'};
1093: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1094: return 'Grades for '.$sheet->{'uname'}.'@'.$sheet->{'udom'};
1095: } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
1096: if (($sheet->{'usymb'} eq '_feedback') ||
1097: ($sheet->{'usymb'} eq '_evaluation') ||
1098: ($sheet->{'usymb'} eq '_discussion') ||
1099: ($sheet->{'usymb'} eq '_tutoring')) {
1100: my $title = $sheet->{'usymb'};
1101: $title =~ s/^_//;
1102: $title = ucfirst($title);
1103: return $title;
1104: }
1105: return if (! defined($sheet->{'mapid'}) ||
1106: $sheet->{'mapid'} !~ /^\d+$/);
1107: my $mapid = $sheet->{'mapid'};
1108: return if (! defined($sheet->{'resid'}) ||
1109: $sheet->{'resid'} !~ /^\d+$/);
1110: my $resid = $sheet->{'resid'};
1111: my %course_db;
1112: tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
1113: &GDBM_READER(),0640);
1114: return if (! tied(%course_db));
1115: my $key = 'title_'.$mapid.'.'.$resid;
1116: my $title = '';
1117: if (exists($course_db{$key})) {
1118: $title = $course_db{$key};
1119: } else {
1120: $title = $sheet->{'usymb'};
1121: }
1122: untie (%course_db);
1123: return $title;
1124: }
1125: }
1126:
1127: # ----------------------------------------------------- Get value of $f{'A'.$n}
1128: sub getfa {
1129: my $sheet = shift;
1130: my ($n)=@_;
1131: return $sheet->{'safe'}->reval('$f{"A'.$n.'"}');
1132: }
1133:
1134: # ------------------------------------------------------------- Export of A-row
1135: sub exportdata {
1136: my $sheet=shift;
1137: my @exportarray=();
1138: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
1139: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
1140: if (exists($sheet->{'values'}->{$_.'0'})) {
1141: push(@exportarray,$sheet->{'values'}->{$_.'0'});
1142: } else {
1143: push(@exportarray,'');
1144: }
1145: }
1146: return @exportarray;
1147: }
1148:
1149:
1150:
1151: sub update_student_sheet{
1152: my ($sheet,$c) = @_;
1153: # Load in the studentcalc sheet
1154: &readsheet($sheet,'default_studentcalc');
1155: # Determine the structure (contained assessments, etc) of the sheet
1156: &updatesheet($sheet);
1157: # Load in the cached sheets for this student
1158: &cachedssheets($sheet);
1159: # Load in the (possibly cached) data from the assessment sheets
1160: &loadstudent($sheet,$c);
1161: # Compute the sheet
1162: &calcsheet($sheet);
1163: }
1164:
1165: # ========================================================== End of Spreadsheet
1166: # =============================================================================
1167: #
1168: # Procedures for spreadsheet output
1169: #
1170: # --------------------------------------------- Produce output row n from sheet
1171:
1172: sub get_row {
1173: my ($sheet,$n) = @_;
1174: my ($rowlabel,@rowdata);
1175: if ($n eq '-') {
1176: ($rowlabel,@rowdata) = &templaterow($sheet);
1177: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1178: ($rowlabel,@rowdata) = &outrowassess($sheet,$n);
1179: } else {
1180: ($rowlabel,@rowdata) = &outrow($sheet,$n);
1181: }
1182: return ($rowlabel,@rowdata);
1183: }
1184:
1185: ########################################################################
1186: ########################################################################
1187: sub sort_indicies {
1188: my $sheet = shift;
1189: my @sortidx=();
1190: #
1191: if ($sheet->{'sheettype'} eq 'classcalc') {
1192: my @sortby=();
1193: # Skip row 0
1194: for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
1195: my (undef,$sname,$sdom,$fullname,$section,$id) =
1196: split(':',$sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$row}});
1197: push (@sortby, lc($fullname));
1198: push (@sortidx, $row);
1199: }
1200: @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1201: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1202: my @sortby=();
1203: # Skip row 0
1204: &Apache::lonnet::logthis('starting sort for studentcalc');
1205: for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
1206: my (undef,$symb,$uname,$udom,$mapid,$resid,$title) =
1207: split(':',$sheet->{'rowlabel'}->{$sheet->{'f'}->{'A'.$row}});
1208: $symb = &Apache::lonnet::unescape($symb);
1209: my ($sequence) = ($symb =~ /\/([^\/]*\.sequence)/);
1210: if ($sequence eq '') {
1211: $sequence = $symb;
1212: }
1213: push (@sortby, $sequence);
1214: push (@sortidx, $row);
1215: }
1216: @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1217: } else {
1218: my @sortby=();
1219: # Skip row 0
1220: for (my $row=1;$row<=$sheet->{'maxrow'};$row++) {
1221: push (@sortby, $sheet->{'safe'}->reval('$f{"A'.$row.'"}'));
1222: push (@sortidx, $row);
1223: }
1224: @sortidx = sort { $sortby[$a] cmp $sortby[$b]; } @sortidx;
1225: }
1226: return @sortidx;
1227: }
1228:
1229: #############################################################
1230: ### ###
1231: ### Spreadsheet Output Routines ###
1232: ### ###
1233: #############################################################
1234:
1235: ############################################
1236: ## HTML output routines ##
1237: ############################################
1238: sub html_editable_cell {
1239: my ($cell,$bgcolor) = @_;
1240: my $result;
1241: my ($name,$formula,$value);
1242: if (defined($cell)) {
1243: $name = $cell->{'name'};
1244: $formula = $cell->{'formula'};
1245: $value = $cell->{'value'};
1246: }
1247: $name = '' if (! defined($name));
1248: $formula = '' if (! defined($formula));
1249: if (! defined($value)) {
1250: $value = '<font color="'.$bgcolor.'">#</font>';
1251: if ($formula ne '') {
1252: $value = '<i>undefined value</i>';
1253: }
1254: }
1255: if ($value =~ /^\s*$/ ) {
1256: $value = '<font color="'.$bgcolor.'">#</font>';
1257: }
1258: $formula =~ s/\n/\\n/gs;
1259: $result .= '<a href="javascript:celledit(\''.
1260: $name.'\',\''.$formula.'\');">'.$value.'</a>';
1261: return $result;
1262: }
1263:
1264: sub html_uneditable_cell {
1265: my ($cell,$bgcolor) = @_;
1266: my $value = (defined($cell) ? $cell->{'value'} : '');
1267: return ' '.$value.' ';
1268: }
1269:
1270: sub outsheet_html {
1271: my ($sheet,$r) = @_;
1272: my ($num_uneditable,$realm,$row_type);
1273: if ($sheet->{'sheettype'} eq 'assesscalc') {
1274: $num_uneditable = 1;
1275: $realm = 'Assessment';
1276: $row_type = 'Item';
1277: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1278: $num_uneditable = 26;
1279: $realm = 'User';
1280: $row_type = 'Assessment';
1281: } elsif ($sheet->{'sheettype'} eq 'classcalc') {
1282: $num_uneditable = 26;
1283: $realm = 'Course';
1284: $row_type = 'Student';
1285: } else {
1286: return; # error
1287: }
1288: ####################################
1289: # Print out header table
1290: ####################################
1291: my $num_left = 52-$num_uneditable;
1292: my $tabledata =<<"END";
1293: <table border="2">
1294: <tr>
1295: <th colspan="1" rowspan="2"><font size="+2">$realm</font></th>
1296: <td bgcolor="#FFDDDD" colspan="$num_uneditable">
1297: <b><font size="+1">Import</font></b></td>
1298: <td colspan="$num_left">
1299: <b><font size="+1">Calculations</font></b></td>
1300: </tr><tr>
1301: END
1302: my $label_num = 0;
1303: foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
1304: if ($label_num<$num_uneditable) {
1305: $tabledata.='<td bgcolor="#FFDDDD">';
1306: } else {
1307: $tabledata.='<td>';
1308: }
1309: $tabledata.="<b><font size=+1>$_</font></b></td>";
1310: $label_num++;
1311: }
1312: $tabledata.="</tr>\n";
1313: $r->print($tabledata);
1314: ####################################
1315: # Print out template row
1316: ####################################
1317: my ($rowlabel,@rowdata) = &get_row($sheet,'-');
1318: my $row_html = '<tr><td>'.&format_html_rowlabel($rowlabel).'</td>';
1319: my $num_cols_output = 0;
1320: foreach my $cell (@rowdata) {
1321: if ($num_cols_output++ < $num_uneditable) {
1322: $row_html .= '<td bgcolor="#FFDDDD">';
1323: $row_html .= &html_uneditable_cell($cell,'#FFDDDD');
1324: } else {
1325: $row_html .= '<td bgcolor="#EOFFDD">';
1326: $row_html .= &html_editable_cell($cell,'#E0FFDD');
1327: }
1328: $row_html .= '</td>';
1329: }
1330: $row_html.= "</tr>\n";
1331: $r->print($row_html);
1332: ####################################
1333: # Print out summary/export row
1334: ####################################
1335: my ($rowlabel,@rowdata) = &get_row($sheet,'0');
1336: $row_html = '<tr><td>'.&format_html_rowlabel($rowlabel).'</td>';
1337: $num_cols_output = 0;
1338: foreach my $cell (@rowdata) {
1339: if ($num_cols_output++ < 26) {
1340: $row_html .= '<td bgcolor="#CCCCFF">';
1341: $row_html .= &html_editable_cell($cell,'#CCCCFF');
1342: } else {
1343: $row_html .= '<td bgcolor="#DDCCFF">';
1344: $row_html .= &html_uneditable_cell(undef,'#CCCCFF');
1345: }
1346: $row_html .= '</td>';
1347: }
1348: $row_html.= "</tr>\n";
1349: $r->print($row_html);
1350: $r->print('</table>');
1351: ####################################
1352: # Prepare to output rows
1353: ####################################
1354: my @Rows = &sort_indicies($sheet);
1355: #
1356: # Loop through the rows and output them one at a time
1357: my $rows_output=0;
1358: foreach my $rownum (@Rows) {
1359: my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
1360: next if ($rowlabel =~ /^\s*$/);
1361: next if (($sheet->{'sheettype'} eq 'assesscalc') &&
1362: (! $ENV{'form.showall'}) &&
1363: ($rowdata[0]->{'value'} =~ /^\s*$/));
1364: if ($sheet->{'sheettype'} =~ /^(studentcalc|classcalc)$/) {
1365: my $row_is_empty = 1;
1366: foreach my $cell (@rowdata) {
1367: if ($cell->{'value'} !~ /^\s*$/) {
1368: $row_is_empty = 0;
1369: last;
1370: }
1371: }
1372: next if $row_is_empty;
1373: }
1374: #
1375: my $defaultbg='#E0FF';
1376: #
1377: my $row_html ="\n".'<tr><td><b><font size=+1>'.$rownum.
1378: '</font></b></td>';
1379: #
1380: if ($sheet->{'sheettype'} eq 'classcalc') {
1381: $row_html.='<td>'.&format_html_rowlabel($rowlabel).'</td>';
1382: # Output links for each student?
1383: # Nope, that is already done for us in format_html_rowlabel (for now)
1384: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1385: $row_html.='<td>'.&format_html_rowlabel($rowlabel);
1386: $row_html.= '<br>'.
1387: '<select name="sel_'.$rownum.'" '.
1388: 'onChange="changesheet('.$rownum.')">'.
1389: '<option name="default">Default</option>';
1390: foreach (@{$sheet->{'othersheets'}}) {
1391: $row_html.='<option name="'.$_.'"';
1392: #if ($ufn eq $_) {
1393: # $row_html.=' selected';
1394: #}
1395: $row_html.='>'.$_.'</option>';
1396: }
1397: $row_html.='</select></td>';
1398: } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
1399: $row_html.='<td>'.&format_html_rowlabel($rowlabel).'</td>';
1400: }
1401: #
1402: my $shown_cells = 0;
1403: foreach my $cell (@rowdata) {
1404: my $value = $cell->{'value'};
1405: my $formula = $cell->{'formula'};
1406: my $cellname = $cell->{'name'};
1407: #
1408: my $bgcolor;
1409: if ($shown_cells && ($shown_cells/5 == int($shown_cells/5))) {
1410: $bgcolor = $defaultbg.'99';
1411: } else {
1412: $bgcolor = $defaultbg.'DD';
1413: }
1414: $bgcolor='#FFDDDD' if ($shown_cells < $num_uneditable);
1415: #
1416: $row_html.='<td bgcolor='.$bgcolor.'>';
1417: if ($shown_cells < $num_uneditable) {
1418: $row_html .= &html_uneditable_cell($cell,$bgcolor);
1419: } else {
1420: $row_html .= &html_editable_cell($cell,$bgcolor);
1421: }
1422: $row_html.='</td>';
1423: $shown_cells++;
1424: }
1425: if ($row_html) {
1426: if ($rows_output % 25 == 0) {
1427: $r->print("</table>\n<br>\n");
1428: $r->rflush();
1429: $r->print('<table border=2>'.
1430: '<tr><td> <td>'.$row_type.'</td>'.
1431: '<td>'.
1432: join('</td><td>',
1433: (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.
1434: 'abcdefghijklmnopqrstuvwxyz'))).
1435: "</td></tr>\n");
1436: }
1437: $rows_output++;
1438: $r->print($row_html);
1439: }
1440: }
1441: #
1442: $r->print('</table>');
1443: #
1444: # Debugging code (be sure to uncomment errorlog code in safe space):
1445: #
1446: # $r->print("\n<pre>");
1447: # $r->print(&geterrorlog($sheet));
1448: # $r->print("\n</pre>");
1449: return 1;
1450: }
1451:
1452: ############################################
1453: ## csv output routines ##
1454: ############################################
1455: sub outsheet_csv {
1456: my ($sheet,$r) = @_;
1457: my $csvdata = '';
1458: my @Values;
1459: ####################################
1460: # Prepare to output rows
1461: ####################################
1462: my @Rows = &sort_indicies($sheet);
1463: #
1464: # Loop through the rows and output them one at a time
1465: my $rows_output=0;
1466: foreach my $rownum (@Rows) {
1467: my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
1468: next if ($rowlabel =~ /^\s*$/);
1469: push (@Values,&format_csv_rowlabel($rowlabel));
1470: foreach my $cell (@rowdata) {
1471: push (@Values,'"'.$cell->{'value'}.'"');
1472: }
1473: $csvdata.= join(',',@Values)."\n";
1474: @Values = ();
1475: }
1476: #
1477: # Write the CSV data to a file and serve up a link
1478: #
1479: my $filename = '/prtspool/'.
1480: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
1481: time.'_'.rand(1000000000).'.csv';
1482: my $file;
1483: unless ($file = Apache::File->new('>'.'/home/httpd'.$filename)) {
1484: $r->log_error("Couldn't open $filename for output $!");
1485: $r->print("Problems occured in writing the csv file. ".
1486: "This error has been logged. ".
1487: "Please alert your LON-CAPA administrator.");
1488: $r->print("<pre>\n".$csvdata."</pre>\n");
1489: return 0;
1490: }
1491: print $file $csvdata;
1492: close($file);
1493: $r->print('<br /><br />'.
1494: '<a href="'.$filename.'">Your CSV spreadsheet.</a>'."\n");
1495: #
1496: return 1;
1497: }
1498:
1499: ############################################
1500: ## Excel output routines ##
1501: ############################################
1502: sub outsheet_recursive_excel {
1503: my ($sheet,$r) = @_;
1504: my $c = $r->connection;
1505: return undef if ($sheet->{'sheettype'} ne 'classcalc');
1506: my ($workbook,$filename) = &create_excel_spreadsheet($sheet,$r);
1507: return undef if (! defined($workbook));
1508: #
1509: # Create main worksheet
1510: my $main_worksheet = $workbook->addworksheet('main');
1511: #
1512: # Figure out who the students are
1513: my %f=&getformulas($sheet);
1514: my $count = 0;
1515: $r->print(<<END);
1516: <p>
1517: Compiling Excel Workbook with a worksheet for each student.
1518: </p><p>
1519: This operation may take longer than a complete recalculation of the
1520: spreadsheet.
1521: </p><p>
1522: To abort this operation, hit the stop button on your browser.
1523: </p><p>
1524: A link to the spreadsheet will be available at the end of this process.
1525: </p>
1526: <p>
1527: END
1528: $r->rflush();
1529: my $starttime = time;
1530: foreach (keys(%f)) {
1531: next if ($_!~/^A(\d+)/ || $1 == 0 || ($f{$_}=~/^[!~-]/));
1532: $count++;
1533: my ($sname,$sdom) = split(':',$f{$_});
1534: my $student_excel_worksheet=$workbook->addworksheet($sname.'@'.$sdom);
1535: # Create a new spreadsheet
1536: my $studentsheet = &makenewsheet($sname,$sdom,'studentcalc',undef);
1537: # Read in the spreadsheet definition
1538: &update_student_sheet($studentsheet,$c);
1539: # Stuff the sheet into excel
1540: &export_sheet_as_excel($studentsheet,$student_excel_worksheet);
1541: my $totaltime = int((time - $starttime) / $count * $sheet->{'maxrow'});
1542: my $timeleft = int((time - $starttime) / $count * ($sheet->{'maxrow'} - $count));
1543: if ($count % 5 == 0) {
1544: $r->print($count.' students completed.'.
1545: ' Time remaining: '.$timeleft.' sec. '.
1546: ' Estimated total time: '.$totaltime." sec <br />\n");
1547: $r->rflush();
1548: }
1549: if(defined($c) && ($c->aborted())) {
1550: last;
1551: }
1552: }
1553: #
1554: if(! $c->aborted() ) {
1555: $r->print('All students spreadsheets completed!<br />');
1556: $r->rflush();
1557: #
1558: # &export_sheet_as_excel fills $worksheet with the data from $sheet
1559: &export_sheet_as_excel($sheet,$main_worksheet);
1560: #
1561: $workbook->close();
1562: # Okay, the spreadsheet is taken care of, so give the user a link.
1563: $r->print('<br /><br />'.
1564: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
1565: } else {
1566: $workbook->close(); # Not sure how necessary this is.
1567: #unlink('/home/httpd'.$filename); # No need to keep this around?
1568: }
1569: return 1;
1570: }
1571:
1572: sub outsheet_excel {
1573: my ($sheet,$r) = @_;
1574: my ($workbook,$filename) = &create_excel_spreadsheet($sheet,$r);
1575: return undef if (! defined($workbook));
1576: my $sheetname;
1577: if ($sheet->{'sheettype'} eq 'classcalc') {
1578: $sheetname = 'Main';
1579: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
1580: $sheetname = $sheet->{'uname'}.'@'.$sheet->{'udom'};
1581: } elsif ($sheet->{'sheettype'} eq 'assesscalc') {
1582: $sheetname = $sheet->{'uname'}.'@'.$sheet->{'udom'}.' assessment';
1583: }
1584: my $worksheet = $workbook->addworksheet($sheetname);
1585: #
1586: # &export_sheet_as_excel fills $worksheet with the data from $sheet
1587: &export_sheet_as_excel($sheet,$worksheet);
1588: #
1589: $workbook->close();
1590: # Okay, the spreadsheet is taken care of, so give the user a link.
1591: $r->print('<br /><br />'.
1592: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
1593: return 1;
1594: }
1595:
1596: sub create_excel_spreadsheet {
1597: my ($sheet,$r) = @_;
1598: my $filename = '/prtspool/'.
1599: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
1600: time.'_'.rand(1000000000).'.xls';
1601: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1602: if (! defined($workbook)) {
1603: $r->log_error("Error creating excel spreadsheet $filename: $!");
1604: $r->print("Problems creating new Excel file. ".
1605: "This error has been logged. ".
1606: "Please alert your LON-CAPA administrator");
1607: return undef;
1608: }
1609: #
1610: # The spreadsheet stores temporary data in files, then put them
1611: # together. If needed we should be able to disable this (memory only).
1612: # The temporary directory must be specified before calling 'addworksheet'.
1613: # File::Temp is used to determine the temporary directory.
1614: $workbook->set_tempdir('/home/httpd/perl/tmp');
1615: #
1616: # Determine the name to give the worksheet
1617: return ($workbook,$filename);
1618: }
1619:
1620: sub export_sheet_as_excel {
1621: my $sheet = shift;
1622: my $worksheet = shift;
1623: #
1624: my $rows_output = 0;
1625: my $cols_output = 0;
1626: ####################################
1627: # Write an identifying row #
1628: ####################################
1629: my @Headerinfo = ($sheet->{'coursedesc'});
1630: my $title = &gettitle($sheet);
1631: $cols_output = 0;
1632: if (defined($title)) {
1633: $worksheet->write($rows_output++,$cols_output++,$title);
1634: }
1635: ####################################
1636: # Write the summary/export row #
1637: ####################################
1638: my ($rowlabel,@rowdata) = &get_row($sheet,'0');
1639: my $label = &format_excel_rowlabel($rowlabel);
1640: $cols_output = 0;
1641: $worksheet->write($rows_output,$cols_output++,$label);
1642: foreach my $cell (@rowdata) {
1643: $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
1644: }
1645: $rows_output+= 2; # Skip a row, just for fun
1646: ####################################
1647: # Prepare to output rows
1648: ####################################
1649: my @Rows = &sort_indicies($sheet);
1650: #
1651: # Loop through the rows and output them one at a time
1652: foreach my $rownum (@Rows) {
1653: my ($rowlabel,@rowdata) = &get_row($sheet,$rownum);
1654: next if ($rowlabel =~ /^\s*$/);
1655: $cols_output = 0;
1656: my $label = &format_excel_rowlabel($rowlabel);
1657: $worksheet->write($rows_output,$cols_output++,$label);
1658: if (ref($label)) {
1659: $cols_output = (scalar(@$label));
1660: }
1661: foreach my $cell (@rowdata) {
1662: $worksheet->write($rows_output,$cols_output++,$cell->{'value'});
1663: }
1664: $rows_output++;
1665: }
1666: return;
1667: }
1668:
1669: ############################################
1670: ## XML output routines ##
1671: ############################################
1672: sub outsheet_xml {
1673: my ($sheet,$r) = @_;
1674: ## Someday XML
1675: ## Will be rendered for the user
1676: ## But not on this day
1677: }
1678:
1679: ##
1680: ## Outsheet - calls other outsheet_* functions
1681: ##
1682: sub outsheet {
1683: my ($r,$sheet)=@_;
1684: if (! exists($ENV{'form.output'})) {
1685: $ENV{'form.output'} = 'HTML';
1686: }
1687: if (lc($ENV{'form.output'}) eq 'csv') {
1688: &outsheet_csv($sheet,$r);
1689: } elsif (lc($ENV{'form.output'}) eq 'excel') {
1690: &outsheet_excel($sheet,$r);
1691: } elsif (lc($ENV{'form.output'}) eq 'recursive excel') {
1692: &outsheet_recursive_excel($sheet,$r);
1693: # } elsif (lc($ENV{'form.output'}) eq 'xml' ) {
1694: # &outsheet_xml($sheet,$r);
1695: } else {
1696: &outsheet_html($sheet,$r);
1697: }
1698: }
1699:
1700: ########################################################################
1701: ########################################################################
1702: sub othersheets {
1703: my ($sheet,$stype)=@_;
1704: $stype = $sheet->{'sheettype'} if (! defined($stype));
1705: #
1706: my $cnum = $sheet->{'cnum'};
1707: my $cdom = $sheet->{'cdom'};
1708: my $chome = $sheet->{'chome'};
1709: #
1710: my @alternatives=();
1711: my %results=&Apache::lonnet::dump($stype.'_spreadsheets',$cdom,$cnum);
1712: my ($tmp) = keys(%results);
1713: unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1714: @alternatives = sort (keys(%results));
1715: }
1716: return @alternatives;
1717: }
1718:
1719: #
1720: # -------------------------------------- Parse a spreadsheet
1721: #
1722: sub parse_sheet {
1723: # $sheetxml is a scalar reference or a scalar
1724: my ($sheetxml) = @_;
1725: if (! ref($sheetxml)) {
1726: my $tmp = $sheetxml;
1727: $sheetxml = \$tmp;
1728: }
1729: my %f;
1730: my $parser=HTML::TokeParser->new($sheetxml);
1731: my $token;
1732: while ($token=$parser->get_token) {
1733: if ($token->[0] eq 'S') {
1734: if ($token->[1] eq 'field') {
1735: $f{$token->[2]->{'col'}.$token->[2]->{'row'}}=
1736: $parser->get_text('/field');
1737: }
1738: if ($token->[1] eq 'template') {
1739: $f{'template_'.$token->[2]->{'col'}}=
1740: $parser->get_text('/template');
1741: }
1742: }
1743: }
1744: return \%f;
1745: }
1746:
1747: #
1748: # -------------------------------------- Read spreadsheet formulas for a course
1749: #
1750: sub readsheet {
1751: my ($sheet,$fn)=@_;
1752: #
1753: my $stype = $sheet->{'sheettype'};
1754: my $cnum = $sheet->{'cnum'};
1755: my $cdom = $sheet->{'cdom'};
1756: my $chome = $sheet->{'chome'};
1757: #
1758: if (! defined($fn)) {
1759: # There is no filename. Look for defaults in course and global, cache
1760: unless ($fn=$defaultsheets{$cnum.'_'.$cdom.'_'.$stype}) {
1761: my %tmphash = &Apache::lonnet::get('environment',
1762: ['spreadsheet_default_'.$stype],
1763: $cdom,$cnum);
1764: my ($tmp) = keys(%tmphash);
1765: if ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1766: $fn = 'default_'.$stype;
1767: } else {
1768: $fn = $tmphash{'spreadsheet_default_'.$stype};
1769: }
1770: unless (($fn) && ($fn!~/^error\:/)) {
1771: $fn='default_'.$stype;
1772: }
1773: $defaultsheets{$cnum.'_'.$cdom.'_'.$stype}=$fn;
1774: }
1775: }
1776: # $fn now has a value
1777: $sheet->{'filename'} = $fn;
1778: # see if sheet is cached
1779: my $fstring='';
1780: if ($fstring=$spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}) {
1781: my %tmp = split(/___;___/,$fstring);
1782: $sheet->{'f'} = \%tmp;
1783: &setformulas($sheet);
1784: } else {
1785: # Not cached, need to read
1786: my %f=();
1787: if ($fn=~/^default\_/) {
1788: my $sheetxml='';
1789: my $fh;
1790: my $dfn=$fn;
1791: $dfn=~s/\_/\./g;
1792: if ($fh=Apache::File->new($includedir.'/'.$dfn)) {
1793: $sheetxml=join('',<$fh>);
1794: } else {
1795: # $sheetxml='<field row="0" col="A">"Error"</field>';
1796: $sheetxml='<field row="0" col="A"></field>';
1797: }
1798: %f=%{&parse_sheet(\$sheetxml)};
1799: } elsif($fn=~/\/*\.spreadsheet$/) {
1800: my $sheetxml=&Apache::lonnet::getfile
1801: (&Apache::lonnet::filelocation('',$fn));
1802: if ($sheetxml == -1) {
1803: $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
1804: .$fn.'"</field>';
1805: }
1806: %f=%{&parse_sheet(\$sheetxml)};
1807: } else {
1808: my $sheet='';
1809: my %tmphash = &Apache::lonnet::dump($fn,$cdom,$cnum);
1810: my ($tmp) = keys(%tmphash);
1811: unless ($tmp =~ /^(con_lost|error|no_such_host)/i) {
1812: foreach (keys(%tmphash)) {
1813: $f{$_}=$tmphash{$_};
1814: }
1815: }
1816: }
1817: # Cache and set
1818: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
1819: $sheet->{'f'}=\%f;
1820: &setformulas($sheet);
1821: }
1822: }
1823:
1824: # -------------------------------------------------------- Make new spreadsheet
1825: sub makenewsheet {
1826: my ($uname,$udom,$stype,$usymb)=@_;
1827: my $sheet={};
1828: $sheet->{'uname'} = $uname;
1829: $sheet->{'udom'} = $udom;
1830: $sheet->{'sheettype'} = $stype;
1831: $sheet->{'usymb'} = $usymb;
1832: $sheet->{'mapid'} = $ENV{'form.mapid'};
1833: $sheet->{'resid'} = $ENV{'form.resid'};
1834: $sheet->{'cid'} = $ENV{'request.course.id'};
1835: $sheet->{'csec'} = $Section{$uname.':'.$udom};
1836: $sheet->{'coursefilename'} = $ENV{'request.course.fn'};
1837: $sheet->{'cnum'} = $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
1838: $sheet->{'cdom'} = $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
1839: $sheet->{'chome'} = $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
1840: $sheet->{'coursedesc'} = $ENV{'course.'.$ENV{'request.course.id'}.
1841: '.description'};
1842: $sheet->{'uhome'} = &Apache::lonnet::homeserver($uname,$udom);
1843: #
1844: #
1845: $sheet->{'f'} = {};
1846: $sheet->{'constants'} = {};
1847: $sheet->{'othersheets'} = [];
1848: $sheet->{'rowlabel'} = {};
1849: #
1850: #
1851: $sheet->{'safe'}=&initsheet($sheet->{'sheettype'});
1852: #
1853: # Place all the %$sheet items into the safe space except the safe space
1854: # itself
1855: my $initstring = '';
1856: foreach (qw/uname udom sheettype usymb cid csec coursefilename
1857: cnum cdom chome uhome/) {
1858: $initstring.= qq{\$$_="$sheet->{$_}";};
1859: }
1860: $sheet->{'safe'}->reval($initstring);
1861: return $sheet;
1862: }
1863:
1864: # ------------------------------------------------------------ Save spreadsheet
1865: sub writesheet {
1866: my ($sheet,$makedef)=@_;
1867: my $cid=$sheet->{'cid'};
1868: if (&Apache::lonnet::allowed('opa',$cid)) {
1869: my %f=&getformulas($sheet);
1870: my $stype= $sheet->{'sheettype'};
1871: my $cnum = $sheet->{'cnum'};
1872: my $cdom = $sheet->{'cdom'};
1873: my $chome= $sheet->{'chome'};
1874: my $fn = $sheet->{'filename'};
1875: # Cache new sheet
1876: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
1877: # Write sheet
1878: foreach (keys(%f)) {
1879: delete($f{$_}) if ($f{$_} eq 'import');
1880: }
1881: my $reply = &Apache::lonnet::put($fn,\%f,$cdom,$cnum);
1882: if ($reply eq 'ok') {
1883: $reply = &Apache::lonnet::put($stype.'_spreadsheets',
1884: {$fn => $ENV{'user.name'}.'@'.$ENV{'user.domain'}},
1885: $cdom,$cnum);
1886: if ($reply eq 'ok') {
1887: if ($makedef) {
1888: return &Apache::lonnet::put('environment',
1889: {'spreadsheet_default_'.$stype => $fn },
1890: $cdom,$cnum);
1891: }
1892: return $reply;
1893: }
1894: return $reply;
1895: }
1896: return $reply;
1897: }
1898: return 'unauthorized';
1899: }
1900:
1901: # ----------------------------------------------- Make a temp copy of the sheet
1902: # "Modified workcopy" - interactive only
1903: #
1904: sub tmpwrite {
1905: my ($sheet) = @_;
1906: my $fn=$ENV{'user.name'}.'_'.
1907: $ENV{'user.domain'}.'_spreadsheet_'.$sheet->{'usymb'}.'_'.
1908: $sheet->{'filename'};
1909: $fn=~s/\W/\_/g;
1910: $fn=$tmpdir.$fn.'.tmp';
1911: my $fh;
1912: if ($fh=Apache::File->new('>'.$fn)) {
1913: print $fh join("\n",&getformulas($sheet));
1914: }
1915: }
1916:
1917: # ---------------------------------------------------------- Read the temp copy
1918: sub tmpread {
1919: my ($sheet,$nfield,$nform)=@_;
1920: my $fn=$ENV{'user.name'}.'_'.
1921: $ENV{'user.domain'}.'_spreadsheet_'.$sheet->{'usymb'}.'_'.
1922: $sheet->{'filename'};
1923: $fn=~s/\W/\_/g;
1924: $fn=$tmpdir.$fn.'.tmp';
1925: my $fh;
1926: my %fo=();
1927: my $countrows=0;
1928: if ($fh=Apache::File->new($fn)) {
1929: my $name;
1930: while ($name=<$fh>) {
1931: chomp($name);
1932: my $value=<$fh>;
1933: chomp($value);
1934: $fo{$name}=$value;
1935: if ($name=~/^A(\d+)$/) {
1936: if ($1>$countrows) {
1937: $countrows=$1;
1938: }
1939: }
1940: }
1941: }
1942: if ($nform eq 'changesheet') {
1943: $fo{'A'.$nfield}=(split(/__&&&\__/,$fo{'A'.$nfield}))[0];
1944: unless ($ENV{'form.sel_'.$nfield} eq 'Default') {
1945: $fo{'A'.$nfield}.='__&&&__'.$ENV{'form.sel_'.$nfield};
1946: }
1947: } elsif ($nfield eq 'insertrow') {
1948: $countrows++;
1949: my $newrow=substr('000000'.$countrows,-7);
1950: if ($nform eq 'top') {
1951: $fo{'A'.$countrows}='--- '.$newrow;
1952: } else {
1953: $fo{'A'.$countrows}='~~~ '.$newrow;
1954: }
1955: } else {
1956: if ($nfield) { $fo{$nfield}=$nform; }
1957: }
1958: $sheet->{'f'}=\%fo;
1959: &setformulas($sheet);
1960: }
1961:
1962: ##################################################
1963: ##################################################
1964:
1965: =pod
1966:
1967: =item &parmval()
1968:
1969: Determine the value of a parameter.
1970:
1971: Inputs: $what, the parameter needed, $sheet, the safe space
1972:
1973: Returns: The value of a parameter, or '' if none.
1974:
1975: This function cascades through the possible levels searching for a value for
1976: a parameter. The levels are checked in the following order:
1977: user, course (at section level and course level), map, and lonnet::metadata.
1978: This function uses %parmhash, which must be tied prior to calling it.
1979: This function also requires %courseopt and %useropt to be initialized for
1980: this user and course.
1981:
1982: =cut
1983:
1984: ##################################################
1985: ##################################################
1986: sub parmval {
1987: my ($what,$sheet)=@_;
1988: my $symb = $sheet->{'usymb'};
1989: unless ($symb) { return ''; }
1990: #
1991: my $cid = $sheet->{'cid'};
1992: my $csec = $sheet->{'csec'};
1993: my $uname = $sheet->{'uname'};
1994: my $udom = $sheet->{'udom'};
1995: my $result='';
1996: #
1997: my ($mapname,$id,$fn)=split(/\_\_\_/,$symb);
1998: # Cascading lookup scheme
1999: my $rwhat=$what;
2000: $what =~ s/^parameter\_//;
2001: $what =~ s/\_([^\_]+)$/\.$1/;
2002: #
2003: my $symbparm = $symb.'.'.$what;
2004: my $mapparm = $mapname.'___(all).'.$what;
2005: my $usercourseprefix = $uname.'_'.$udom.'_'.$cid;
2006: #
2007: my $seclevel = $usercourseprefix.'.['.$csec.'].'.$what;
2008: my $seclevelr = $usercourseprefix.'.['.$csec.'].'.$symbparm;
2009: my $seclevelm = $usercourseprefix.'.['.$csec.'].'.$mapparm;
2010: #
2011: my $courselevel = $usercourseprefix.'.'.$what;
2012: my $courselevelr = $usercourseprefix.'.'.$symbparm;
2013: my $courselevelm = $usercourseprefix.'.'.$mapparm;
2014: # fourth, check user
2015: if (defined($uname)) {
2016: return $useropt{$courselevelr} if (defined($useropt{$courselevelr}));
2017: return $useropt{$courselevelm} if (defined($useropt{$courselevelm}));
2018: return $useropt{$courselevel} if (defined($useropt{$courselevel}));
2019: }
2020: # third, check course
2021: if (defined($csec)) {
2022: return $courseopt{$seclevelr} if (defined($courseopt{$seclevelr}));
2023: return $courseopt{$seclevelm} if (defined($courseopt{$seclevelm}));
2024: return $courseopt{$seclevel} if (defined($courseopt{$seclevel}));
2025: }
2026: #
2027: return $courseopt{$courselevelr} if (defined($courseopt{$courselevelr}));
2028: return $courseopt{$courselevelm} if (defined($courseopt{$courselevelm}));
2029: return $courseopt{$courselevel} if (defined($courseopt{$courselevel}));
2030: # second, check map parms
2031: my $thisparm = $parmhash{$symbparm};
2032: return $thisparm if (defined($thisparm));
2033: # first, check default
2034: return &Apache::lonnet::metadata($fn,$rwhat.'.default');
2035: }
2036:
2037:
2038: ##################################################################
2039: ## Row label formatting routines ##
2040: ##################################################################
2041: sub format_html_rowlabel {
2042: my $rowlabel = shift;
2043: return '' if ($rowlabel eq '');
2044: my ($type,$labeldata) = split(':',$rowlabel,2);
2045: my $result = '';
2046: if ($type eq 'symb') {
2047: my ($symb,$uname,$udom,$mapid,$resid,$title) = split(':',$labeldata);
2048: $symb = &Apache::lonnet::unescape($symb);
2049: $result = '<a href="/adm/assesscalc?usymb='.$symb.
2050: '&uname='.$uname.'&udom='.$udom.
2051: '&mapid='.$mapid.'&resid='.$resid.'">'.$title.'</a>';
2052: } elsif ($type eq 'student') {
2053: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
2054: $result ='<a href="/adm/studentcalc?uname='.$sname.
2055: '&udom='.$sdom.'">';
2056: $result.=$section.' '.$id." ".$fullname.'</a>';
2057: } elsif ($type eq 'parameter') {
2058: $result = $labeldata;
2059: } else {
2060: $result = '<b><font size=+1>'.$rowlabel.'</font></b>';
2061: }
2062: return $result;
2063: }
2064:
2065: sub format_csv_rowlabel {
2066: my $rowlabel = shift;
2067: return '' if ($rowlabel eq '');
2068: my ($type,$labeldata) = split(':',$rowlabel,2);
2069: my $result = '';
2070: if ($type eq 'symb') {
2071: my ($symb,$uname,$udom,$mapid,$resid,$title) = split(':',$labeldata);
2072: $symb = &Apache::lonnet::unescape($symb);
2073: $result = $title;
2074: } elsif ($type eq 'student') {
2075: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
2076: $result = join('","',($sname,$sdom,$fullname,$section,$id));
2077: } elsif ($type eq 'parameter') {
2078: $labeldata =~ s/<br>/ /g;
2079: $result = $labeldata;
2080: } else {
2081: $result = $rowlabel;
2082: }
2083: return '"'.$result.'"';
2084: }
2085:
2086: sub format_excel_rowlabel {
2087: my $rowlabel = shift;
2088: return '' if ($rowlabel eq '');
2089: my ($type,$labeldata) = split(':',$rowlabel,2);
2090: my $result = '';
2091: if ($type eq 'symb') {
2092: my ($symb,$uname,$udom,$mapid,$resid,$title) = split(':',$labeldata);
2093: $symb = &Apache::lonnet::unescape($symb);
2094: $result = $title;
2095: } elsif ($type eq 'student') {
2096: my ($sname,$sdom,$fullname,$section,$id) = split(':',$labeldata);
2097: $section = '' if (! defined($section));
2098: $id = '' if (! defined($id));
2099: my @Data = ($sname,$sdom,$fullname,$section,$id);
2100: $result = \@Data;
2101: } elsif ($type eq 'parameter') {
2102: $labeldata =~ s/<br>/ /g;
2103: $result = $labeldata;
2104: } else {
2105: $result = $rowlabel;
2106: }
2107: return $result;
2108: }
2109:
2110: # ---------------------------------------------- Update rows for course listing
2111: sub updateclasssheet {
2112: my ($sheet) = @_;
2113: my $cnum =$sheet->{'cnum'};
2114: my $cdom =$sheet->{'cdom'};
2115: my $cid =$sheet->{'cid'};
2116: my $chome =$sheet->{'chome'};
2117: #
2118: %Section = ();
2119: #
2120: # Read class list and row labels
2121: my $classlist = &Apache::loncoursedata::get_classlist();
2122: if (! defined($classlist)) {
2123: return 'Could not access course classlist';
2124: }
2125: #
2126: my %currentlist=();
2127: foreach my $student (keys(%$classlist)) {
2128: my ($studentDomain,$studentName,$end,$start,$id,$studentSection,
2129: $fullname,$status) = @{$classlist->{$student}};
2130: $Section{$studentName.':'.$studentDomain} = $studentSection;
2131: if ($ENV{'form.Status'} eq $status || $ENV{'form.Status'} eq 'Any') {
2132: $currentlist{$student}=join(':',('student',$studentName,
2133: $studentDomain,$fullname,
2134: $studentSection,$id));
2135: }
2136: }
2137: #
2138: # Find discrepancies between the course row table and this
2139: #
2140: my %f=&getformulas($sheet);
2141: my $changed=0;
2142: #
2143: $sheet->{'maxrow'}=0;
2144: my %existing=();
2145: #
2146: # Now obsolete rows
2147: foreach (keys(%f)) {
2148: if ($_=~/^A(\d+)/) {
2149: if ($1 > $sheet->{'maxrow'}) {
2150: $sheet->{'maxrow'}= $1;
2151: }
2152: $existing{$f{$_}}=1;
2153: unless ((defined($currentlist{$f{$_}})) || (!$1) ||
2154: ($f{$_}=~/^(~~~|---)/)) {
2155: $f{$_}='!!! Obsolete';
2156: $changed=1;
2157: }
2158: }
2159: }
2160: #
2161: # New and unknown keys
2162: foreach my $student (sort keys(%currentlist)) {
2163: unless ($existing{$student}) {
2164: $changed=1;
2165: $sheet->{'maxrow'}++;
2166: $f{'A'.$sheet->{'maxrow'}}=$student;
2167: }
2168: }
2169: if ($changed) {
2170: $sheet->{'f'} = \%f;
2171: &setformulas($sheet,%f);
2172: }
2173: #
2174: &setrowlabels($sheet,\%currentlist);
2175: }
2176:
2177: # ----------------------------------- Update rows for student and assess sheets
2178: sub get_student_rowlabels {
2179: my ($sheet) = @_;
2180: #
2181: my %course_db;
2182: #
2183: my $stype = $sheet->{'sheettype'};
2184: my $uname = $sheet->{'uname'};
2185: my $udom = $sheet->{'udom'};
2186: #
2187: $sheet->{'rowlabel'} = {};
2188: #
2189: my $identifier =$sheet->{'coursefilename'}.'_'.$stype;
2190: if ($rowlabel_cache{$identifier}) {
2191: %{$sheet->{'rowlabel'}}=split(/___;___/,$rowlabel_cache{$identifier});
2192: } else {
2193: # Get the data and store it in the cache
2194: # Tie hash
2195: tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
2196: &GDBM_READER(),0640);
2197: if (! tied(%course_db)) {
2198: return 'Could not access course data';
2199: }
2200: #
2201: my %assesslist;
2202: foreach ('Feedback','Evaluation','Tutoring','Discussion') {
2203: my $symb = '_'.lc($_);
2204: $assesslist{$symb} = join(':',('symb',$symb,$uname,$udom,0,0,$_));
2205: }
2206: #
2207: while (my ($key,$srcf) = each(%course_db)) {
2208: next if ($key !~ /^src_(\d+)\.(\d+)$/);
2209: my $mapid = $1;
2210: my $resid = $2;
2211: my $id = $mapid.'.'.$resid;
2212: if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
2213: my $symb=
2214: &Apache::lonnet::declutter($course_db{'map_id_'.$mapid}).
2215: '___'.$resid.'___'.&Apache::lonnet::declutter($srcf);
2216: $assesslist{$symb}='symb:'.&Apache::lonnet::escape($symb).':'
2217: .$uname.':'.$udom.':'.$mapid.':'.$resid.':'.
2218: $course_db{'title_'.$id};
2219: }
2220: }
2221: untie(%course_db);
2222: # Store away the data
2223: $sheet->{'rowlabel'} = \%assesslist;
2224: $rowlabel_cache{$identifier}=join('___;___',%{$sheet->{'rowlabel'}});
2225: }
2226:
2227: }
2228:
2229: sub get_assess_rowlabels {
2230: my ($sheet) = @_;
2231: #
2232: my %course_db;
2233: #
2234: my $stype = $sheet->{'sheettype'};
2235: my $uname = $sheet->{'uname'};
2236: my $udom = $sheet->{'udom'};
2237: my $usymb = $sheet->{'usymb'};
2238: #
2239: $sheet->{'rowlabel'} = {};
2240: my $identifier =$sheet->{'coursefilename'}.'_'.$stype.'_'.$usymb;
2241: #
2242: if ($rowlabel_cache{$identifier}) {
2243: %{$sheet->{'rowlabel'}}=split(/___;___/,$rowlabel_cache{$identifier});
2244: } else {
2245: # Get the data and store it in the cache
2246: # Tie hash
2247: tie(%course_db,'GDBM_File',$sheet->{'coursefilename'}.'.db',
2248: &GDBM_READER(),0640);
2249: if (! tied(%course_db)) {
2250: return 'Could not access course data';
2251: }
2252: #
2253: my %parameter_labels=
2254: ('timestamp' =>
2255: 'parameter:Timestamp of Last Transaction<br>timestamp',
2256: 'subnumber' =>
2257: 'parameter:Number of Submissions<br>subnumber',
2258: 'tutornumber' =>
2259: 'parameter:Number of Tutor Responses<br>tutornumber',
2260: 'totalpoints' =>
2261: 'parameter:Total Points Granted<br>totalpoints');
2262: while (my ($key,$srcf) = each(%course_db)) {
2263: next if ($key !~ /^src_(\d+)\.(\d+)$/);
2264: my $mapid = $1;
2265: my $resid = $2;
2266: my $id = $mapid.'.'.$resid;
2267: if ($srcf=~/\.(problem|exam|quiz|assess|survey|form)$/) {
2268: # Loop through the metadata for this key
2269: my @Metadata = split(/,/,
2270: &Apache::lonnet::metadata($srcf,'keys'));
2271: foreach my $key (@Metadata) {
2272: next if ($key !~ /^(stores|parameter)_/);
2273: my $display=
2274: &Apache::lonnet::metadata($srcf,$key.'.display');
2275: unless ($display) {
2276: $display.=
2277: &Apache::lonnet::metadata($srcf,$key.'.name');
2278: }
2279: $display.='<br>'.$key;
2280: $parameter_labels{$key}='parameter:'.$display;
2281: } # end of foreach
2282: }
2283: }
2284: untie(%course_db);
2285: # Store away the results
2286: $sheet->{'rowlabel'} = \%parameter_labels;
2287: $rowlabel_cache{$identifier}=join('___;___',%{$sheet->{'rowlabel'}});
2288: }
2289:
2290: }
2291:
2292: sub updatestudentassesssheet {
2293: my $sheet = shift;
2294: if ($sheet->{'sheettype'} eq 'studentcalc') {
2295: &get_student_rowlabels($sheet);
2296: } else {
2297: &get_assess_rowlabels($sheet);
2298: }
2299: # Determine if any of the information has changed
2300: my %f=&getformulas($sheet);
2301: my $changed=0;
2302:
2303: $sheet->{'maxrow'} = 0;
2304: my %existing=();
2305: # Now obsolete rows
2306: while (my ($cell, $formula) = each (%f)) {
2307: next if ($cell !~ /^A(\d+)/);
2308: $sheet->{'maxrow'} = $1 if ($1 > $sheet->{'maxrow'});
2309: my ($usy,$ufn)=split(/__&&&\__/,$formula);
2310: $existing{$usy}=1;
2311: unless ((exists($sheet->{'rowlabel'}->{$usy}) &&
2312: (defined($sheet->{'rowlabel'}->{$usy})) || (!$1) ||
2313: ($formula =~ /^(~~~|---)/) )) {
2314: $f{$_}='!!! Obsolete';
2315: $changed=1;
2316: } elsif ($ufn) {
2317: # I do not think this works any more
2318: $sheet->{'rowlabel'}->{$usy}
2319: =~s/assesscalc\?usymb\=/assesscalc\?ufn\=$ufn&\usymb\=/;
2320: }
2321: }
2322: # New and unknown keys
2323: foreach (keys(%{$sheet->{'rowlabel'}})) {
2324: unless ($existing{$_}) {
2325: $changed=1;
2326: $sheet->{'maxrow'}++;
2327: $f{'A'.$sheet->{'maxrow'}}=$_;
2328: }
2329: }
2330: if ($changed) {
2331: $sheet->{'f'} = \%f;
2332: &setformulas($sheet);
2333: }
2334: }
2335:
2336: # ------------------------------------------------ Load data for one assessment
2337:
2338: sub loadstudent{
2339: my ($sheet,$r,$c)=@_;
2340: my %constants=();
2341: my %formulas=&getformulas($sheet);
2342: $cachedassess=$sheet->{'uname'}.':'.$sheet->{'udom'};
2343: # Get ALL the student preformance data
2344: my @tmp = &Apache::lonnet::dump($sheet->{'cid'},
2345: $sheet->{'udom'},
2346: $sheet->{'uname'},
2347: undef);
2348: if ($tmp[0] !~ /^error:/) {
2349: %cachedstores = @tmp;
2350: }
2351: undef @tmp;
2352: #
2353: my @assessdata=();
2354: while (my ($cell,$value) = each (%formulas)) {
2355: if(defined($c) && ($c->aborted())) {
2356: last;
2357: }
2358: next if ($cell !~ /^A(\d+)/);
2359: my $row=$1;
2360: next if (($value =~ /^[!~-]/) || ($row==0));
2361: my ($usy,$ufn)=split(/__&&&\__/,$value);
2362: @assessdata=&exportsheet($sheet,$sheet->{'uname'},
2363: $sheet->{'udom'},
2364: 'assesscalc',$usy,$ufn,$r);
2365: my $index=0;
2366: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
2367: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
2368: if (defined($assessdata[$index])) {
2369: my $col=$_;
2370: if ($assessdata[$index]=~/\D/) {
2371: $constants{$col.$row}="'".$assessdata[$index]."'";
2372: } else {
2373: $constants{$col.$row}=$assessdata[$index];
2374: }
2375: unless ($col eq 'A') {
2376: $formulas{$col.$row}='import';
2377: }
2378: }
2379: $index++;
2380: }
2381: }
2382: $cachedassess='';
2383: undef %cachedstores;
2384: $sheet->{'f'} = \%formulas;
2385: &setformulas($sheet);
2386: &setconstants($sheet,\%constants);
2387: }
2388:
2389: # --------------------------------------------------- Load data for one student
2390: #
2391: sub loadcourse {
2392: my ($sheet,$r,$c)=@_;
2393: #
2394: my %constants=();
2395: my %formulas=&getformulas($sheet);
2396: #
2397: my $total=0;
2398: foreach (keys(%formulas)) {
2399: if ($_=~/^A(\d+)/) {
2400: unless ($formulas{$_}=~/^[\!\~\-]/) { $total++; }
2401: }
2402: }
2403: my $now=0;
2404: my $since=time;
2405: $r->print(<<ENDPOP);
2406: <script>
2407: popwin=open('','popwin','width=400,height=100');
2408: popwin.document.writeln('<html><body bgcolor="#FFFFFF">'+
2409: '<h3>Spreadsheet Calculation Progress</h3>'+
2410: '<form name=popremain>'+
2411: '<input type=text size=35 name=remaining value=Starting></form>'+
2412: '</body></html>');
2413: popwin.document.close();
2414: </script>
2415: ENDPOP
2416: $r->rflush();
2417: foreach (keys(%formulas)) {
2418: if(defined($c) && ($c->aborted())) {
2419: last;
2420: }
2421: next if ($_!~/^A(\d+)/);
2422: my $row=$1;
2423: next if (($formulas{$_}=~/^[\!\~\-]/) || ($row==0));
2424: my ($sname,$sdom) = split(':',$formulas{$_});
2425: my @studentdata=&exportsheet($sheet,$sname,$sdom,'studentcalc',
2426: undef,undef,$r);
2427: undef %userrdatas;
2428: $now++;
2429: $r->print('<script>popwin.document.popremain.remaining.value="'.
2430: $now.'/'.$total.': '.int((time-$since)/$now*($total-$now)).
2431: ' secs remaining";</script>');
2432: $r->rflush();
2433: #
2434: my $index=0;
2435: foreach ('A','B','C','D','E','F','G','H','I','J','K','L','M',
2436: 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z') {
2437: if (defined($studentdata[$index])) {
2438: my $col=$_;
2439: if ($studentdata[$index]=~/\D/) {
2440: $constants{$col.$row}="'".$studentdata[$index]."'";
2441: } else {
2442: $constants{$col.$row}=$studentdata[$index];
2443: }
2444: unless ($col eq 'A') {
2445: $formulas{$col.$row}='import';
2446: }
2447: }
2448: $index++;
2449: }
2450: }
2451: $sheet->{'f'}=\%formulas;
2452: &setformulas($sheet);
2453: &setconstants($sheet,\%constants);
2454: $r->print('<script>popwin.close()</script>');
2455: $r->rflush();
2456: }
2457:
2458: # ------------------------------------------------ Load data for one assessment
2459: #
2460: sub loadassessment {
2461: my ($sheet,$r,$c)=@_;
2462:
2463: my $uhome = $sheet->{'uhome'};
2464: my $uname = $sheet->{'uname'};
2465: my $udom = $sheet->{'udom'};
2466: my $symb = $sheet->{'usymb'};
2467: my $cid = $sheet->{'cid'};
2468: my $cnum = $sheet->{'cnum'};
2469: my $cdom = $sheet->{'cdom'};
2470: my $chome = $sheet->{'chome'};
2471:
2472: my $namespace;
2473: unless ($namespace=$cid) { return ''; }
2474: # Get stored values
2475: my %returnhash=();
2476: if ($cachedassess eq $uname.':'.$udom) {
2477: #
2478: # get data out of the dumped stores
2479: #
2480: my $version=$cachedstores{'version:'.$symb};
2481: my $scope;
2482: for ($scope=1;$scope<=$version;$scope++) {
2483: foreach (split(/\:/,$cachedstores{$scope.':keys:'.$symb})) {
2484: $returnhash{$_}=$cachedstores{$scope.':'.$symb.':'.$_};
2485: }
2486: }
2487: } else {
2488: #
2489: # restore individual
2490: #
2491: %returnhash = &Apache::lonnet::restore($symb,$namespace,$udom,$uname);
2492: for (my $version=1;$version<=$returnhash{'version'};$version++) {
2493: foreach (split(/\:/,$returnhash{$version.':keys'})) {
2494: $returnhash{$_}=$returnhash{$version.':'.$_};
2495: }
2496: }
2497: }
2498: #
2499: # returnhash now has all stores for this resource
2500: # convert all "_" to "." to be able to use libraries, multiparts, etc
2501: #
2502: # This is dumb. It is also necessary :(
2503: my @oldkeys=keys %returnhash;
2504: #
2505: foreach my $name (@oldkeys) {
2506: my $value=$returnhash{$name};
2507: delete $returnhash{$name};
2508: $name=~s/\_/\./g;
2509: $returnhash{$name}=$value;
2510: }
2511: # initialize coursedata and userdata for this user
2512: undef %courseopt;
2513: undef %useropt;
2514:
2515: my $userprefix=$uname.'_'.$udom.'_';
2516:
2517: unless ($uhome eq 'no_host') {
2518: # Get coursedata
2519: unless ((time-$courserdatas{$cid.'.last_cache'})<240) {
2520: my %Tmp = &Apache::lonnet::dump('resourcedata',$cdom,$cnum);
2521: $courserdatas{$cid}=\%Tmp;
2522: $courserdatas{$cid.'.last_cache'}=time;
2523: }
2524: while (my ($name,$value) = each(%{$courserdatas{$cid}})) {
2525: $courseopt{$userprefix.$name}=$value;
2526: }
2527: # Get userdata (if present)
2528: unless ((time-$userrdatas{$uname.'@'.$udom.'.last_cache'})<240) {
2529: my %Tmp = &Apache::lonnet::dump('resourcedata',$udom,$uname);
2530: $userrdatas{$cid} = \%Tmp;
2531: # Most of the time the user does not have a 'resourcedata.db'
2532: # file. We need to cache that we got nothing instead of bothering
2533: # with requesting it every time.
2534: $userrdatas{$uname.'@'.$udom.'.last_cache'}=time;
2535: }
2536: while (my ($name,$value) = each(%{$userrdatas{$cid}})) {
2537: $useropt{$userprefix.$name}=$value;
2538: }
2539: }
2540: # now courseopt, useropt initialized for this user and course
2541: # (used by parmval)
2542: #
2543: # Load keys for this assessment only
2544: #
2545: my %thisassess=();
2546: my ($symap,$syid,$srcf)=split(/\_\_\_/,$symb);
2547: foreach (split(/\,/,&Apache::lonnet::metadata($srcf,'keys'))) {
2548: $thisassess{$_}=1;
2549: }
2550: #
2551: # Load parameters
2552: #
2553: my %c=();
2554: if (tie(%parmhash,'GDBM_File',
2555: $sheet->{'coursefilename'}.'_parms.db',&GDBM_READER(),0640)) {
2556: my %f=&getformulas($sheet);
2557: foreach my $cell (keys(%f)) {
2558: next if ($cell !~ /^A/);
2559: next if ($f{$cell} =~/^[\!\~\-]/);
2560: if ($f{$cell}=~/^parameter/) {
2561: if (defined($thisassess{$f{$cell}})) {
2562: my $val = &parmval($f{$cell},$sheet);
2563: $c{$cell} = $val;
2564: $c{$f{$cell}} = $val;
2565: }
2566: } else {
2567: my $key=$f{$cell};
2568: my $ckey=$key;
2569: $key=~s/^stores\_/resource\./;
2570: $key=~s/\_/\./g;
2571: $c{$cell}=$returnhash{$key};
2572: $c{$ckey}=$returnhash{$key};
2573: }
2574: }
2575: untie(%parmhash);
2576: }
2577: &setconstants($sheet,\%c);
2578: }
2579:
2580: # --------------------------------------------------------- Various form fields
2581:
2582: sub textfield {
2583: my ($title,$name,$value)=@_;
2584: return "\n<p><b>$title:</b><br>".
2585: '<input type=text name="'.$name.'" size=80 value="'.$value.'">';
2586: }
2587:
2588: sub hiddenfield {
2589: my ($name,$value)=@_;
2590: return "\n".'<input type=hidden name="'.$name.'" value="'.$value.'">';
2591: }
2592:
2593: sub selectbox {
2594: my ($title,$name,$value,%options)=@_;
2595: my $selout="\n<p><b>$title:</b><br>".'<select name="'.$name.'">';
2596: foreach (sort keys(%options)) {
2597: $selout.='<option value="'.$_.'"';
2598: if ($_ eq $value) { $selout.=' selected'; }
2599: $selout.='>'.$options{$_}.'</option>';
2600: }
2601: return $selout.'</select>';
2602: }
2603:
2604: # =============================================== Update information in a sheet
2605: #
2606: # Add new users or assessments, etc.
2607: #
2608:
2609: sub updatesheet {
2610: my ($sheet)=@_;
2611: if ($sheet->{'sheettype'} eq 'classcalc') {
2612: return &updateclasssheet($sheet);
2613: } else {
2614: return &updatestudentassesssheet($sheet);
2615: }
2616: }
2617:
2618: # =================================================== Load the rows for a sheet
2619: #
2620: # Import the data for rows
2621: #
2622:
2623: sub loadrows {
2624: my ($sheet,$r)=@_;
2625: my $c = $r->connection;
2626: my $stype=$sheet->{'sheettype'};
2627: if ($stype eq 'classcalc') {
2628: &loadcourse($sheet,$r,$c);
2629: } elsif ($stype eq 'studentcalc') {
2630: &loadstudent($sheet,$r,$c);
2631: } else {
2632: &loadassessment($sheet,$r,$c);
2633: }
2634: }
2635:
2636: # ======================================================= Forced recalculation?
2637:
2638: sub checkthis {
2639: my ($keyname,$time)=@_;
2640: return ($time<$expiredates{$keyname});
2641: }
2642:
2643: sub forcedrecalc {
2644: my ($uname,$udom,$stype,$usymb)=@_;
2645: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2646: my $time=$oldsheets{$key.'.time'};
2647: if ($ENV{'form.forcerecalc'}) { return 1; }
2648: unless ($time) { return 1; }
2649: if ($stype eq 'assesscalc') {
2650: my $map=(split(/___/,$usymb))[0];
2651: if (&checkthis('::assesscalc:',$time) ||
2652: &checkthis('::assesscalc:'.$map,$time) ||
2653: &checkthis('::assesscalc:'.$usymb,$time) ||
2654: &checkthis($uname.':'.$udom.':assesscalc:',$time) ||
2655: &checkthis($uname.':'.$udom.':assesscalc:'.$map,$time) ||
2656: &checkthis($uname.':'.$udom.':assesscalc:'.$usymb,$time)) {
2657: return 1;
2658: }
2659: } else {
2660: if (&checkthis('::studentcalc:',$time) ||
2661: &checkthis($uname.':'.$udom.':studentcalc:',$time)) {
2662: return 1;
2663: }
2664: }
2665: return 0;
2666: }
2667:
2668: # ============================================================== Export handler
2669: # exportsheet
2670: # returns the export row for a spreadsheet.
2671: #
2672: sub exportsheet {
2673: my ($sheet,$uname,$udom,$stype,$usymb,$fn,$r)=@_;
2674: $uname = $uname || $sheet->{'uname'};
2675: $udom = $udom || $sheet->{'udom'};
2676: $stype = $stype || $sheet->{'sheettype'};
2677: my @exportarr=();
2678: if (defined($usymb) && ($usymb=~/^\_(\w+)/) &&
2679: (!defined($fn) || $fn eq '')) {
2680: $fn='default_'.$1;
2681: }
2682: #
2683: # Check if cached
2684: #
2685: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
2686: my $found='';
2687: if ($oldsheets{$key}) {
2688: foreach (split(/___&\___/,$oldsheets{$key})) {
2689: my ($name,$value)=split(/___=___/,$_);
2690: if ($name eq $fn) {
2691: $found=$value;
2692: }
2693: }
2694: }
2695: unless ($found) {
2696: &cachedssheets($sheet,$uname,$udom);
2697: if ($oldsheets{$key}) {
2698: foreach (split(/___&\___/,$oldsheets{$key})) {
2699: my ($name,$value)=split(/___=___/,$_);
2700: if ($name eq $fn) {
2701: $found=$value;
2702: }
2703: }
2704: }
2705: }
2706: #
2707: # Check if still valid
2708: #
2709: if ($found) {
2710: if (&forcedrecalc($uname,$udom,$stype,$usymb)) {
2711: $found='';
2712: }
2713: }
2714: if ($found) {
2715: #
2716: # Return what was cached
2717: #
2718: @exportarr=split(/___;___/,$found);
2719: return @exportarr;
2720: }
2721: #
2722: # Not cached
2723: #
2724: my ($newsheet)=&makenewsheet($uname,$udom,$stype,$usymb);
2725: &readsheet($newsheet,$fn);
2726: &updatesheet($newsheet);
2727: &loadrows($newsheet,$r);
2728: &calcsheet($newsheet);
2729: @exportarr=&exportdata($newsheet);
2730: ##
2731: ## Store now
2732: ##
2733: #
2734: # load in the old value
2735: #
2736: my %currentlystored=();
2737: if ($stype eq 'studentcalc') {
2738: my @tmp = &Apache::lonnet::get('nohist_calculatedsheets',
2739: [$key],
2740: $sheet->{'cdom'},$sheet->{'cnum'});
2741: if ($tmp[0]!~/^error/) {
2742: %currentlystored = @tmp;
2743: }
2744: } else {
2745: my @tmp = &Apache::lonnet::get('nohist_calculatedsheets_'.
2746: $sheet->{'cid'},[$key],
2747: $sheet->{'udom'},$sheet->{'uname'});
2748: if ($tmp[0]!~/^error/) {
2749: %currentlystored = @tmp;
2750: }
2751: }
2752: #
2753: # Add the new line
2754: #
2755: $currentlystored{$fn}=join('___;___',@exportarr);
2756: #
2757: # Stick everything back together
2758: #
2759: my $newstore='';
2760: foreach (keys(%currentlystored)) {
2761: if ($newstore) { $newstore.='___&___'; }
2762: $newstore.=$_.'___=___'.$currentlystored{$_};
2763: }
2764: my $now=time;
2765: #
2766: # Store away the new value
2767: #
2768: if ($stype eq 'studentcalc') {
2769: &Apache::lonnet::put('nohist_calculatedsheets',
2770: { $key => $newstore,
2771: $key.time => $now },
2772: $sheet->{'cdom'},$sheet->{'cnum'});
2773: } else {
2774: &Apache::lonnet::put('nohist_calculatedsheets_'.$sheet->{'cid'},
2775: { $key => $newstore,
2776: $key.time => $now },
2777: $sheet->{'udom'},
2778: $sheet->{'uname'})
2779: }
2780: return @exportarr;
2781: }
2782:
2783: # ============================================================ Expiration Dates
2784: #
2785: # Load previously cached student spreadsheets for this course
2786: #
2787: sub load_spreadsheet_expirationdates {
2788: undef %expiredates;
2789: my $cid=$ENV{'request.course.id'};
2790: my @tmp = &Apache::lonnet::dump('nohist_expirationdates',
2791: $ENV{'course.'.$cid.'.domain'},
2792: $ENV{'course.'.$cid.'.num'});
2793: if (lc($tmp[0]) !~ /^error/){
2794: %expiredates = @tmp;
2795: }
2796: }
2797:
2798: # ===================================================== Calculated sheets cache
2799: #
2800: # Load previously cached student spreadsheets for this course
2801: #
2802:
2803: sub cachedcsheets {
2804: my $cid=$ENV{'request.course.id'};
2805: my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets',
2806: $ENV{'course.'.$cid.'.domain'},
2807: $ENV{'course.'.$cid.'.num'});
2808: if ($tmp[0] !~ /^error/) {
2809: my %StupidTempHash = @tmp;
2810: while (my ($key,$value) = each %StupidTempHash) {
2811: $oldsheets{$key} = $value;
2812: }
2813: }
2814: }
2815:
2816: # ===================================================== Calculated sheets cache
2817: #
2818: # Load previously cached assessment spreadsheets for this student
2819: #
2820:
2821: sub cachedssheets {
2822: my ($sheet,$uname,$udom) = @_;
2823: $uname = $uname || $sheet->{'uname'};
2824: $udom = $udom || $sheet->{'udom'};
2825: if (! $loadedcaches{$uname.'_'.$udom}) {
2826: my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets',
2827: $sheet->{'udom'},
2828: $sheet->{'uname'});
2829: if ($tmp[0] !~ /^error/) {
2830: my %TempHash = @tmp;
2831: my $count = 0;
2832: while (my ($key,$value) = each %TempHash) {
2833: $oldsheets{$key} = $value;
2834: $count++;
2835: }
2836: $loadedcaches{$sheet->{'uname'}.'_'.$sheet->{'udom'}}=1;
2837: }
2838: }
2839:
2840: }
2841:
2842: # ===================================================== Calculated sheets cache
2843: #
2844: # Load previously cached assessment spreadsheets for this student
2845: #
2846:
2847: # ================================================================ Main handler
2848: #
2849: # Interactive call to screen
2850: #
2851: #
2852: sub handler {
2853: my $r=shift;
2854:
2855: my ($sheettype) = ($r->uri=~/\/(\w+)$/);
2856:
2857: if (! exists($ENV{'form.Status'})) {
2858: $ENV{'form.Status'} = 'Active';
2859: }
2860: if ( ! exists($ENV{'form.output'}) ||
2861: ($sheettype ne 'classcalc' &&
2862: lc($ENV{'form.output'}) eq 'recursive excel')) {
2863: $ENV{'form.output'} = 'HTML';
2864: }
2865: #
2866: # Overload checking
2867: #
2868: # Check this server
2869: my $loaderror=&Apache::lonnet::overloaderror($r);
2870: if ($loaderror) { return $loaderror; }
2871: # Check the course homeserver
2872: $loaderror= &Apache::lonnet::overloaderror($r,
2873: $ENV{'course.'.$ENV{'request.course.id'}.'.home'});
2874: if ($loaderror) { return $loaderror; }
2875: #
2876: # HTML Header
2877: #
2878: if ($r->header_only) {
2879: $r->content_type('text/html');
2880: $r->send_http_header;
2881: return OK;
2882: }
2883: #
2884: # Global directory configs
2885: #
2886: $includedir = $r->dir_config('lonIncludes');
2887: $tmpdir = $r->dir_config('lonDaemons').'/tmp/';
2888: #
2889: # Roles Checking
2890: #
2891: # Needs to be in a course
2892: if (! $ENV{'request.course.fn'}) {
2893: # Not in a course, or not allowed to modify parms
2894: $ENV{'user.error.msg'}=
2895: $r->uri.":opa:0:0:Cannot modify spreadsheet";
2896: return HTTP_NOT_ACCEPTABLE;
2897: }
2898: #
2899: # Get query string for limited number of parameters
2900: #
2901: &Apache::loncommon::get_unprocessed_cgi
2902: ($ENV{'QUERY_STRING'},['uname','udom','usymb','ufn','mapid','resid']);
2903: #
2904: # Deal with restricted student permissions
2905: #
2906: if ($ENV{'request.role'} =~ /^st\./) {
2907: delete $ENV{'form.unewfield'} if (exists($ENV{'form.unewfield'}));
2908: delete $ENV{'form.unewformula'} if (exists($ENV{'form.unewformula'}));
2909: }
2910: #
2911: # Clean up symb and spreadsheet filename
2912: #
2913: if (($ENV{'form.usymb'}=~/^\_(\w+)/) && (!$ENV{'form.ufn'})) {
2914: $ENV{'form.ufn'}='default_'.$1;
2915: }
2916: #
2917: # Interactive loading of specific sheet?
2918: #
2919: if (($ENV{'form.load'}) && ($ENV{'form.loadthissheet'} ne 'Default')) {
2920: $ENV{'form.ufn'}=$ENV{'form.loadthissheet'};
2921: }
2922: #
2923: # Determine the user name and domain for the sheet.
2924: my $aname;
2925: my $adom;
2926: unless ($ENV{'form.uname'}) {
2927: $aname=$ENV{'user.name'};
2928: $adom=$ENV{'user.domain'};
2929: } else {
2930: $aname=$ENV{'form.uname'};
2931: $adom=$ENV{'form.udom'};
2932: }
2933: #
2934: # Open page, try to prevent browser cache.
2935: #
2936: $r->content_type('text/html');
2937: $r->header_out('Cache-control','no-cache');
2938: $r->header_out('Pragma','no-cache');
2939: $r->send_http_header;
2940: #
2941: # Header....
2942: #
2943: $r->print('<html><head><title>LON-CAPA Spreadsheet</title>');
2944: my $nothing = "''";
2945: if ($ENV{'browser.type'} eq 'explorer') {
2946: $nothing = "'javascript:void(0);'";
2947: }
2948:
2949: if ($ENV{'request.role'} !~ /^st\./) {
2950: $r->print(<<ENDSCRIPT);
2951: <script language="JavaScript">
2952:
2953: var editwin;
2954:
2955: function celledit(cellname,cellformula) {
2956: var edit_text = '';
2957: edit_text +='<html><head><title>Cell Edit Window</title></head><body>';
2958: edit_text += '<form name="editwinform">';
2959: edit_text += '<center><h3>Cell '+cellname+'</h3>';
2960: edit_text += '<textarea name="newformula" cols="40" rows="6"';
2961: edit_text += ' wrap="off" >'+cellformula+'</textarea>';
2962: edit_text += '</br>';
2963: edit_text += '<input type="button" name="accept" value="Accept"';
2964: edit_text += ' onClick=\\\'javascript:';
2965: edit_text += 'opener.document.sheet.unewfield.value=';
2966: edit_text += '"'+cellname+'";';
2967: edit_text += 'opener.document.sheet.unewformula.value=';
2968: edit_text += 'document.editwinform.newformula.value;';
2969: edit_text += 'opener.document.sheet.submit();';
2970: edit_text += 'self.close()\\\' />';
2971: edit_text += ' ';
2972: edit_text += '<input type="button" name="abort" ';
2973: edit_text += 'value="Discard Changes"';
2974: edit_text += ' onClick="javascript:self.close()" />';
2975: edit_text += '</center></body></html>';
2976:
2977: if (editwin != null && !(editwin.closed) ) {
2978: editwin.close();
2979: }
2980:
2981: editwin = window.open($nothing,'CellEditWin','height=200,width=350,scrollbars=no,resizeable=yes,alwaysRaised=yes,dependent=yes',true);
2982: editwin.document.write(edit_text);
2983: }
2984:
2985: function changesheet(cn) {
2986: document.sheet.unewfield.value=cn;
2987: document.sheet.unewformula.value='changesheet';
2988: document.sheet.submit();
2989: }
2990:
2991: function insertrow(cn) {
2992: document.sheet.unewfield.value='insertrow';
2993: document.sheet.unewformula.value=cn;
2994: document.sheet.submit();
2995: }
2996:
2997: </script>
2998: ENDSCRIPT
2999: }
3000: $r->print('</head>'.&Apache::loncommon::bodytag('Grades Spreadsheet').
3001: '<form action="'.$r->uri.'" name="sheet" method="post">');
3002: $r->print(&hiddenfield('uname',$ENV{'form.uname'}).
3003: &hiddenfield('udom',$ENV{'form.udom'}).
3004: &hiddenfield('usymb',$ENV{'form.usymb'}).
3005: &hiddenfield('unewfield','').
3006: &hiddenfield('unewformula',''));
3007: $r->rflush();
3008: #
3009: # Full recalc?
3010: #
3011: if ($ENV{'form.forcerecalc'}) {
3012: $r->print('<h4>Completely Recalculating Sheet ...</h4>');
3013: undef %spreadsheets;
3014: undef %courserdatas;
3015: undef %userrdatas;
3016: undef %defaultsheets;
3017: undef %rowlabel_cache;
3018: }
3019: # Read new sheet or modified worksheet
3020: my ($sheet)=&makenewsheet($aname,$adom,$sheettype,$ENV{'form.usymb'});
3021: #
3022: # Check user permissions
3023: if (($sheet->{'sheettype'} eq 'classcalc' ) ||
3024: ($sheet->{'uname'} ne $ENV{'user.name'} ) ||
3025: ($sheet->{'udom'} ne $ENV{'user.domain'})) {
3026: unless (&Apache::lonnet::allowed('vgr',$sheet->{'cid'})) {
3027: $r->print('<h1>Access Permission Denied</h1>'.
3028: '</form></body></html>');
3029: return OK;
3030: }
3031: }
3032: # Print out user information
3033: $r->print('<h2>'.$sheet->{'coursedesc'}.'</h2>');
3034: if ($sheet->{'sheettype'} ne 'classcalc') {
3035: $r->print('<h2>'.&gettitle($sheet).'</h2><p>');
3036: }
3037: if ($sheet->{'sheettype'} eq 'assesscalc') {
3038: $r->print('<b>User:</b> '.$sheet->{'uname'}.
3039: '<br /><b>Domain:</b> '.$sheet->{'udom'}.'<br />');
3040: }
3041: if ($sheet->{'sheettype'} eq 'studentcalc' ||
3042: $sheet->{'sheettype'} eq 'assesscalc') {
3043: $r->print('<b>Section/Group:</b>'.$sheet->{'csec'}.'</p>');
3044: }
3045: #
3046: # If a new formula had been entered, go from work copy
3047: if ($ENV{'form.unewfield'}) {
3048: $r->print('<h2>Modified Workcopy</h2>');
3049: $ENV{'form.unewformula'}=~s/\'/\"/g;
3050: $r->print('<p>New formula: '.$ENV{'form.unewfield'}.'='.
3051: $ENV{'form.unewformula'}.'<p>');
3052: $sheet->{'filename'} = $ENV{'form.ufn'};
3053: &tmpread($sheet,$ENV{'form.unewfield'},$ENV{'form.unewformula'});
3054: } elsif ($ENV{'form.saveas'}) {
3055: $sheet->{'filename'} = $ENV{'form.ufn'};
3056: &tmpread($sheet);
3057: } else {
3058: &readsheet($sheet,$ENV{'form.ufn'});
3059: }
3060: # Additional options
3061: if ($sheet->{'sheettype'} eq 'assesscalc') {
3062: $r->print('<p><font size=+2>'.
3063: '<a href="/adm/studentcalc?'.
3064: 'uname='.$sheet->{'uname'}.
3065: '&udom='.$sheet->{'udom'}.'">'.
3066: 'Level up: Student Sheet</a></font></p>');
3067: }
3068: if (($sheet->{'sheettype'} eq 'studentcalc') &&
3069: (&Apache::lonnet::allowed('vgr',$sheet->{'cid'}))) {
3070: $r->print ('<p><font size=+2><a href="/adm/classcalc">'.
3071: 'Level up: Course Sheet</a></font></p>');
3072: }
3073: # Recalc button
3074: $r->print('<br />'.
3075: '<input type="submit" name="forcerecalc" '.
3076: 'value="Completely Recalculate Sheet"></p>');
3077: # Save dialog
3078: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
3079: my $fname=$ENV{'form.ufn'};
3080: $fname=~s/\_[^\_]+$//;
3081: if ($fname eq 'default') { $fname='course_default'; }
3082: $r->print('<input type=submit name=saveas value="Save as ...">'.
3083: '<input type=text size=20 name=newfn value="'.$fname.'">'.
3084: 'make default: <input type=checkbox name="makedefufn"><p>');
3085: }
3086: $r->print(&hiddenfield('ufn',$sheet->{'filename'}));
3087: # Load dialog
3088: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
3089: $r->print('<p><input type=submit name=load value="Load ...">'.
3090: '<select name="loadthissheet">'.
3091: '<option name="default">Default</option>');
3092: foreach (&othersheets($sheet)) {
3093: $r->print('<option name="'.$_.'"');
3094: if ($ENV{'form.ufn'} eq $_) {
3095: $r->print(' selected');
3096: }
3097: $r->print('>'.$_.'</option>');
3098: }
3099: $r->print('</select><p>');
3100: if ($sheet->{'sheettype'} eq 'studentcalc') {
3101: &setothersheets($sheet,
3102: &othersheets($sheet,'assesscalc'));
3103: }
3104: }
3105: #
3106: # Set up caching mechanisms
3107: #
3108: &load_spreadsheet_expirationdates();
3109: # Clear out old caches if we have not seen this class before.
3110: if (exists($oldsheets{'course'}) &&
3111: $oldsheets{'course'} ne $sheet->{'cid'}) {
3112: undef %oldsheets;
3113: undef %loadedcaches;
3114: }
3115: $oldsheets{'course'} = $sheet->{'cid'};
3116: #
3117: if ($sheet->{'sheettype'} eq 'classcalc') {
3118: $r->print("Loading previously calculated student sheets ...\n");
3119: $r->rflush();
3120: &cachedcsheets();
3121: } elsif ($sheet->{'sheettype'} eq 'studentcalc') {
3122: $r->print("Loading previously calculated assessment sheets ...\n");
3123: $r->rflush();
3124: &cachedssheets($sheet);
3125: }
3126: # Update sheet, load rows
3127: $r->print("Loaded sheet(s), updating rows ...<br>\n");
3128: $r->rflush();
3129: #
3130: &updatesheet($sheet);
3131: $r->print("Updated rows, loading row data ...\n");
3132: $r->rflush();
3133: #
3134: &loadrows($sheet,$r);
3135: $r->print("Loaded row data, calculating sheet ...<br>\n");
3136: $r->rflush();
3137: #
3138: my $calcoutput=&calcsheet($sheet);
3139: $r->print('<h3><font color=red>'.$calcoutput.'</h3></font>');
3140: # See if something to save
3141: if (&Apache::lonnet::allowed('opa',$ENV{'request.course.id'})) {
3142: my $fname='';
3143: if ($ENV{'form.saveas'} && ($fname=$ENV{'form.newfn'})) {
3144: $fname=~s/\W/\_/g;
3145: if ($fname eq 'default') { $fname='course_default'; }
3146: $fname.='_'.$sheet->{'sheettype'};
3147: $sheet->{'filename'} = $fname;
3148: $ENV{'form.ufn'}=$fname;
3149: $r->print('<p>Saving spreadsheet: '.
3150: &writesheet($sheet,$ENV{'form.makedefufn'}).
3151: '<p>');
3152: }
3153: }
3154: #
3155: # Write the modified worksheet
3156: $r->print('<b>Current sheet:</b> '.$sheet->{'filename'}.'</p>');
3157: &tmpwrite($sheet);
3158: if ($sheet->{'sheettype'} eq 'assesscalc') {
3159: $r->print('<p>Show rows with empty A column: ');
3160: } else {
3161: $r->print('<p>Show empty rows: ');
3162: }
3163: #
3164: $r->print(&hiddenfield('userselhidden','true').
3165: '<input type="checkbox" name="showall" onClick="submit()"');
3166: #
3167: if ($ENV{'form.showall'}) {
3168: $r->print(' checked');
3169: } else {
3170: unless ($ENV{'form.userselhidden'}) {
3171: unless
3172: ($ENV{'course.'.$sheet->{'cid'}.'.hideemptyrows'} eq 'yes') {
3173: $r->print(' checked');
3174: $ENV{'form.showall'}=1;
3175: }
3176: }
3177: }
3178: $r->print('>');
3179: #
3180: # CSV format checkbox (classcalc sheets only)
3181: $r->print(' Output as <select name="output" size="1" onClick="submit()">'.
3182: "\n");
3183: foreach my $mode (qw/HTML CSV Excel/) {
3184: $r->print('<option value="'.$mode.'"');
3185: if ($ENV{'form.output'} eq $mode) {
3186: $r->print(' selected ');
3187: }
3188: $r->print('>'.$mode.'</option>'."\n");
3189: }
3190: if ($sheet->{'sheettype'} eq 'classcalc') {
3191: $r->print('<option value="recursive excel"');
3192: if ($ENV{'form.output'} eq 'recursive excel') {
3193: $r->print(' selected ');
3194: }
3195: $r->print(">Multi-Sheet Excel</option>\n");
3196: }
3197: $r->print("</select>\n");
3198: #
3199: if ($sheet->{'sheettype'} eq 'classcalc') {
3200: $r->print(' Student Status: '.
3201: &Apache::lonhtmlcommon::StatusOptions
3202: ($ENV{'form.Status'},'sheet'));
3203: }
3204: #
3205: # Buttons to insert rows
3206: # $r->print(<<ENDINSERTBUTTONS);
3207: #<br>
3208: #<input type='button' onClick='insertrow("top");'
3209: #value='Insert Row Top'>
3210: #<input type='button' onClick='insertrow("bottom");'
3211: #value='Insert Row Bottom'><br>
3212: #ENDINSERTBUTTONS
3213: # Print out sheet
3214: &outsheet($r,$sheet);
3215: $r->print('</form></body></html>');
3216: # Done
3217: return OK;
3218: }
3219:
3220: 1;
3221: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>