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