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