Annotation of loncom/interface/spreadsheet/Spreadsheet.pm, revision 1.80
1.1 matthew 1: #
1.80 ! bisitz 2: # $Id: Spreadsheet.pm,v 1.79 2008/09/11 14:47:22 bisitz 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;
1.24 matthew 51: #use warnings FATAL=>'all';
52: #no warnings 'uninitialized';
1.1 matthew 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;
1.28 www 62: use Apache::lonlocal;
1.69 www 63: use lib '/home/httpd/lib/perl/';
64: use LONCAPA;
65:
1.1 matthew 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: #
1.68 raeburn 91: my ($name,$domain,$filename,$usymb,$section,$groups)=@_;
1.39 matthew 92: if (defined($usymb) && ref($usymb)) {
93: $usymb = $usymb->symb;
94: }
1.36 matthew 95: if (! defined($name) || $name eq '') {
1.41 albertel 96: $name = $env{'user.name'};
1.36 matthew 97: }
98: if (! defined($domain) || $domain eq '') {
1.41 albertel 99: $domain = $env{'user.domain'};
1.36 matthew 100: }
1.66 albertel 101: if (! defined($section) || $section eq '') {
102: $section = &Apache::lonnet::getsection($domain,$name,
103: $env{'request.course.id'});
104: }
1.68 raeburn 105: if (! defined($groups)) {
106:
107: my @usersgroups = &Apache::lonnet::get_users_groups($domain,$name,
1.67 raeburn 108: $env{'request.course.id'});
1.68 raeburn 109: $groups = \@usersgroups;
1.67 raeburn 110: }
1.1 matthew 111: #
112: my $self = {
113: name => $name,
114: domain => $domain,
1.66 albertel 115: section => $section,
1.68 raeburn 116: groups => $groups,
1.1 matthew 117: type => $stype,
118: symb => $usymb,
119: errorlog => '',
1.22 matthew 120: maxrow => 0,
1.41 albertel 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'},
1.12 matthew 126: #
127: # Flags
128: temporary => 0, # true if this sheet has been modified but not saved
1.49 albertel 129: new_rows => 0, # true if this sheet has new rows
130: loaded => 0, # true if the formulas have been loaded
1.1 matthew 131: #
1.3 matthew 132: # blackout is used to determine if any data needs to be hidden from the
133: # student.
134: blackout => 0,
135: #
1.1 matthew 136: # Data storage
137: formulas => {},
138: constants => {},
139: rows => [],
140: row_source => {},
141: othersheets => [],
142: };
143: #
144: bless($self,$class);
1.50 albertel 145: $self->filename($filename);
1.1 matthew 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' ||
1.13 matthew 166: $newfilename !~ /\w/ || $newfilename eq '') {
167: my $key = 'course.'.$self->{'cid'}.'.spreadsheet_default_'.
168: $self->{'type'};
1.41 albertel 169: if (exists($env{$key}) && $env{$key} ne '') {
170: $newfilename = $env{$key};
1.13 matthew 171: } else {
172: $newfilename = 'default_'.$self->{'type'};
1.1 matthew 173: }
1.13 matthew 174: }
1.71 albertel 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: }
1.1 matthew 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',
1.13 matthew 210: {'spreadsheet_default_'.$self->{'type'} => $self->filename()},
1.1 matthew 211: $self->{'cdom'},$self->{'cnum'});
212: return $result if ($result ne 'ok');
1.78 raeburn 213: &Apache::lonnet::appenv({'course.'.$self->{'cid'}.'.spreadsheet_default_'.
214: $self->{'type'} => $self->filename()});
1.1 matthew 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)
1.56 albertel 235: my $default_filename = $env{'course.'.$self->{'cid'}.
236: '.spreadsheet_default_'.$self->{'type'}};
1.13 matthew 237: if ($default_filename =~ /^\s*$/) {
238: $default_filename = 'default_'.$self->{'type'};
239: }
1.1 matthew 240: return 1 if ($self->filename() eq $default_filename);
241: return 0;
1.11 matthew 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.
1.1 matthew 247: }
248:
1.23 matthew 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:
1.1 matthew 259: sub initialize_spreadsheet_package {
260: &load_spreadsheet_expirationdates();
261: &clear_spreadsheet_definition_cache();
262: }
263:
264: sub load_spreadsheet_expirationdates {
265: undef %expiredates;
1.41 albertel 266: my $cid=$env{'request.course.id'};
1.1 matthew 267: my @tmp = &Apache::lonnet::dump('nohist_expirationdates',
1.41 albertel 268: $env{'course.'.$cid.'.domain'},
269: $env{'course.'.$cid.'.num'});
1.1 matthew 270: if (lc($tmp[0]) !~ /^error/){
271: %expiredates = @tmp;
272: }
273: }
274:
275: sub check_expiration_time {
276: my $self = shift;
277: my ($time)=@_;
1.22 matthew 278: return 0 if (! defined($time));
1.19 matthew 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
1.1 matthew 287: $key1 = '::'.$self->{'type'}.':';
288: $key2 = $self->{'name'}.':'.$self->{'domain'}.':'.$self->{'type'}.':';
289: $key3 = $key2.$self->{'container'} if (defined($self->{'container'}));
1.19 matthew 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) {
1.1 matthew 294: next if (! defined($key));
1.19 matthew 295: if (exists($expiredates{$key}) && $expiredates{$key} > $time) {
296: $returnvalue = 0; # need to recompute
1.1 matthew 297: }
298: }
1.19 matthew 299: return $returnvalue;
1.1 matthew 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: ######################################################
1.25 matthew 317: {
318:
319: my $safeeval;
320:
1.1 matthew 321: sub initialize_safe_space {
1.25 matthew 322: my $self = shift;
1.38 matthew 323: my $usection = &Apache::lonnet::getsection($self->{'domain'},
324: $self->{'name'},
1.41 albertel 325: $env{'request.course.id'});
1.25 matthew 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");
1.38 matthew 333: $safehole->wrap(\&Apache::lonnet::EXT,$safeeval,'&Apache::lonnet::EXT');
1.25 matthew 334: $safehole->wrap(\&mask,$safeeval,'&mask');
1.44 albertel 335: $safehole->wrap(\&Apache::lonnet::logthis,$safeeval,'&logthis');
1.25 matthew 336: $safeeval->share('$@');
1.46 albertel 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');
1.25 matthew 341: my $code=<<'ENDDEFS';
1.1 matthew 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)
1.46 albertel 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.
1.1 matthew 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:
1.38 matthew 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 {
1.61 albertel 400: my ($parameter,$specific_symb) = @_;
1.38 matthew 401: return '' if (! defined($parameter) || $parameter eq '');
402: $parameter =~ s/^parameter\./resource\./;
1.61 albertel 403: if ($specific_symb eq '') { $specific_symb = $symb; }
404: my $value = &Apache::lonnet::EXT($parameter,$specific_symb,$domain,$name,
405: $usection);
1.38 matthew 406: return $value;
407: }
408:
409: #-------------------------------------------------------
410:
411: =pod
412:
1.1 matthew 413: =item NUM(range)
414:
415: returns the number of items in the range.
416:
417: =cut
418:
419: #-------------------------------------------------------
420: sub NUM {
1.44 albertel 421: my $values=&get_values(@_);
422: my $num= scalar(@$values);
1.1 matthew 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)=@_;
1.44 albertel 437: my $values=&get_values($lower,$upper);
1.1 matthew 438: my $num=0;
1.44 albertel 439: foreach (@$values) {
440: if (($_>=$low) && ($_<=$high)) {
1.1 matthew 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 {
1.44 albertel 459: my $values=&get_values(@_);
1.1 matthew 460: my $sum=0;
1.44 albertel 461: foreach (@$values) {
462: $sum+=$_;
1.1 matthew 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 {
1.44 albertel 479: my $values=&get_values(@_);
1.1 matthew 480: my $sum=0;
481: my $num=0;
1.44 albertel 482: foreach (@$values) {
483: $sum+=$_;
1.1 matthew 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 {
1.44 albertel 505: my $values=&get_values(@_);
1.1 matthew 506: my $sum=0; my $num=0;
1.44 albertel 507: foreach (@$values) {
508: $sum+=$_;
1.1 matthew 509: $num++;
510: }
511: unless ($num>1) { return undef; }
512: my $mean=$sum/$num;
513: $sum=0;
1.44 albertel 514: foreach (@$values) {
515: $sum+=($_-$mean)**2;
1.1 matthew 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 {
1.44 albertel 532: my $values=&get_values(@_);
1.1 matthew 533: my $prod=1;
1.44 albertel 534: foreach (@$values) {
535: $prod*=$_;
1.1 matthew 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 {
1.44 albertel 552: my $values=&get_values(@_);
1.1 matthew 553: my $max='-';
1.44 albertel 554: foreach (@$values) {
555: if (($_>$max) || ($max eq '-')) {
556: $max=$_;
1.1 matthew 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 {
1.44 albertel 574: my $values=&get_values(@_);
1.1 matthew 575: my $min='-';
1.44 albertel 576: foreach (@$values) {
577: if (($_<$min) || ($min eq '-')) {
578: $min=$_;
1.1 matthew 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)=@_;
1.44 albertel 598: my $values=&get_values($lower,$upper);
599: my @inside=sort {$a <=> $b} (@$values);
1.1 matthew 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)=@_;
1.44 albertel 621: my $values=&get_values($lower,$upper);
622: my @inside=sort {$a <=> $b} (@$values);
1.1 matthew 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:
1.75 albertel 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:
1.45 albertel 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: #-------------------------------------------------------
1.44 albertel 707: sub get_values {
708: my ($lower,$upper)=@_;
1.45 albertel 709: $upper = $lower if (! defined($upper));
1.44 albertel 710: my @values;
1.45 albertel 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 '*') {
1.44 albertel 715: my @alpha;
716: if (($la eq '*') || ($ua eq '*')) {
717: @alpha=('A'..'z');
718: } else {
1.45 albertel 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: }
1.44 albertel 732: }
733: }
1.45 albertel 734: return \@values;
735: } else {
1.60 albertel 736: $num = '([1-9]\d*)';
1.45 albertel 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{$_});
1.44 albertel 747: }
1.45 albertel 748: return \@values;
1.44 albertel 749: }
1.1 matthew 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};
1.65 bowersj2 759: $sheet_values{$cell}=eval $value;
1.1 matthew 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: }
1.30 matthew 778: return 'okay';
1.1 matthew 779: }
780:
781: # ------------------------------------------- End of "Inside of the safe space"
782: ENDDEFS
1.25 matthew 783: $safeeval->reval($code);
784: }
1.1 matthew 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 = '';
1.38 matthew 791: foreach (qw/name domain type symb cid csec coursefilename
1.48 albertel 792: cnum cdom/) {
1.1 matthew 793: $initstring.= qq{\$$_="$self->{$_}";};
794: }
1.38 matthew 795: $initstring.=qq{\$usection="$usection";};
1.1 matthew 796: $self->{'safe'}->reval($initstring);
797: return $self;
798: }
1.25 matthew 799:
800: }
801:
1.1 matthew 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=~/^\&/) {
1.74 albertel 823: my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/s);
1.1 matthew 824: my @vars=split(/\W+/,$formula);
1.73 albertel 825: # make the list uniq
826: @vars = keys(%{{ map { $_ => 1 } @vars }});
1.1 matthew 827: my %values=();
828: foreach my $varname ( @vars ) {
1.20 matthew 829: if ($varname=~/^(parameter|stores|timestamp)/) {
830: $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
1.76 albertel 831: $varname=~s/$var/\([\\w:\\- ]\+\)/g;
832: foreach (keys(%{$self->{'constants'}})) {
833: if ($_=~/$varname/) {
834: $values{$1}=1;
835: }
836: }
1.1 matthew 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/\+$//;
1.64 bowersj2 847: return '('.$result.')';
1.1 matthew 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 = ();
1.14 matthew 860: my @values = ();
1.1 matthew 861: $#matches = -1;
1.14 matthew 862: while (my($parameter,$value) = each(%{$self->{'constants'}})) {
863: next if ($parameter !~ /$expression/);
864: push(@matches,$parameter);
865: push(@values,$value);
1.1 matthew 866: }
867: if (scalar(@matches) == 0) {
1.10 matthew 868: $returnvalue = '""';#'"unmatched parameter: '.$parameter.'"';
1.1 matthew 869: } elsif (scalar(@matches) == 1) {
870: # why do we not do this lookup here, instead of delaying it?
1.14 matthew 871: $returnvalue = $values[0];
1.1 matthew 872: } elsif (scalar(@matches) > 0) {
873: # more than one match. Look for a concise one
874: $returnvalue = "'non-unique parameter name : $expression'";
1.14 matthew 875: for (my $i=0; $i<=$#matches;$i++) {
876: if ($matches[$i] =~ /^$expression$/) {
1.1 matthew 877: # why do we not do this lookup here?
1.14 matthew 878: $returnvalue = $values[$i];
1.1 matthew 879: }
880: }
881: } else {
882: # There was a negative number of matches, which indicates
883: # something is wrong with reality. Better warn the user.
1.14 matthew 884: $returnvalue = '"bizzare parameter: '.$expression.'"';
1.1 matthew 885: }
886: return $returnvalue;
887: }
888: }
889:
890: sub sett {
891: my $self = shift;
892: my %t=();
1.46 albertel 893: undef(%Apache::Spreadsheet::sheet_values);
1.1 matthew 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
1.74 albertel 910: $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/sge;
1.1 matthew 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;
1.74 albertel 922: $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/sge;
1.1 matthew 923: } elsif ( $col =~ /^[A-Z]$/ ) {
1.42 albertel 924: if ($formula !~ /^\!/ && exists($self->{'constants'}->{$cell})
925: && $self->{'constants'}->{$cell} ne '') {
1.46 albertel 926: $Apache::Spreadsheet::sheet_values{$cell}=
927: eval($self->{'constants'}->{$cell});
1.1 matthew 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;
1.74 albertel 933: $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/sge;
1.1 matthew 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'.
1.47 albertel 946: #%{$self->{'safe'}->varglob('f')}=%{$self->{'formulas'}};
1.1 matthew 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.
1.47 albertel 950: #@{$self->{'safe'}->varglob('os')}=@{$self->{'othersheets'}};
1.1 matthew 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'} = [];
1.54 albertel 1003: $self->{'loaded'} = 1;
1.1 matthew 1004: return;
1005: } else {
1.54 albertel 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();
1.49 albertel 1021: }
1.1 matthew 1022: }
1023: }
1024:
1025: sub set_formula {
1026: my $self = shift;
1027: my ($cell,$formula) = @_;
1.54 albertel 1028: $self->check_formulas_loaded();
1.1 matthew 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;
1.54 albertel 1038: $self->check_formulas_loaded();
1.1 matthew 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;
1.54 albertel 1049: $self->check_formulas_loaded();
1.1 matthew 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'}=[];
1.54 albertel 1128: $self->check_formulas_loaded();
1.1 matthew 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());
1.30 matthew 1176: if ($result ne 'okay') {
1177: $self->set_calcerror($result);
1178: }
1.1 matthew 1179: return $result;
1180: }
1181:
1.30 matthew 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:
1.1 matthew 1219: ###########################################################
1220: ##
1221: ## Output Helpers
1222: ##
1223: ###########################################################
1.5 matthew 1224: sub display {
1225: my $self = shift;
1226: my ($r) = @_;
1227: my $outputmode = 'html';
1.31 matthew 1228: foreach ($self->output_options()) {
1.41 albertel 1229: if ($env{'form.output_format'} eq $_->{'value'}) {
1.31 matthew 1230: $outputmode = $_->{'value'};
1231: last;
1232: }
1.5 matthew 1233: }
1.62 bowersj2 1234: $self->{outputmode} = $outputmode;
1.5 matthew 1235: if ($outputmode eq 'html') {
1.31 matthew 1236: $self->compute($r);
1.5 matthew 1237: $self->outsheet_html($r);
1.31 matthew 1238: } elsif ($outputmode eq 'htmlclasslist') {
1239: # No computation neccessary... This is kludgy
1240: $self->outsheet_htmlclasslist($r);
1.62 bowersj2 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);
1.5 matthew 1247: } elsif ($outputmode eq 'excel') {
1.31 matthew 1248: $self->compute($r);
1.5 matthew 1249: $self->outsheet_excel($r);
1250: } elsif ($outputmode eq 'csv') {
1.31 matthew 1251: $self->compute($r);
1.5 matthew 1252: $self->outsheet_csv($r);
1.33 matthew 1253: } elsif ($outputmode eq 'xml') {
1254: # $self->compute($r);
1255: $self->outsheet_xml($r);
1.5 matthew 1256: }
1.22 matthew 1257: $self->cleanup();
1.5 matthew 1258: return;
1259: }
1260:
1.1 matthew 1261: ############################################
1262: ## HTML output routines ##
1263: ############################################
1.30 matthew 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:
1.1 matthew 1276: sub html_export_row {
1277: my $self = shift();
1.17 matthew 1278: my ($color) = @_;
1279: $color = '#CCCCFF' if (! defined($color));
1.41 albertel 1280: my $allowed = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
1.1 matthew 1281: my $row_html;
1282: my @rowdata = $self->get_row(0);
1283: foreach my $cell (@rowdata) {
1284: if ($cell->{'name'} =~ /^[A-Z]/) {
1.17 matthew 1285: $row_html .= '<td bgcolor="'.$color.'">'.
1.62 bowersj2 1286: &html_editable_cell($cell,$color,$allowed,
1287: $self->{outputmode} eq 'source').'</td>';
1.1 matthew 1288: } else {
1289: $row_html .= '<td bgcolor="#DDCCFF">'.
1.62 bowersj2 1290: &html_editable_cell($cell,'#DDCCFF',$allowed,
1291: $self->{outputmode} eq 'source').'</td>';
1.1 matthew 1292: }
1293: }
1294: return $row_html;
1295: }
1296:
1297: sub html_template_row {
1298: my $self = shift();
1.41 albertel 1299: my $allowed = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
1.17 matthew 1300: my ($num_uneditable,$importcolor) = @_;
1.1 matthew 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) {
1.17 matthew 1307: $row_html .= '<td bgcolor="'.$importcolor.'">'.
1.7 matthew 1308: &html_uneditable_cell($cell,'#FFDDDD',$allowed).'</td>';
1.1 matthew 1309: } else {
1.70 albertel 1310: $row_html .= '<td bgcolor="#E0FFDD">'.
1311: &html_editable_cell($cell,'#E0FFDD',$allowed,
1.62 bowersj2 1312: $self->{outputmode} eq 'source').'</td>';
1.1 matthew 1313: }
1314: }
1315: return $row_html;
1316: }
1317:
1318: sub html_editable_cell {
1.62 bowersj2 1319: my ($cell,$bgcolor,$allowed,$showsource) = @_;
1.1 matthew 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));
1.65 bowersj2 1329: if ($showsource) {
1.62 bowersj2 1330: if (!defined($formula) || $formula =~ /^\s*$/) {
1331: $value = '<font color="'.$bgcolor.'">#</font>';
1332: } else {
1333: $value = &HTML::Entities::encode($formula, '<>&"');
1334: }
1.65 bowersj2 1335: } elsif (! defined($value)) {
1.1 matthew 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 {
1.37 albertel 1343: $value = &HTML::Entities::encode($value,'<>&"') if ($value !~/ /);
1.1 matthew 1344: }
1345: return $value if (! $allowed);
1.18 matthew 1346: #
1.1 matthew 1347: # The formula will be parsed by the browser twice before being
1.18 matthew 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.
1.21 matthew 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;
1.18 matthew 1355: # Escape it again - this time the only encodable character is '&'
1356: $formula =~ s/\&/\&/g;
1.1 matthew 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'} : '');
1.37 albertel 1366: $value = &HTML::Entities::encode($value,'<>&"') if ($value !~/ /);
1.1 matthew 1367: return ' '.$value.' ';
1368: }
1369:
1370: sub html_row {
1371: my $self = shift();
1.17 matthew 1372: my ($num_uneditable,$row,$exportcolor,$importcolor) = @_;
1.41 albertel 1373: my $allowed = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
1.1 matthew 1374: my @rowdata = $self->get_row($row);
1375: my $num_cols_output = 0;
1376: my $row_html;
1.17 matthew 1377: my $color = $importcolor;
1378: if ($row == 0) {
1379: $color = $exportcolor;
1380: }
1381: $color = '#FFDDDD' if (! defined($color));
1.1 matthew 1382: foreach my $cell (@rowdata) {
1383: if ($num_cols_output++ < $num_uneditable) {
1.17 matthew 1384: $row_html .= '<td bgcolor="'.$color.'">';
1.1 matthew 1385: $row_html .= &html_uneditable_cell($cell,'#FFDDDD');
1386: } else {
1.70 albertel 1387: $row_html .= '<td bgcolor="#E0FFDD">';
1.62 bowersj2 1388: $row_html .= &html_editable_cell($cell,'#E0FFDD',$allowed,
1389: $self->{outputmode} eq 'source');
1.1 matthew 1390: }
1391: $row_html .= '</td>';
1392: }
1393: return $row_html;
1394: }
1395:
1.5 matthew 1396: sub html_header {
1397: my $self = shift;
1.41 albertel 1398: return '' if (! $env{'request.role.adv'});
1.5 matthew 1399: return "<table>\n".
1.29 matthew 1400: '<tr><th align="center">'.&mt('Output Format').'</th></tr>'."\n".
1.31 matthew 1401: '<tr><td>'.$self->output_selector()."</td></tr>\n".
1.5 matthew 1402: "</table>\n";
1403: }
1404:
1.31 matthew 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'},
1.62 bowersj2 1413: {value => 'source',
1414: description => 'Show Source'},
1.33 matthew 1415: # {value => 'xml',
1416: # description => 'XML'},
1.31 matthew 1417: {value => 'csv',
1418: description => 'Comma Separated Values'},);
1419: }
1420:
1.5 matthew 1421: sub output_selector {
1.31 matthew 1422: my $self = shift();
1.5 matthew 1423: my $output_selector = '<select name="output_format" size="3">'."\n";
1424: my $default = 'html';
1.41 albertel 1425: if (exists($env{'form.output_format'})) {
1426: $default = $env{'form.output_format'}
1.5 matthew 1427: } else {
1.41 albertel 1428: $env{'form.output_format'} = $default;
1.5 matthew 1429: }
1.31 matthew 1430: foreach ($self->output_options()) {
1431: $output_selector.='<option value="'.$_->{'value'}.'"';
1432: if ($_->{'value'} eq $default) {
1.5 matthew 1433: $output_selector .= ' selected';
1434: }
1.31 matthew 1435: $output_selector .= ">".&mt($_->{'description'})."</option>\n";
1.5 matthew 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:
1.31 matthew 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;
1.5 matthew 1467: }
1468:
1469: sub outsheet_excel {
1470: my $self = shift;
1471: my ($r) = @_;
1.23 matthew 1472: my $connection = $r->connection();
1.32 matthew 1473: #
1474: $r->print($self->html_report_error());
1475: $r->rflush();
1476: #
1.28 www 1477: $r->print("<h2>".&mt('Preparing Excel Spreadsheet')."</h2>");
1.5 matthew 1478: #
1.40 matthew 1479: # Create excel workbook
1480: my ($workbook,$filename,$format)=&Apache::loncommon::create_workbook($r);
1.5 matthew 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;
1.40 matthew 1491: $worksheet->write($rows_output++,$cols_output,$value,$format->{'h1'});
1.5 matthew 1492: }
1493: $rows_output++; # skip a line
1494: #
1495: # Write summary/export row
1496: $cols_output = 0;
1.40 matthew 1497: $self->excel_output_row($worksheet,0,$rows_output++,'Summary',
1498: $format->{'b'});
1.5 matthew 1499: $rows_output++; # skip a line
1500: #
1.40 matthew 1501: $self->excel_rows($connection,$worksheet,$cols_output,$rows_output,
1502: $format);
1.5 matthew 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");
1.6 matthew 1511: return;
1512: }
1513:
1514: #################################
1515: ## CSV output routines ##
1516: #################################
1517: sub outsheet_csv {
1518: my $self = shift;
1519: my ($r) = @_;
1.23 matthew 1520: my $connection = $r->connection();
1.32 matthew 1521: #
1522: $r->print($self->html_report_error());
1523: $r->rflush();
1524: #
1.6 matthew 1525: my $csvdata = '';
1526: my @Values;
1527: #
1.80 ! bisitz 1528: # Open the CSV file
1.6 matthew 1529: my $filename = '/prtspool/'.
1.41 albertel 1530: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.6 matthew 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 $!");
1.80 ! bisitz 1535: $r->print(&mt('Problems occurred in writing the CSV file. '
1.79 bisitz 1536: .'This error has been logged. '
1537: .'Please alert your LON-CAPA administrator.'));
1.6 matthew 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
1.23 matthew 1548: $self->csv_rows($connection,$file);
1.6 matthew 1549: #
1.80 ! bisitz 1550: # Close the CSV file
1.6 matthew 1551: close($file);
1552: $r->print('<br /><br />'.
1.28 www 1553: '<a href="'.$filename.'">'.&mt('Your CSV spreadsheet.').'</a>'."\n");
1.6 matthew 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";
1.5 matthew 1575: return;
1.1 matthew 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";
1.54 albertel 1588: $self->check_formulas_loaded();
1.1 matthew 1589: while (my ($cell,$formula) = each(%{$self->{'formulas'}})) {
1.34 matthew 1590: if ($cell =~ /^template_(\w+)/) {
1.1 matthew 1591: my $col = $1;
1592: $Str .= '<template col="'.$col.'">'.$formula.'</template>'."\n";
1593: } else {
1.33 matthew 1594: my ($col,$row) = ($cell =~ /^([A-z])(\d+)/);
1.1 matthew 1595: next if (! defined($row) || ! defined($col));
1.33 matthew 1596: next if ($row != 0);
1597: $Str .=
1598: '<field row="'.$row.'" col="'.$col.'" >'.$formula.'</field>'
1.1 matthew 1599: ."\n";
1600: }
1601: }
1602: $Str.="</spreadsheet>";
1.34 matthew 1603: $r->print("<pre>\n\n\n".$Str."\n\n\n</pre>");
1.1 matthew 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');
1.34 matthew 1630: } elsif ($token->[1] eq 'template') {
1.1 matthew 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:
1.13 matthew 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:
1.1 matthew 1665: sub load {
1666: my $self = shift;
1667: #
1668: my $stype = $self->{'type'};
1669: my $cnum = $self->{'cnum'};
1670: my $cdom = $self->{'cdom'};
1671: #
1.13 matthew 1672: my $filename = $self->filename();
1.1 matthew 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'};
1.51 albertel 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'};
1.57 albertel 1683: } else {
1.1 matthew 1684: # Not cached, need to read
1.13 matthew 1685: if (! defined($filename)) {
1686: $formulas = $self->load_system_default_sheet();
1.33 matthew 1687: } elsif($filename =~ /^\/res\/.*\.spreadsheet$/) {
1.1 matthew 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);
1.13 matthew 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: }
1.1 matthew 1704: } else {
1705: # Load the spreadsheet definition file from the save file
1.13 matthew 1706: my %tmphash = &Apache::lonnet::dump($filename,$cdom,$cnum);
1.1 matthew 1707: my ($tmp) = keys(%tmphash);
1.71 albertel 1708: if (%tmphash
1709: && $tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1 matthew 1710: while (my ($cell,$formula) = each(%tmphash)) {
1711: $formulas->{$cell}=$formula;
1712: }
1713: } else {
1.13 matthew 1714: $formulas = $self->load_system_default_sheet();
1.1 matthew 1715: }
1716: }
1.51 albertel 1717: $self->formulas($formulas);
1718: $self->set_row_sources();
1719: $self->set_row_numbers();
1.57 albertel 1720: $self->cache_sheet($formulas);
1721: }
1722: }
1723:
1724: sub cache_sheet {
1725: my $self = shift;
1.59 albertel 1726: my ($formulas) = @_;
1.57 albertel 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:
1.58 albertel 1734: if (ref($formulas) eq 'HASH') {
1.57 albertel 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'}};
1.1 matthew 1742: }
1.57 albertel 1743: $spreadsheets{$cachekey}->{'maxrow'} = $self->{'maxrow'};
1.1 matthew 1744: }
1745:
1746: sub set_row_sources {
1747: my $self = shift;
1.54 albertel 1748: $self->check_formulas_loaded();
1.1 matthew 1749: while (my ($cell,$value) = each(%{$self->{'formulas'}})) {
1.22 matthew 1750: next if ($cell !~ /^A(\d+)/ || $1 < 1);
1.1 matthew 1751: my $row = $1;
1752: $self->{'row_source'}->{$row} = $value;
1753: }
1754: return;
1755: }
1756:
1.12 matthew 1757: sub set_row_numbers {
1758: my $self = shift;
1.54 albertel 1759: $self->check_formulas_loaded();
1.12 matthew 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:
1.1 matthew 1768: ##
1769: ## exportrow is *not* used to get the export row from a computed sub-sheet.
1770: ##
1771: sub exportrow {
1772: my $self = shift;
1.30 matthew 1773: if (exists($self->{'badcalc'}) && $self->{'badcalc'}) {
1774: return ();
1775: }
1.1 matthew 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'};
1.4 matthew 1787: # If we are saving it, it must not be temporary
1788: $self->temporary(0);
1.1 matthew 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'};
1.12 matthew 1794: my $filename = $self->{'filename'};
1.1 matthew 1795: # Cache new sheet
1.57 albertel 1796: $self->cache_sheet(\%f);
1.1 matthew 1797: # Write sheet
1798: foreach (keys(%f)) {
1799: delete($f{$_}) if ($f{$_} eq 'import');
1800: }
1.12 matthew 1801: my $reply = &Apache::lonnet::put($filename,\%f,$cdom,$cnum);
1.1 matthew 1802: return $reply if ($reply ne 'ok');
1803: $reply = &Apache::lonnet::put($stype.'_spreadsheets',
1.41 albertel 1804: {$filename => $env{'user.name'}.'@'.$env{'user.domain'}},
1.1 matthew 1805: $cdom,$cnum);
1806: return $reply if ($reply ne 'ok');
1807: if ($makedef) {
1808: $reply = &Apache::lonnet::put('environment',
1.12 matthew 1809: {'spreadsheet_default_'.$stype => $filename },
1.1 matthew 1810: $cdom,$cnum);
1811: return $reply if ($reply ne 'ok');
1.78 raeburn 1812: &Apache::lonnet::appenv({'course.'.$self->{'cid'}.'.spreadsheet_default_'.
1813: $self->{'type'} => $self->filename()});
1.1 matthew 1814: }
1.77 albertel 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','');
1.1 matthew 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;
1.41 albertel 1830: my $filename=$env{'user.name'}.'_'.
1831: $env{'user.domain'}.'_spreadsheet_'.$self->{'symb'}.'_'.
1.1 matthew 1832: $self->{'filename'};
1.9 matthew 1833: $filename=~s/\W/\_/g;
1834: $filename=$Apache::lonnet::tmpdir.$filename.'.tmp';
1.4 matthew 1835: $self->temporary(1);
1.1 matthew 1836: my $fh;
1.9 matthew 1837: if ($fh=Apache::File->new('>'.$filename)) {
1.1 matthew 1838: my %f = $self->formulas();
1839: while( my ($cell,$formula) = each(%f)) {
1840: next if ($formula eq 'import');
1.69 www 1841: print $fh &escape($cell)."=".
1842: &escape($formula)."\n";
1.1 matthew 1843: }
1844: $fh->close();
1845: }
1846: }
1847:
1848: sub load_tmp {
1849: my $self = shift;
1.41 albertel 1850: my $filename=$env{'user.name'}.'_'.
1851: $env{'user.domain'}.'_spreadsheet_'.$self->{'symb'}.'_'.
1.1 matthew 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(/=/);
1.69 www 1860: $cell = &unescape($cell);
1861: $formula = &unescape($formula);
1.1 matthew 1862: $formulas{$cell} = $formula;
1863: }
1864: $spreadsheet_file->close();
1865: }
1.4 matthew 1866: # flag the sheet as temporary
1867: $self->temporary(1);
1.1 matthew 1868: $self->formulas(\%formulas);
1869: $self->set_row_sources();
1870: $self->set_row_numbers();
1871: return;
1.4 matthew 1872: }
1873:
1874: sub temporary {
1875: my $self=shift;
1876: if (@_) {
1877: ($self->{'temporary'})= @_;
1878: }
1879: return $self->{'temporary'};
1.1 matthew 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: #
1.71 albertel 1904: my @alternatives=(&mt('Default'), &mt('LON-CAPA Standard'));
1.1 matthew 1905: my %results=&Apache::lonnet::dump($stype.'_spreadsheets',
1906: $self->{'cdom'}, $self->{'cnum'});
1907: my ($tmp) = keys(%results);
1.71 albertel 1908: if (%results
1.72 albertel 1909: && $tmp !~ /^(con_lost|error|no_such_host)/i ) {
1.71 albertel 1910: push(@alternatives, sort(keys(%results)));
1.1 matthew 1911: }
1912: return @alternatives;
1.3 matthew 1913: }
1914:
1915: sub blackout {
1916: my $self = shift;
1917: $self->{'blackout'} = $_[0] if (@_);
1918: return $self->{'blackout'};
1.1 matthew 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:
1.12 matthew 1946: sub need_to_save {
1.1 matthew 1947: my $self = shift;
1.12 matthew 1948: if ($self->{'new_rows'} && ! $self->temporary()) {
1949: return 1;
1.1 matthew 1950: }
1.12 matthew 1951: return 0;
1.1 matthew 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'};
1.13 matthew 1963: # $self->logthis('added row '.$self->{'row_numbers'}->{$key}.
1964: # ' for '.$key);
1.12 matthew 1965: $self->{'new_rows'} = 1;
1.1 matthew 1966: }
1967: return $self->{'row_numbers'}->{$key};
1968: }
1969:
1970: 1;
1971:
1972: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>