Annotation of loncom/interface/spreadsheet/Spreadsheet.pm, revision 1.11
1.1 matthew 1: #
1.11 ! matthew 2: # $Id: Spreadsheet.pm,v 1.10 2003/05/28 17:38:57 matthew Exp $
1.1 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: #
26: # The LearningOnline Network with CAPA
27: # Spreadsheet/Grades Display Handler
28: #
29: # POD required stuff:
30:
31: =head1 NAME
32:
33: Spreadsheet
34:
35: =head1 SYNOPSIS
36:
37: =head1 DESCRIPTION
38:
39: =over 4
40:
41: =cut
42:
43: ###################################################
44: ###################################################
45: ### Spreadsheet ###
46: ###################################################
47: ###################################################
48: package Apache::Spreadsheet;
49:
50: use strict;
51: use Apache::Constants qw(:common :http);
52: use Apache::lonnet;
53: use Safe;
54: use Safe::Hole;
55: use Opcode;
56: use HTML::Entities();
57: use HTML::TokeParser;
58: use Spreadsheet::WriteExcel;
59: use Time::HiRes;
60:
61: ##
62: ## Package Variables
63: ##
64: my %expiredates;
65:
66: my @UC_Columns = split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
67: my @LC_Columns = split(//,'abcdefghijklmnopqrstuvwxyz');
68:
69: ######################################################
70:
71: =pod
72:
73: =item &new
74:
75: Returns a new spreadsheet object.
76:
77: =cut
78:
79: ######################################################
80: sub new {
81: my $this = shift;
82: my $class = ref($this) || $this;
83: my ($stype) = ($class =~ /Apache::(.*)$/);
84: #
85: my ($name,$domain,$filename,$usymb)=@_;
86: #
87: my $self = {
88: name => $name,
89: domain => $domain,
90: type => $stype,
91: symb => $usymb,
92: errorlog => '',
93: maxrow => '',
94: cid => $ENV{'request.course.id'},
95: cnum => $ENV{'course.'.$ENV{'request.course.id'}.'.num'},
96: cdom => $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
97: chome => $ENV{'course.'.$ENV{'request.course.id'}.'.home'},
98: coursedesc => $ENV{'course.'.$ENV{'request.course.id'}.'.description'},
99: coursefilename => $ENV{'request.course.fn'},
1.4 matthew 100: temporary => '',
1.1 matthew 101: #
1.3 matthew 102: # blackout is used to determine if any data needs to be hidden from the
103: # student.
104: blackout => 0,
105: #
1.1 matthew 106: # Data storage
107: formulas => {},
108: constants => {},
109: rows => [],
110: row_source => {},
111: othersheets => [],
112: };
113: #
114: $self->{'uhome'} = &Apache::lonnet::homeserver($name,$domain);
115: #
116: bless($self,$class);
117: #
118: # Load in the spreadsheet definition
119: $self->filename($filename);
120: if (exists($ENV{'form.workcopy'}) &&
121: $self->{'type'} eq $ENV{'form.workcopy'}) {
122: $self->load_tmp();
123: } else {
124: $self->load();
125: }
126: return $self;
127: }
128:
129: ######################################################
130:
131: =pod
132:
133: =item &filename
134:
135: get or set the filename for a spreadsheet.
136:
137: =cut
138:
139: ######################################################
140: sub filename {
141: my $self = shift();
142: if (@_) {
143: my ($newfilename) = @_;
144: if (! defined($newfilename) || $newfilename eq 'Default' ||
1.8 matthew 145: $newfilename !~ /\w/) {
1.1 matthew 146: my %tmphash = &Apache::lonnet::get('environment',
147: ['spreadsheet_default_'.
148: $self->{'type'}],
149: $self->{'cdom'},
150: $self->{'cnum'});
151: my ($tmp) = keys(%tmphash);
152: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
153: $newfilename=$tmphash{'spreadsheet_default_'.$self->{'type'}};
154: }
1.8 matthew 155: if (! defined($newfilename) ||
156: $newfilename !~ /\w/ ||
157: $newfilename =~ /^\W*$/) {
158: $newfilename = 'default.'.$self->{'type'};
159: }
1.9 matthew 160: } elsif ($newfilename !~ /^\/res\/.*\.spreadsheet/ &&
161: $newfilename !~ /^default\.$self->{'type'}$/ ) {
1.1 matthew 162: my $regexp = '_'.$self->{'type'}.'$';
163: if ($newfilename !~ /$regexp/) {
164: $newfilename .= '_'.$self->{'type'};
165: }
166: }
167: $self->{'filename'} = $newfilename;
168: return;
169: }
170: return $self->{'filename'};
171: }
172:
173: ######################################################
174:
175: =pod
176:
177: =item &make_default()
178:
179: Make the current spreadsheet file the default for the course. Expires all the
180: default spreadsheets.......!
181:
182: =cut
183:
184: ######################################################
185: sub make_default {
186: my $self = shift();
187: my $result = &Apache::lonnet::put('environment',
188: {'spreadsheet_default_'.$self->{'type'} => $self->filename()},
189: $self->{'cdom'},$self->{'cnum'});
190: return $result if ($result ne 'ok');
191: my $symb = $self->{'symb'};
192: $symb = '' if (! defined($symb));
193: &Apache::lonnet::expirespread('','',$self->{'type'},$symb);
194: }
195:
196: ######################################################
197:
198: =pod
199:
200: =item &is_default()
201:
202: Returns 1 if the current spreadsheet is the default as specified in the
203: course environment. Returns 0 otherwise.
204:
205: =cut
206:
207: ######################################################
208: sub is_default {
209: my $self = shift;
210: # Check to find out if we are the default spreadsheet (filenames match)
211: my $default_filename = '';
212: my %tmphash = &Apache::lonnet::get('environment',
213: ['spreadsheet_default_'.
214: $self->{'type'}],
215: $self->{'cdom'},
216: $self->{'cnum'});
217: my ($tmp) = keys(%tmphash);
218: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
219: $default_filename = $tmphash{'spreadsheet_default_'.$self->{'type'}};
220: }
221: return 1 if ($self->filename() eq $default_filename);
222: return 0;
1.11 ! matthew 223: }
! 224:
! 225: sub initialize {
! 226: # This method is here to remind you that it will be overridden by
! 227: # the descendents of the spreadsheet class.
1.1 matthew 228: }
229:
230: sub initialize_spreadsheet_package {
231: &load_spreadsheet_expirationdates();
232: &clear_spreadsheet_definition_cache();
233: }
234:
235: sub load_spreadsheet_expirationdates {
236: undef %expiredates;
237: my $cid=$ENV{'request.course.id'};
238: my @tmp = &Apache::lonnet::dump('nohist_expirationdates',
239: $ENV{'course.'.$cid.'.domain'},
240: $ENV{'course.'.$cid.'.num'});
241: if (lc($tmp[0]) !~ /^error/){
242: %expiredates = @tmp;
243: }
244: }
245:
246: sub check_expiration_time {
247: my $self = shift;
248: my ($time)=@_;
249: my ($key1,$key2,$key3,$key4);
250: $key1 = '::'.$self->{'type'}.':';
251: $key2 = $self->{'name'}.':'.$self->{'domain'}.':'.$self->{'type'}.':';
252: $key3 = $key2.$self->{'container'} if (defined($self->{'container'}));
253: $key4 = $key2.$self->{'usymb'} if (defined($self->{'usymb'}));
254: foreach my $key ($key1,$key2,$key3,$key4) {
255: next if (! defined($key));
256: if (exists($expiredates{$key}) &&$expiredates{$key} > $time) {
257: return 0;
258: }
259: }
260: return 1;
261: }
262:
263: ######################################################
264:
265: =pod
266:
267: =item &initialize_safe_space
268:
269: Returns the safe space required by a Spreadsheet object.
270:
271: =head 2 Safe Space Functions
272:
273: =over 4
274:
275: =cut
276:
277: ######################################################
278: sub initialize_safe_space {
279: my $self = shift;
280: my $safeeval = new Safe(shift);
281: my $safehole = new Safe::Hole;
282: $safeeval->permit("entereval");
283: $safeeval->permit(":base_math");
284: $safeeval->permit("sort");
285: $safeeval->deny(":base_io");
286: $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&EXT');
287: $safehole->wrap(\&mask,$safeeval,'&mask');
288: $safeeval->share('$@');
289: my $code=<<'ENDDEFS';
290: # ---------------------------------------------------- Inside of the safe space
291: #
292: # f: formulas
293: # t: intermediate format (variable references expanded)
294: # v: output values
295: # c: preloaded constants (A-column)
296: # rl: row label
297: # os: other spreadsheets (for student spreadsheet only)
298: undef %sheet_values; # Holds the (computed, final) values for the sheet
299: # This is only written to by &calc, the spreadsheet computation routine.
300: # It is read by many functions
301: undef %t; # Holds the values of the spreadsheet temporarily. Set in &sett,
302: # which does the translation of strings like C5 into the value in C5.
303: # Used in &calc - %t holds the values that are actually eval'd.
304: undef %f; # Holds the formulas for each cell. This is the users
305: # (spreadsheet authors) data for each cell.
306: undef %c; # Holds the constants for a sheet. In the assessment
307: # sheets, this is the A column. Used in &MINPARM, &MAXPARM, &expandnamed,
308: # &sett, and &constants. There is no &getconstants.
309: # &constants is called by &loadstudent, &loadcourse, &load assessment,
310: undef @os; # Holds the names of other spreadsheets - this is used to specify
311: # the spreadsheets that are available for the assessment sheet.
312: # Set by &setothersheets. &setothersheets is called by &handler. A
313: # related subroutine is &othersheets.
314: $errorlog = '';
315: #
316: $maxrow = 0;
317: $type = '';
318: #
319: # filename/reference of the sheet
320: $filename = '';
321: #
322: # user data
323: $name = '';
324: $uhome = '';
325: $domain = '';
326: #
327: # course data
328: $csec = '';
329: $chome= '';
330: $cnum = '';
331: $cdom = '';
332: $cid = '';
333: $coursefilename = '';
334: #
335: # symb
336: $usymb = '';
337: #
338: # error messages
339: $errormsg = '';
340: #
341: #-------------------------------------------------------
342:
343: =pod
344:
345: =item NUM(range)
346:
347: returns the number of items in the range.
348:
349: =cut
350:
351: #-------------------------------------------------------
352: sub NUM {
353: my $mask=&mask(@_);
354: my $num= $#{@{grep(/$mask/,keys(%sheet_values))}}+1;
355: return $num;
356: }
357:
358: #-------------------------------------------------------
359:
360: =pod
361:
362: =item BIN(low,high,lower,upper)
363:
364: =cut
365:
366: #-------------------------------------------------------
367: sub BIN {
368: my ($low,$high,$lower,$upper)=@_;
369: my $mask=&mask($lower,$upper);
370: my $num=0;
371: foreach (grep /$mask/,keys(%sheet_values)) {
372: if (($sheet_values{$_}>=$low) && ($sheet_values{$_}<=$high)) {
373: $num++;
374: }
375: }
376: return $num;
377: }
378:
379: #-------------------------------------------------------
380:
381: =pod
382:
383: =item SUM(range)
384:
385: returns the sum of items in the range.
386:
387: =cut
388:
389: #-------------------------------------------------------
390: sub SUM {
391: my $mask=&mask(@_);
392: my $sum=0;
393: foreach (grep /$mask/,keys(%sheet_values)) {
394: $sum+=$sheet_values{$_};
395: }
396: return $sum;
397: }
398:
399: #-------------------------------------------------------
400:
401: =pod
402:
403: =item MEAN(range)
404:
405: compute the average of the items in the range.
406:
407: =cut
408:
409: #-------------------------------------------------------
410: sub MEAN {
411: my $mask=&mask(@_);
412: my $sum=0;
413: my $num=0;
414: foreach (grep /$mask/,keys(%sheet_values)) {
415: $sum+=$sheet_values{$_};
416: $num++;
417: }
418: if ($num) {
419: return $sum/$num;
420: } else {
421: return undef;
422: }
423: }
424:
425: #-------------------------------------------------------
426:
427: =pod
428:
429: =item STDDEV(range)
430:
431: compute the standard deviation of the items in the range.
432:
433: =cut
434:
435: #-------------------------------------------------------
436: sub STDDEV {
437: my $mask=&mask(@_);
438: my $sum=0; my $num=0;
439: foreach (grep /$mask/,keys(%sheet_values)) {
440: $sum+=$sheet_values{$_};
441: $num++;
442: }
443: unless ($num>1) { return undef; }
444: my $mean=$sum/$num;
445: $sum=0;
446: foreach (grep /$mask/,keys(%sheet_values)) {
447: $sum+=($sheet_values{$_}-$mean)**2;
448: }
449: return sqrt($sum/($num-1));
450: }
451:
452: #-------------------------------------------------------
453:
454: =pod
455:
456: =item PROD(range)
457:
458: compute the product of the items in the range.
459:
460: =cut
461:
462: #-------------------------------------------------------
463: sub PROD {
464: my $mask=&mask(@_);
465: my $prod=1;
466: foreach (grep /$mask/,keys(%sheet_values)) {
467: $prod*=$sheet_values{$_};
468: }
469: return $prod;
470: }
471:
472: #-------------------------------------------------------
473:
474: =pod
475:
476: =item MAX(range)
477:
478: compute the maximum of the items in the range.
479:
480: =cut
481:
482: #-------------------------------------------------------
483: sub MAX {
484: my $mask=&mask(@_);
485: my $max='-';
486: foreach (grep /$mask/,keys(%sheet_values)) {
487: unless ($max) { $max=$sheet_values{$_}; }
488: if (($sheet_values{$_}>$max) || ($max eq '-')) {
489: $max=$sheet_values{$_};
490: }
491: }
492: return $max;
493: }
494:
495: #-------------------------------------------------------
496:
497: =pod
498:
499: =item MIN(range)
500:
501: compute the minimum of the items in the range.
502:
503: =cut
504:
505: #-------------------------------------------------------
506: sub MIN {
507: my $mask=&mask(@_);
508: my $min='-';
509: foreach (grep /$mask/,keys(%sheet_values)) {
510: unless ($max) { $max=$sheet_values{$_}; }
511: if (($sheet_values{$_}<$min) || ($min eq '-')) {
512: $min=$sheet_values{$_};
513: }
514: }
515: return $min;
516: }
517:
518: #-------------------------------------------------------
519:
520: =pod
521:
522: =item SUMMAX(num,lower,upper)
523:
524: compute the sum of the largest 'num' items in the range from
525: 'lower' to 'upper'
526:
527: =cut
528:
529: #-------------------------------------------------------
530: sub SUMMAX {
531: my ($num,$lower,$upper)=@_;
532: my $mask=&mask($lower,$upper);
533: my @inside=();
534: foreach (grep /$mask/,keys(%sheet_values)) {
535: push (@inside,$sheet_values{$_});
536: }
537: @inside=sort(@inside);
538: my $sum=0; my $i;
539: for ($i=$#inside;(($i>$#inside-$num) && ($i>=0));$i--) {
540: $sum+=$inside[$i];
541: }
542: return $sum;
543: }
544:
545: #-------------------------------------------------------
546:
547: =pod
548:
549: =item SUMMIN(num,lower,upper)
550:
551: compute the sum of the smallest 'num' items in the range from
552: 'lower' to 'upper'
553:
554: =cut
555:
556: #-------------------------------------------------------
557: sub SUMMIN {
558: my ($num,$lower,$upper)=@_;
559: my $mask=&mask($lower,$upper);
560: my @inside=();
561: foreach (grep /$mask/,keys(%sheet_values)) {
562: $inside[$#inside+1]=$sheet_values{$_};
563: }
564: @inside=sort(@inside);
565: my $sum=0; my $i;
566: for ($i=0;(($i<$num) && ($i<=$#inside));$i++) {
567: $sum+=$inside[$i];
568: }
569: return $sum;
570: }
571:
572: #-------------------------------------------------------
573:
574: =pod
575:
576: =item MINPARM(parametername)
577:
578: Returns the minimum value of the parameters matching the parametername.
579: parametername should be a string such as 'duedate'.
580:
581: =cut
582:
583: #-------------------------------------------------------
584: sub MINPARM {
585: my ($expression) = @_;
586: my $min = undef;
587: study($expression);
588: foreach $parameter (keys(%c)) {
589: next if ($parameter !~ /$expression/);
590: if ((! defined($min)) || ($min > $c{$parameter})) {
591: $min = $c{$parameter}
592: }
593: }
594: return $min;
595: }
596:
597: #-------------------------------------------------------
598:
599: =pod
600:
601: =item MAXPARM(parametername)
602:
603: Returns the maximum value of the parameters matching the input parameter name.
604: parametername should be a string such as 'duedate'.
605:
606: =cut
607:
608: #-------------------------------------------------------
609: sub MAXPARM {
610: my ($expression) = @_;
611: my $max = undef;
612: study($expression);
613: foreach $parameter (keys(%c)) {
614: next if ($parameter !~ /$expression/);
615: if ((! defined($min)) || ($max < $c{$parameter})) {
616: $max = $c{$parameter}
617: }
618: }
619: return $max;
620: }
621:
622:
623: sub calc {
624: %sheet_values = %t;
625: my $notfinished = 1;
626: my $lastcalc = '';
627: my $depth = 0;
628: while ($notfinished) {
629: $notfinished=0;
630: while (my ($cell,$value) = each(%t)) {
631: my $old=$sheet_values{$cell};
632: $sheet_values{$cell}=eval $value;
633: # $errorlog .= $cell.' = '.$old.'->'.$sheet_values{$cell}."\n";
634: if ($@) {
635: undef %sheet_values;
636: return $cell.': '.$@;
637: }
638: if ($sheet_values{$cell} ne $old) {
639: $notfinished=1;
640: $lastcalc=$cell;
641: }
642: }
643: # $errorlog.="------------------------------------------------";
644:
645: $depth++;
646: if ($depth>100) {
647: undef %sheet_values;
648: return $lastcalc.': Maximum calculation depth exceeded';
649: }
650: }
651: return '';
652: }
653:
654: # ------------------------------------------- End of "Inside of the safe space"
655: ENDDEFS
656: $safeeval->reval($code);
657: $self->{'safe'} = $safeeval;
658: $self->{'root'} = $self->{'safe'}->root();
659: #
660: # Place some of the %$self items into the safe space except the safe space
661: # itself
662: my $initstring = '';
663: foreach (qw/name domain type usymb cid csec coursefilename
664: cnum cdom chome uhome/) {
665: $initstring.= qq{\$$_="$self->{$_}";};
666: }
667: $self->{'safe'}->reval($initstring);
668: return $self;
669: }
670: ######################################################
671:
672: =pod
673:
674: =back
675:
676: =cut
677:
678: ######################################################
679:
680:
681: ######################################################
682:
683:
684: ######################################################
685: {
686:
687: my %memoizer;
688:
689: sub mask {
690: my ($lower,$upper)=@_;
691: my $key = $lower.'_'.$upper;
692: if (exists($memoizer{$key})) {
693: return $memoizer{$key};
694: }
695: $upper = $lower if (! defined($upper));
696: #
697: my ($la,$ld) = ($lower=~/([A-Za-z]|\*)(\d+|\*)/);
698: my ($ua,$ud) = ($upper=~/([A-Za-z]|\*)(\d+|\*)/);
699: #
700: my $alpha='';
701: my $num='';
702: #
703: if (($la eq '*') || ($ua eq '*')) {
704: $alpha='[A-Za-z]';
705: } else {
706: if (($la=~/[A-Z]/) && ($ua=~/[A-Z]/) ||
707: ($la=~/[a-z]/) && ($ua=~/[a-z]/)) {
708: $alpha='['.$la.'-'.$ua.']';
709: } else {
710: $alpha='['.$la.'-Za-'.$ua.']';
711: }
712: }
713: if (($ld eq '*') || ($ud eq '*')) {
714: $num='\d+';
715: } else {
716: if (length($ld)!=length($ud)) {
717: $num.='(';
718: foreach ($ld=~m/\d/g) {
719: $num.='['.$_.'-9]';
720: }
721: if (length($ud)-length($ld)>1) {
722: $num.='|\d{'.(length($ld)+1).','.(length($ud)-1).'}';
723: }
724: $num.='|';
725: foreach ($ud=~m/\d/g) {
726: $num.='[0-'.$_.']';
727: }
728: $num.=')';
729: } else {
730: my @lda=($ld=~m/\d/g);
731: my @uda=($ud=~m/\d/g);
732: my $i;
733: my $j=0;
734: my $notdone=1;
735: for ($i=0;($i<=$#lda)&&($notdone);$i++) {
736: if ($lda[$i]==$uda[$i]) {
737: $num.=$lda[$i];
738: $j=$i;
739: } else {
740: $notdone=0;
741: }
742: }
743: if ($j<$#lda-1) {
744: $num.='('.$lda[$j+1];
745: for ($i=$j+2;$i<=$#lda;$i++) {
746: $num.='['.$lda[$i].'-9]';
747: }
748: if ($uda[$j+1]-$lda[$j+1]>1) {
749: $num.='|['.($lda[$j+1]+1).'-'.($uda[$j+1]-1).']\d{'.
750: ($#lda-$j-1).'}';
751: }
752: $num.='|'.$uda[$j+1];
753: for ($i=$j+2;$i<=$#uda;$i++) {
754: $num.='[0-'.$uda[$i].']';
755: }
756: $num.=')';
757: } else {
758: if ($lda[-1]!=$uda[-1]) {
759: $num.='['.$lda[-1].'-'.$uda[-1].']';
760: }
761: }
762: }
763: }
764: my $expression ='^'.$alpha.$num."\$";
765: $memoizer{$key} = $expression;
766: return $expression;
767: }
768:
769: }
770:
771: ##
772: ## sub add_hash_to_safe {} # spreadsheet, would like to destroy
773: ##
774:
775: #
776: # expandnamed used to reside in the safe space
777: #
778: sub expandnamed {
779: my $self = shift;
780: my $expression=shift;
781: if ($expression=~/^\&/) {
782: my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/);
783: my @vars=split(/\W+/,$formula);
784: my %values=();
785: foreach my $varname ( @vars ) {
786: if ($varname=~/\D/) {
787: $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
788: $varname=~s/$var/\([\\w:\\- ]\+\)/g;
789: foreach (keys(%{$self->{'constants'}})) {
790: if ($_=~/$varname/) {
791: $values{$1}=1;
792: }
793: }
794: }
795: }
796: if ($func eq 'EXPANDSUM') {
797: my $result='';
798: foreach (keys(%values)) {
799: my $thissum=$formula;
800: $thissum=~s/$var/$_/g;
801: $result.=$thissum.'+';
802: }
803: $result=~s/\+$//;
804: return $result;
805: } else {
806: return 0;
807: }
808: } else {
809: # it is not a function, so it is a parameter name
810: # We should do the following:
811: # 1. Take the list of parameter names
812: # 2. look through the list for ones that match the parameter we want
813: # 3. If there are no collisions, return the one that matches
814: # 4. If there is a collision, return 'bad parameter name error'
815: my $returnvalue = '';
816: my @matches = ();
817: $#matches = -1;
818: study $expression;
819: my $parameter;
820: foreach $parameter (keys(%{$self->{'constants'}})) {
821: push @matches,$parameter if ($parameter =~ /$expression/);
822: }
823: if (scalar(@matches) == 0) {
1.10 matthew 824: $returnvalue = '""';#'"unmatched parameter: '.$parameter.'"';
1.1 matthew 825: } elsif (scalar(@matches) == 1) {
826: # why do we not do this lookup here, instead of delaying it?
827: $returnvalue = '$c{\''.$matches[0].'\'}';
828: } elsif (scalar(@matches) > 0) {
829: # more than one match. Look for a concise one
830: $returnvalue = "'non-unique parameter name : $expression'";
831: foreach (@matches) {
832: if (/^$expression$/) {
833: # why do we not do this lookup here?
834: $returnvalue = '$c{\''.$_.'\'}';
835: }
836: }
837: } else {
838: # There was a negative number of matches, which indicates
839: # something is wrong with reality. Better warn the user.
1.10 matthew 840: $returnvalue = '"bizzare parameter: '.$parameter.'"';
1.1 matthew 841: }
842: return $returnvalue;
843: }
844: }
845:
846: sub sett {
847: my $self = shift;
848: my %t=();
849: #
850: # Deal with the template row
851: foreach my $col ($self->template_cells()) {
852: next if ($col=~/^[A-Z]/);
853: foreach my $row ($self->rows()) {
854: # Get the name of this cell
855: my $cell=$col.$row;
856: # Grab the template declaration
857: $t{$cell}=$self->formula('template_'.$col);
858: # Replace '#' with the row number
859: $t{$cell}=~s/\#/$row/g;
860: # Replace '....' with ','
861: $t{$cell}=~s/\.\.+/\,/g;
862: # Replace 'A0' with the value from 'A0'
863: $t{$cell}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
864: # Replace parameters
865: $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
866: }
867: }
868: #
869: # Deal with the normal cells
870: while (my($cell,$formula) = each(%{$self->{'formulas'}})) {
871: next if ($_=~/^template\_/);
872: my ($col,$row) = ($cell =~ /^([A-z])(\d+)$/);
873: if ($row eq '0') {
874: $t{$cell}=$formula;
875: $t{$cell}=~s/\.\.+/\,/g;
876: $t{$cell}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
877: $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
878: } elsif ( $col =~ /^[A-Z]$/ ) {
879: if ($formula !~ /^\!/ && exists($self->{'constants'}->{$cell})) {
880: my $data = $self->{'constants'}->{$cell};
881: $t{$cell} = $data;
882: }
883: } else { # $row > 1 and $col =~ /[a-z]
884: $t{$cell}=$formula;
885: $t{$cell}=~s/\.\.+/\,/g;
886: $t{$cell}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
887: $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
888: }
889: }
890: %{$self->{'safe'}->varglob('t')}=%t;
891: }
892:
893: ##
894: ## sync_safe_space: Called by calcsheet to make sure all the data we
895: # need to calculate is placed into the safe space
896: ##
897: sub sync_safe_space {
898: my $self = shift;
899: # Inside the safe space 'formulas' has a diabolical alter-ego named 'f'.
900: %{$self->{'safe'}->varglob('f')}=%{$self->{'formulas'}};
901: # 'constants' leads a peaceful hidden life of 'c'.
902: %{$self->{'safe'}->varglob('c')}=%{$self->{'constants'}};
903: # 'othersheets' hides as 'os', a disguise few can penetrate.
904: @{$self->{'safe'}->varglob('os')}=@{$self->{'othersheets'}};
905: }
906:
907: ##
908: ## Retrieve the error log from the safe space (used for debugging)
909: ##
910: sub get_errorlog {
911: my $self = shift;
912: $self->{'errorlog'} = $ { $self->{'safe'}->varglob('errorlog') };
913: return $self->{'errorlog'};
914: }
915:
916: ##
917: ## Clear the error log inside the safe space
918: ##
919: sub clear_errorlog {
920: my $self = shift;
921: $ {$self->{'safe'}->varglob('errorlog')} = '';
922: $self->{'errorlog'} = '';
923: }
924:
925: ##
926: ## constants: either set or get the constants
927: ##
928: sub constants {
929: my $self=shift;
930: my ($constants) = @_;
931: if (defined($constants)) {
932: if (! ref($constants)) {
933: my %tmp = @_;
934: $constants = \%tmp;
935: }
936: $self->{'constants'} = $constants;
937: return;
938: } else {
939: return %{$self->{'constants'}};
940: }
941: }
942:
943: ##
944: ## formulas: either set or get the formulas
945: ##
946: sub formulas {
947: my $self=shift;
948: my ($formulas) = @_;
949: if (defined($formulas)) {
950: if (! ref($formulas)) {
951: my %tmp = @_;
952: $formulas = \%tmp;
953: }
954: $self->{'formulas'} = $formulas;
955: $self->{'rows'} = [];
956: $self->{'template_cells'} = [];
957: return;
958: } else {
959: return %{$self->{'formulas'}};
960: }
961: }
962:
963: sub set_formula {
964: my $self = shift;
965: my ($cell,$formula) = @_;
966: $self->{'formulas'}->{$cell}=$formula;
967: return;
968: }
969:
970: ##
971: ## formulas_keys: Return the keys to the formulas hash.
972: ##
973: sub formulas_keys {
974: my $self = shift;
975: my @keys = keys(%{$self->{'formulas'}});
976: return keys(%{$self->{'formulas'}});
977: }
978:
979: ##
980: ## formula: Return the formula for a given cell in the spreadsheet
981: ## returns '' if the cell does not have a formula or does not exist
982: ##
983: sub formula {
984: my $self = shift;
985: my $cell = shift;
986: if (defined($cell) && exists($self->{'formulas'}->{$cell})) {
987: return $self->{'formulas'}->{$cell};
988: }
989: return '';
990: }
991:
992: ##
993: ## logthis: write the input to lonnet.log
994: ##
995: sub logthis {
996: my $self = shift;
997: my $message = shift;
998: &Apache::lonnet::logthis($self->{'type'}.':'.
999: $self->{'name'}.':'.$self->{'domain'}.':'.
1000: $message);
1001: return;
1002: }
1003:
1004: ##
1005: ## dump_formulas_to_log: makes lonnet.log huge...
1006: ##
1007: sub dump_formulas_to_log {
1008: my $self =shift;
1009: $self->logthis("Spreadsheet formulas");
1010: $self->logthis("--------------------------------------------------------");
1011: while (my ($cell, $formula) = each(%{$self->{'formulas'}})) {
1012: $self->logthis(' '.$cell.' = '.$formula);
1013: }
1014: $self->logthis("--------------------------------------------------------");}
1015:
1016: ##
1017: ## value: returns the computed value of a particular cell
1018: ##
1019: sub value {
1020: my $self = shift;
1021: my $cell = shift;
1022: if (defined($cell) && exists($self->{'values'}->{$cell})) {
1023: return $self->{'values'}->{$cell};
1024: }
1025: return '';
1026: }
1027:
1028: ##
1029: ## dump_values_to_log: makes lonnet.log huge...
1030: ##
1031: sub dump_values_to_log {
1032: my $self =shift;
1033: $self->logthis("Spreadsheet Values");
1034: $self->logthis("------------------------------------------------------");
1035: while (my ($cell, $value) = each(%{$self->{'values'}})) {
1036: $self->logthis(' '.$cell.' = '.$value);
1037: }
1038: $self->logthis("------------------------------------------------------");
1039: }
1040:
1041: ##
1042: ## Yet another debugging function
1043: ##
1044: sub dump_hash_to_log {
1045: my $self= shift();
1046: my %tmp = @_;
1047: if (@_<2) {
1048: %tmp = %{$_[0]};
1049: }
1050: $self->logthis('---------------------------- (begin hash dump)');
1051: while (my ($key,$val) = each (%tmp)) {
1052: $self->logthis(' '.$key.' = '.$val.':');
1053: }
1054: $self->logthis('---------------------------- (finished hash dump)');
1055: }
1056:
1057: ##
1058: ## rebuild_stats: rebuilds the rows and template_cells arrays
1059: ##
1060: sub rebuild_stats {
1061: my $self = shift;
1062: $self->{'rows'}=[];
1063: $self->{'template_cells'}=[];
1064: while (my ($cell,$formula) = each(%{$self->{'formulas'}})) {
1065: push(@{$self->{'rows'}},$1) if ($cell =~ /^A(\d+)/ && $1 != 0);
1066: push(@{$self->{'template_cells'}},$1) if ($cell =~ /^template_(\w+)/);
1067: }
1068: return;
1069: }
1070:
1071: ##
1072: ## template_cells returns a list of the cells defined in the template row
1073: ##
1074: sub template_cells {
1075: my $self = shift;
1076: $self->rebuild_stats() if (! defined($self->{'template_cells'}) ||
1077: ! @{$self->{'template_cells'}});
1078: return @{$self->{'template_cells'}};
1079: }
1080:
1081: ##
1082: ## Sigh....
1083: ##
1084: sub setothersheets {
1085: my $self = shift;
1086: my @othersheets = @_;
1087: $self->{'othersheets'} = \@othersheets;
1088: }
1089:
1090: ##
1091: ## rows returns a list of the names of cells defined in the A column
1092: ##
1093: sub rows {
1094: my $self = shift;
1095: $self->rebuild_stats() if (!@{$self->{'rows'}});
1096: return @{$self->{'rows'}};
1097: }
1098:
1099: #
1100: # calcsheet: makes all the calls to compute the spreadsheet.
1101: #
1102: sub calcsheet {
1103: my $self = shift;
1104: $self->sync_safe_space();
1105: $self->clear_errorlog();
1106: $self->sett();
1107: my $result = $self->{'safe'}->reval('&calc();');
1108: # $self->logthis($self->get_errorlog());
1109: %{$self->{'values'}} = %{$self->{'safe'}->varglob('sheet_values')};
1110: # $self->logthis($self->get_errorlog());
1111: return $result;
1112: }
1113:
1114: ###########################################################
1115: ##
1116: ## Output Helpers
1117: ##
1118: ###########################################################
1.5 matthew 1119: sub display {
1120: my $self = shift;
1121: my ($r) = @_;
1122: $self->compute($r);
1123: my $outputmode = 'html';
1124: if ($ENV{'form.output_format'} =~ /^(html|excel|csv)$/) {
1125: $outputmode = $ENV{'form.output_format'};
1126: }
1127: if ($outputmode eq 'html') {
1128: $self->outsheet_html($r);
1129: } elsif ($outputmode eq 'excel') {
1130: $self->outsheet_excel($r);
1131: } elsif ($outputmode eq 'csv') {
1132: $self->outsheet_csv($r);
1133: }
1134: return;
1135: }
1136:
1.1 matthew 1137: ############################################
1138: ## HTML output routines ##
1139: ############################################
1140: sub html_export_row {
1141: my $self = shift();
1142: my $allowed = &Apache::lonnet::allowed('mgr',$ENV{'request.course.id'});
1143: my $row_html;
1144: my @rowdata = $self->get_row(0);
1145: foreach my $cell (@rowdata) {
1146: if ($cell->{'name'} =~ /^[A-Z]/) {
1147: $row_html .= '<td bgcolor="#CCCCFF">'.
1148: &html_editable_cell($cell,'#CCCCFF',$allowed).'</td>';
1149: } else {
1150: $row_html .= '<td bgcolor="#DDCCFF">'.
1151: &html_editable_cell($cell,'#DDCCFF',$allowed).'</td>';
1152: }
1153: }
1154: return $row_html;
1155: }
1156:
1157: sub html_template_row {
1158: my $self = shift();
1159: my $allowed = &Apache::lonnet::allowed('mgr',$ENV{'request.course.id'});
1160: my ($num_uneditable) = @_;
1161: my $row_html;
1162: my @rowdata = $self->get_template_row();
1163: my $count = 0;
1164: for (my $i = 0; $i<=$#rowdata; $i++) {
1165: my $cell = $rowdata[$i];
1166: if ($i < $num_uneditable) {
1.7 matthew 1167: $row_html .= '<td bgcolor="#FFDDDD">'.
1168: &html_uneditable_cell($cell,'#FFDDDD',$allowed).'</td>';
1.1 matthew 1169: } else {
1170: $row_html .= '<td bgcolor="#EOFFDD">'.
1171: &html_editable_cell($cell,'#EOFFDD',$allowed).'</td>';
1172: }
1173: }
1174: return $row_html;
1175: }
1176:
1177: sub html_editable_cell {
1178: my ($cell,$bgcolor,$allowed) = @_;
1179: my $result;
1180: my ($name,$formula,$value);
1181: if (defined($cell)) {
1182: $name = $cell->{'name'};
1183: $formula = $cell->{'formula'};
1184: $value = $cell->{'value'};
1185: }
1186: $name = '' if (! defined($name));
1187: $formula = '' if (! defined($formula));
1188: if (! defined($value)) {
1189: $value = '<font color="'.$bgcolor.'">#</font>';
1190: if ($formula ne '') {
1191: $value = '<i>undefined value</i>';
1192: }
1193: } elsif ($value =~ /^\s*$/ ) {
1194: $value = '<font color="'.$bgcolor.'">#</font>';
1195: } else {
1196: $value = &HTML::Entities::encode($value) if ($value !~/ /);
1197: }
1198: return $value if (! $allowed);
1199: # Make the formula safe for outputting
1200: $formula =~ s/\'/\"/g;
1201: # The formula will be parsed by the browser twice before being
1202: # displayed to the user for editing.
1203: $formula = &HTML::Entities::encode(&HTML::Entities::encode($formula));
1204: # Escape newlines so they make it into the edit window
1205: $formula =~ s/\n/\\n/gs;
1206: # Glue everything together
1207: $result .= "<a href=\"javascript:celledit(\'".
1208: $name."','".$formula."');\">".$value."</a>";
1209: return $result;
1210: }
1211:
1212: sub html_uneditable_cell {
1213: my ($cell,$bgcolor) = @_;
1214: my $value = (defined($cell) ? $cell->{'value'} : '');
1215: $value = &HTML::Entities::encode($value) if ($value !~/ /);
1216: return ' '.$value.' ';
1217: }
1218:
1219: sub html_row {
1220: my $self = shift();
1221: my ($num_uneditable,$row) = @_;
1222: my $allowed = &Apache::lonnet::allowed('mgr',$ENV{'request.course.id'});
1223: my @rowdata = $self->get_row($row);
1224: my $num_cols_output = 0;
1225: my $row_html;
1226: foreach my $cell (@rowdata) {
1227: if ($num_cols_output++ < $num_uneditable) {
1228: $row_html .= '<td bgcolor="#FFDDDD">';
1229: $row_html .= &html_uneditable_cell($cell,'#FFDDDD');
1230: } else {
1231: $row_html .= '<td bgcolor="#EOFFDD">';
1232: $row_html .= &html_editable_cell($cell,'#E0FFDD',$allowed);
1233: }
1234: $row_html .= '</td>';
1235: }
1236: return $row_html;
1237: }
1238:
1.5 matthew 1239: sub html_header {
1240: my $self = shift;
1241: return '' if (! $ENV{'request.role.adv'});
1242: return "<table>\n".
1243: '<tr><th align="center">Output Format</th><tr>'."\n".
1244: '<tr><td>'.&output_selector()."</td></tr>\n".
1245: "</table>\n";
1246: }
1247:
1248: sub output_selector {
1249: my $output_selector = '<select name="output_format" size="3">'."\n";
1250: my $default = 'html';
1251: if (exists($ENV{'form.output_format'})) {
1252: $default = $ENV{'form.output_format'}
1253: } else {
1254: $ENV{'form.output_format'} = $default;
1255: }
1256: foreach (['html','HTML'],
1257: ['excel','Excel'],
1258: ['csv','Comma Seperated Values']) {
1259: my ($name,$description) = @{$_};
1260: $output_selector.=qq{<option value="$name"};
1261: if ($name eq $default) {
1262: $output_selector .= ' selected';
1263: }
1264: $output_selector .= ">$description</option>\n";
1265: }
1266: $output_selector .= "</select>\n";
1267: return $output_selector;
1268: }
1269:
1270: ################################################
1271: ## Excel output routines ##
1272: ################################################
1273: sub excel_output_row {
1274: my $self = shift;
1275: my ($worksheet,$rownum,$rows_output,@prepend) = @_;
1276: my $cols_output = 0;
1277: #
1278: my @rowdata = $self->get_row($rownum);
1279: foreach my $cell (@prepend,@rowdata) {
1280: my $value = $cell;
1281: $value = $cell->{'value'} if (ref($value));
1282: $value =~ s/\ / /gi;
1283: $worksheet->write($rows_output,$cols_output++,$value);
1284: }
1285: return;
1286: }
1287:
1.1 matthew 1288: sub create_excel_spreadsheet {
1289: my $self = shift;
1290: my ($r) = @_;
1291: my $filename = '/prtspool/'.
1292: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
1293: time.'_'.rand(1000000000).'.xls';
1294: my $workbook = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
1295: if (! defined($workbook)) {
1296: $r->log_error("Error creating excel spreadsheet $filename: $!");
1297: $r->print("Problems creating new Excel file. ".
1298: "This error has been logged. ".
1299: "Please alert your LON-CAPA administrator");
1300: return undef;
1301: }
1302: #
1303: # The excel spreadsheet stores temporary data in files, then put them
1304: # together. If needed we should be able to disable this (memory only).
1305: # The temporary directory must be specified before calling 'addworksheet'.
1306: # File::Temp is used to determine the temporary directory.
1307: $workbook->set_tempdir('/home/httpd/perl/tmp');
1308: #
1309: # Determine the name to give the worksheet
1310: return ($workbook,$filename);
1.5 matthew 1311: }
1312:
1313: sub outsheet_excel {
1314: my $self = shift;
1315: my ($r) = @_;
1316: $r->print("<h2>Preparing Excel Spreadsheet</h2>");
1317: #
1318: # Create excel worksheet
1319: my ($workbook,$filename) = $self->create_excel_spreadsheet($r);
1320: return if (! defined($workbook));
1321: #
1322: # Create main worksheet
1323: my $worksheet = $workbook->addworksheet('main');
1324: my $rows_output = 0;
1325: my $cols_output = 0;
1326: #
1327: # Write excel header
1328: foreach my $value ($self->get_title()) {
1329: $cols_output = 0;
1330: $worksheet->write($rows_output++,$cols_output,$value);
1331: }
1332: $rows_output++; # skip a line
1333: #
1334: # Write summary/export row
1335: $cols_output = 0;
1336: $self->excel_output_row($worksheet,0,$rows_output++,'Summary');
1337: $rows_output++; # skip a line
1338: #
1339: $self->excel_rows($worksheet,$cols_output,$rows_output);
1340: #
1341: #
1342: # Close the excel file
1343: $workbook->close();
1344: #
1345: # Write a link to allow them to download it
1346: $r->print('<br />'.
1347: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
1.6 matthew 1348: return;
1349: }
1350:
1351: #################################
1352: ## CSV output routines ##
1353: #################################
1354: sub outsheet_csv {
1355: my $self = shift;
1356: my ($r) = @_;
1357: my $csvdata = '';
1358: my @Values;
1359: #
1360: # Open the csv file
1361: my $filename = '/prtspool/'.
1362: $ENV{'user.name'}.'_'.$ENV{'user.domain'}.'_'.
1363: time.'_'.rand(1000000000).'.csv';
1364: my $file;
1365: unless ($file = Apache::File->new('>'.'/home/httpd'.$filename)) {
1366: $r->log_error("Couldn't open $filename for output $!");
1367: $r->print("Problems occured in writing the csv file. ".
1368: "This error has been logged. ".
1369: "Please alert your LON-CAPA administrator.");
1370: $r->print("<pre>\n".$csvdata."</pre>\n");
1371: return 0;
1372: }
1373: #
1374: # Output the title information
1375: foreach my $value ($self->get_title()) {
1376: print $file "'".&Apache::loncommon::csv_translate($value)."'\n";
1377: }
1378: #
1379: # Output the body of the spreadsheet
1380: $self->csv_rows($file);
1381: #
1382: # Close the csv file
1383: close($file);
1384: $r->print('<br /><br />'.
1385: '<a href="'.$filename.'">Your CSV spreadsheet.</a>'."\n");
1386: #
1387: return 1;
1388: }
1389:
1390: sub csv_output_row {
1391: my $self = shift;
1392: my ($filehandle,$rownum,@prepend) = @_;
1393: #
1394: my @rowdata = ();
1395: if (defined($rownum)) {
1396: @rowdata = $self->get_row($rownum);
1397: }
1398: my @output = ();
1399: foreach my $cell (@prepend,@rowdata) {
1400: my $value = $cell;
1401: $value = $cell->{'value'} if (ref($value));
1402: $value =~ s/\ / /gi;
1403: $value = "'".$value."'";
1404: push (@output,$value);
1405: }
1406: print $filehandle join(',',@output )."\n";
1.5 matthew 1407: return;
1.1 matthew 1408: }
1409:
1410: ############################################
1411: ## XML output routines ##
1412: ############################################
1413: sub outsheet_xml {
1414: my $self = shift;
1415: my ($r) = @_;
1416: ## Someday XML
1417: ## Will be rendered for the user
1418: ## But not on this day
1419: my $Str = '<spreadsheet type="'.$self->{'type'}.'">'."\n";
1420: while (my ($cell,$formula) = each(%{$self->{'formulas'}})) {
1421: if ($cell =~ /^template_(\d+)/) {
1422: my $col = $1;
1423: $Str .= '<template col="'.$col.'">'.$formula.'</template>'."\n";
1424: } else {
1425: my ($row,$col) = ($cell =~ /^([A-z])(\d+)/);
1426: next if (! defined($row) || ! defined($col));
1427: $Str .= '<field row="'.$row.'" col="'.$col.'" >'.$formula.'</cell>'
1428: ."\n";
1429: }
1430: }
1431: $Str.="</spreadsheet>";
1432: return $Str;
1433: }
1434:
1435: ############################################
1436: ### Filesystem routines ###
1437: ############################################
1438: sub parse_sheet {
1439: # $sheetxml is a scalar reference or a scalar
1440: my ($sheetxml) = @_;
1441: if (! ref($sheetxml)) {
1442: my $tmp = $sheetxml;
1443: $sheetxml = \$tmp;
1444: }
1445: my %formulas;
1446: my %sources;
1447: my $parser=HTML::TokeParser->new($sheetxml);
1448: my $token;
1449: while ($token=$parser->get_token) {
1450: if ($token->[0] eq 'S') {
1451: if ($token->[1] eq 'field') {
1452: my $cell = $token->[2]->{'col'}.$token->[2]->{'row'};
1453: my $source = $token->[2]->{'source'};
1454: my $formula = $parser->get_text('/field');
1455: $formulas{$cell} = $formula;
1456: $sources{$cell} = $source if (defined($source));
1457: $parser->get_text('/field');
1458: }
1459: if ($token->[1] eq 'template') {
1460: $formulas{'template_'.$token->[2]->{'col'}}=
1461: $parser->get_text('/template');
1462: }
1463: }
1464: }
1465: return (\%formulas,\%sources);
1466: }
1467:
1468: {
1469:
1470: my %spreadsheets;
1471:
1472: sub clear_spreadsheet_definition_cache {
1473: undef(%spreadsheets);
1474: }
1475:
1476: sub load {
1477: my $self = shift;
1478: my $includedir = $Apache::lonnet::perlvar{'lonIncludes'};
1479: #
1480: my $stype = $self->{'type'};
1481: my $cnum = $self->{'cnum'};
1482: my $cdom = $self->{'cdom'};
1483: my $chome = $self->{'chome'};
1484: my $filename = $self->{'filename'};
1485: #
1486: my $cachekey = join('_',($cnum,$cdom,$stype,$filename));
1487: #
1488: # see if sheet is cached
1489: my ($formulas);
1490: if (exists($spreadsheets{$cachekey})) {
1491: $formulas = $spreadsheets{$cachekey}->{'formulas'};
1492: } else {
1493: # Not cached, need to read
1494: if (! defined($self->filename())) {
1495: # load in the default defined spreadsheet
1496: my $sheetxml='';
1497: my $fh;
1498: if ($fh=Apache::File->new($includedir.'/default.'.$filename)) {
1499: $sheetxml=join('',<$fh>);
1500: $fh->close();
1501: } else {
1502: # $sheetxml='<field row="0" col="A">"Error"</field>';
1503: $sheetxml='<field row="0" col="A"></field>';
1504: }
1505: ($formulas,undef) = &parse_sheet(\$sheetxml);
1.8 matthew 1506: } elsif($self->filename() =~ /^\/res\/.*\.spreadsheet$/) {
1.1 matthew 1507: # Load a spreadsheet definition file
1508: my $sheetxml=&Apache::lonnet::getfile
1509: (&Apache::lonnet::filelocation('',$filename));
1510: if ($sheetxml == -1) {
1511: $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
1512: .$self->filename().'"</field>';
1513: }
1514: ($formulas,undef) = &parse_sheet(\$sheetxml);
1515: } else {
1516: # Load the spreadsheet definition file from the save file
1517: my %tmphash = &Apache::lonnet::dump($self->filename(),$cdom,$cnum);
1518: my ($tmp) = keys(%tmphash);
1519: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1520: while (my ($cell,$formula) = each(%tmphash)) {
1521: $formulas->{$cell}=$formula;
1522: }
1523: } else {
1524: # Unable to grab the specified spreadsheet,
1525: # so we get the default ones instead.
1526: $filename = 'default.'.$stype;
1527: $self->filename($filename);
1528: my $sheetxml;
1529: if (my $fh=Apache::File->new($includedir.'/'.$filename)) {
1530: $sheetxml = join('',<$fh>);
1531: $fh->close();
1532: } else {
1533: $sheetxml='<field row="0" col="A">'.
1534: '"Unable to load spreadsheet"</field>';
1535: }
1536: ($formulas,undef) = &parse_sheet(\$sheetxml);
1537: $self->formulas($formulas);
1538: }
1539: }
1540: $cachekey = join('_',($cnum,$cdom,$stype,$filename));
1541: %{$spreadsheets{$cachekey}->{'formulas'}} = %{$formulas};
1542: }
1543: $self->formulas($formulas);
1544: $self->set_row_sources();
1545: $self->set_row_numbers();
1546: }
1547:
1548: sub set_row_sources {
1549: my $self = shift;
1550: while (my ($cell,$value) = each(%{$self->{'formulas'}})) {
1551: next if ($cell !~ /^A(\d+)/ && $1 > 0);
1552: my $row = $1;
1553: $self->{'row_source'}->{$row} = $value;
1554: }
1555: return;
1556: }
1557:
1558: ##
1559: ## exportrow is *not* used to get the export row from a computed sub-sheet.
1560: ##
1561: sub exportrow {
1562: my $self = shift;
1563: my @exportarray;
1564: foreach my $column (@UC_Columns) {
1565: push(@exportarray,$self->value($column.'0'));
1566: }
1567: return @exportarray;
1568: }
1569:
1570: sub save {
1571: my $self = shift;
1572: my ($makedef)=@_;
1573: my $cid=$self->{'cid'};
1.4 matthew 1574: # If we are saving it, it must not be temporary
1575: $self->temporary(0);
1.1 matthew 1576: if (&Apache::lonnet::allowed('opa',$cid)) {
1577: my %f=$self->formulas();
1578: my $stype = $self->{'type'};
1579: my $cnum = $self->{'cnum'};
1580: my $cdom = $self->{'cdom'};
1581: my $chome = $self->{'chome'};
1582: my $fn = $self->{'filename'};
1583: # Cache new sheet
1584: $spreadsheets{$cnum.'_'.$cdom.'_'.$stype.'_'.$fn}=join('___;___',%f);
1585: # Write sheet
1586: foreach (keys(%f)) {
1587: delete($f{$_}) if ($f{$_} eq 'import');
1588: }
1589: my $reply = &Apache::lonnet::put($fn,\%f,$cdom,$cnum);
1590: return $reply if ($reply ne 'ok');
1591: $reply = &Apache::lonnet::put($stype.'_spreadsheets',
1592: {$fn => $ENV{'user.name'}.'@'.$ENV{'user.domain'}},
1593: $cdom,$cnum);
1594: return $reply if ($reply ne 'ok');
1595: if ($makedef) {
1596: $reply = &Apache::lonnet::put('environment',
1597: {'spreadsheet_default_'.$stype => $fn },
1598: $cdom,$cnum);
1599: return $reply if ($reply ne 'ok');
1600: }
1601: if ($self->is_default()) {
1602: &Apache::lonnet::expirespread('','',$self->{'type'},'');
1603: }
1604: return $reply;
1605: }
1606: return 'unauthorized';
1607: }
1608:
1609: } # end of scope for %spreadsheets
1610:
1611: sub save_tmp {
1612: my $self = shift;
1.9 matthew 1613: my $filename=$ENV{'user.name'}.'_'.
1.1 matthew 1614: $ENV{'user.domain'}.'_spreadsheet_'.$self->{'usymb'}.'_'.
1615: $self->{'filename'};
1.9 matthew 1616: $filename=~s/\W/\_/g;
1617: $filename=$Apache::lonnet::tmpdir.$filename.'.tmp';
1.4 matthew 1618: $self->temporary(1);
1.1 matthew 1619: my $fh;
1.9 matthew 1620: if ($fh=Apache::File->new('>'.$filename)) {
1.1 matthew 1621: my %f = $self->formulas();
1622: while( my ($cell,$formula) = each(%f)) {
1623: next if ($formula eq 'import');
1624: print $fh &Apache::lonnet::escape($cell)."=".
1625: &Apache::lonnet::escape($formula)."\n";
1626: }
1627: $fh->close();
1628: }
1629: }
1630:
1631: sub load_tmp {
1632: my $self = shift;
1633: my $filename=$ENV{'user.name'}.'_'.
1634: $ENV{'user.domain'}.'_spreadsheet_'.$self->{'usymb'}.'_'.
1635: $self->{'filename'};
1636: $filename=~s/\W/\_/g;
1637: $filename=$Apache::lonnet::tmpdir.$filename.'.tmp';
1638: my %formulas = ();
1639: if (my $spreadsheet_file = Apache::File->new($filename)) {
1640: while (<$spreadsheet_file>) {
1641: chomp;
1642: my ($cell,$formula) = split(/=/);
1643: $cell = &Apache::lonnet::unescape($cell);
1644: $formula = &Apache::lonnet::unescape($formula);
1645: $formulas{$cell} = $formula;
1646: }
1647: $spreadsheet_file->close();
1648: }
1.4 matthew 1649: # flag the sheet as temporary
1650: $self->temporary(1);
1.1 matthew 1651: $self->formulas(\%formulas);
1652: $self->set_row_sources();
1653: $self->set_row_numbers();
1654: return;
1.4 matthew 1655: }
1656:
1657: sub temporary {
1658: my $self=shift;
1659: if (@_) {
1660: ($self->{'temporary'})= @_;
1661: }
1662: return $self->{'temporary'};
1.1 matthew 1663: }
1664:
1665: sub modify_cell {
1666: # studentcalc overrides this
1667: my $self = shift;
1668: my ($cell,$formula) = @_;
1669: if ($cell =~ /([A-z])\-/) {
1670: $cell = 'template_'.$1;
1671: } elsif ($cell !~ /^([A-z](\d+)|template_[A-z])$/) {
1672: return;
1673: }
1674: $self->set_formula($cell,$formula);
1675: $self->rebuild_stats();
1676: return;
1677: }
1678:
1679: ###########################################
1680: # othersheets: Returns the list of other spreadsheets available
1681: ###########################################
1682: sub othersheets {
1683: my $self = shift();
1684: my ($stype) = @_;
1685: $stype = $self->{'type'} if (! defined($stype) || $stype !~ /calc$/);
1686: #
1687: my @alternatives=();
1688: my %results=&Apache::lonnet::dump($stype.'_spreadsheets',
1689: $self->{'cdom'}, $self->{'cnum'});
1690: my ($tmp) = keys(%results);
1.2 matthew 1691: if ($tmp =~ /^(con_lost|error|no_such_host)/i ) {
1692: @alternatives = ('Default');
1693: } else {
1.1 matthew 1694: @alternatives = sort (keys(%results));
1695: }
1696: return @alternatives;
1.3 matthew 1697: }
1698:
1699: sub blackout {
1700: my $self = shift;
1701: $self->{'blackout'} = $_[0] if (@_);
1702: return $self->{'blackout'};
1.1 matthew 1703: }
1704:
1705: sub get_row {
1706: my $self = shift;
1707: my ($n)=@_;
1708: my @cols=();
1709: foreach my $col (@UC_Columns,@LC_Columns) {
1710: my $cell = $col.$n;
1711: push(@cols,{ name => $cell,
1712: formula => $self->formula($cell),
1713: value => $self->value($cell)});
1714: }
1715: return @cols;
1716: }
1717:
1718: sub get_template_row {
1719: my $self = shift;
1720: my @cols=();
1721: foreach my $col (@UC_Columns,@LC_Columns) {
1722: my $cell = 'template_'.$col;
1723: push(@cols,{ name => $cell,
1724: formula => $self->formula($cell),
1725: value => $self->formula($cell) });
1726: }
1727: return @cols;
1728: }
1729:
1730: sub set_row_numbers {
1731: my $self = shift;
1732: my %f=$self->formulas();
1733: while (my ($cell,$value) = each(%{$self->{'formulas'}})) {
1734: next if ($cell !~ /^A(\d+)$/);
1735: next if (! defined($value));
1736: $self->{'row_numbers'}->{$value} = $1;
1737: }
1738: }
1739:
1740: sub get_row_number_from_key {
1741: my $self = shift;
1742: my ($key) = @_;
1743: if (! exists($self->{'row_numbers'}->{$key}) ||
1744: ! defined($self->{'row_numbers'}->{$key})) {
1745: # I used to set $f here to the new value, but the key passed for lookup
1746: # may not be the key we need to save
1747: $self->{'maxrow'}++;
1748: $self->{'row_numbers'}->{$key} = $self->{'maxrow'};
1749: }
1750: return $self->{'row_numbers'}->{$key};
1751: }
1752:
1753: 1;
1754:
1755: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>