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