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