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