Annotation of loncom/interface/spreadsheet/Spreadsheet.pm, revision 1.72
1.1 matthew 1: #
1.72 ! albertel 2: # $Id: Spreadsheet.pm,v 1.71 2006/09/03 00:45:51 albertel 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.55 albertel 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.45 albertel 678: #-------------------------------------------------------
679:
680: =pod
681:
682: =item &get_values($lower,$upper)
683:
684: Inputs: $lower and $upper, cell names ("X12" or "a150") or globs ("X*").
685:
686: Returns: an array ref of the values of the cells that exist in the
687: speced range
688:
689: =cut
690:
691: #-------------------------------------------------------
1.44 albertel 692: sub get_values {
693: my ($lower,$upper)=@_;
1.45 albertel 694: $upper = $lower if (! defined($upper));
1.44 albertel 695: my @values;
1.45 albertel 696: my ($la,$ld) = ($lower=~/([A-z]|\*)(\d+|\*)/);
697: my ($ua,$ud) = ($upper=~/([A-z]|\*)(\d+|\*)/);
698: my ($alpha,$num);
699: if ($ld ne '*' && $ud ne '*') {
1.44 albertel 700: my @alpha;
701: if (($la eq '*') || ($ua eq '*')) {
702: @alpha=('A'..'z');
703: } else {
1.45 albertel 704: if ($la gt $ua) { ($la,$ua)=($ua,$la); }
705: if ((lc($la) ne $la) && (lc($ua) eq $ua)) {
706: @alpha=($la..'Z','a'..$ua);
707: } else {
708: @alpha=($la..$ua);
709: }
710: }
711: my @num=($ld..$ud);
712: foreach my $a (@alpha) {
713: foreach my $n (@num) {
714: if (exists($sheet_values{$a.$n})) {
715: push(@values,$sheet_values{$a.$n});
716: }
1.44 albertel 717: }
718: }
1.45 albertel 719: return \@values;
720: } else {
1.60 albertel 721: $num = '([1-9]\d*)';
1.45 albertel 722: }
723: if (($la eq '*') || ($ua eq '*')) {
724: $alpha='[A-z]';
725: } else {
726: if ($la gt $ua) { ($la,$ua)=($ua,$la); }
727: $alpha=qq/[$la-$ua]/;
728: }
729: my $expression = '^'.$alpha.$num.'$';
730: foreach (grep /$expression/,keys(%sheet_values)) {
731: push(@values,$sheet_values{$_});
1.44 albertel 732: }
1.45 albertel 733: return \@values;
1.44 albertel 734: }
1.1 matthew 735:
736: sub calc {
737: my $notfinished = 1;
738: my $lastcalc = '';
739: my $depth = 0;
740: while ($notfinished) {
741: $notfinished=0;
742: while (my ($cell,$value) = each(%t)) {
743: my $old=$sheet_values{$cell};
1.65 bowersj2 744: $sheet_values{$cell}=eval $value;
1.1 matthew 745: # $errorlog .= $cell.' = '.$old.'->'.$sheet_values{$cell}."\n";
746: if ($@) {
747: undef %sheet_values;
748: return $cell.': '.$@;
749: }
750: if ($sheet_values{$cell} ne $old) {
751: $notfinished=1;
752: $lastcalc=$cell;
753: }
754: }
755: # $errorlog.="------------------------------------------------";
756:
757: $depth++;
758: if ($depth>100) {
759: undef %sheet_values;
760: return $lastcalc.': Maximum calculation depth exceeded';
761: }
762: }
1.30 matthew 763: return 'okay';
1.1 matthew 764: }
765:
766: # ------------------------------------------- End of "Inside of the safe space"
767: ENDDEFS
1.25 matthew 768: $safeeval->reval($code);
769: }
1.1 matthew 770: $self->{'safe'} = $safeeval;
771: $self->{'root'} = $self->{'safe'}->root();
772: #
773: # Place some of the %$self items into the safe space except the safe space
774: # itself
775: my $initstring = '';
1.38 matthew 776: foreach (qw/name domain type symb cid csec coursefilename
1.48 albertel 777: cnum cdom/) {
1.1 matthew 778: $initstring.= qq{\$$_="$self->{$_}";};
779: }
1.38 matthew 780: $initstring.=qq{\$usection="$usection";};
1.1 matthew 781: $self->{'safe'}->reval($initstring);
782: return $self;
783: }
1.25 matthew 784:
785: }
786:
1.1 matthew 787: ######################################################
788:
789: =pod
790:
791: =back
792:
793: =cut
794:
795: ######################################################
796:
797: ##
798: ## sub add_hash_to_safe {} # spreadsheet, would like to destroy
799: ##
800:
801: #
802: # expandnamed used to reside in the safe space
803: #
804: sub expandnamed {
805: my $self = shift;
806: my $expression=shift;
807: if ($expression=~/^\&/) {
808: my ($func,$var,$formula)=($expression=~/^\&(\w+)\(([^\;]+)\;(.*)\)/);
809: my @vars=split(/\W+/,$formula);
810: my %values=();
811: foreach my $varname ( @vars ) {
1.20 matthew 812: if ($varname=~/^(parameter|stores|timestamp)/) {
813: $formula=~s/$varname/'$c{\''.$varname.'\'}'/ge;
1.1 matthew 814: $varname=~s/$var/\([\\w:\\- ]\+\)/g;
815: foreach (keys(%{$self->{'constants'}})) {
816: if ($_=~/$varname/) {
817: $values{$1}=1;
818: }
819: }
820: }
821: }
822: if ($func eq 'EXPANDSUM') {
823: my $result='';
824: foreach (keys(%values)) {
825: my $thissum=$formula;
826: $thissum=~s/$var/$_/g;
827: $result.=$thissum.'+';
828: }
829: $result=~s/\+$//;
1.64 bowersj2 830: return '('.$result.')';
1.1 matthew 831: } else {
832: return 0;
833: }
834: } else {
835: # it is not a function, so it is a parameter name
836: # We should do the following:
837: # 1. Take the list of parameter names
838: # 2. look through the list for ones that match the parameter we want
839: # 3. If there are no collisions, return the one that matches
840: # 4. If there is a collision, return 'bad parameter name error'
841: my $returnvalue = '';
842: my @matches = ();
1.14 matthew 843: my @values = ();
1.1 matthew 844: $#matches = -1;
1.14 matthew 845: while (my($parameter,$value) = each(%{$self->{'constants'}})) {
846: next if ($parameter !~ /$expression/);
847: push(@matches,$parameter);
848: push(@values,$value);
1.1 matthew 849: }
850: if (scalar(@matches) == 0) {
1.10 matthew 851: $returnvalue = '""';#'"unmatched parameter: '.$parameter.'"';
1.1 matthew 852: } elsif (scalar(@matches) == 1) {
853: # why do we not do this lookup here, instead of delaying it?
1.14 matthew 854: $returnvalue = $values[0];
1.1 matthew 855: } elsif (scalar(@matches) > 0) {
856: # more than one match. Look for a concise one
857: $returnvalue = "'non-unique parameter name : $expression'";
1.14 matthew 858: for (my $i=0; $i<=$#matches;$i++) {
859: if ($matches[$i] =~ /^$expression$/) {
1.1 matthew 860: # why do we not do this lookup here?
1.14 matthew 861: $returnvalue = $values[$i];
1.1 matthew 862: }
863: }
864: } else {
865: # There was a negative number of matches, which indicates
866: # something is wrong with reality. Better warn the user.
1.14 matthew 867: $returnvalue = '"bizzare parameter: '.$expression.'"';
1.1 matthew 868: }
869: return $returnvalue;
870: }
871: }
872:
873: sub sett {
874: my $self = shift;
875: my %t=();
1.46 albertel 876: undef(%Apache::Spreadsheet::sheet_values);
1.1 matthew 877: #
878: # Deal with the template row
879: foreach my $col ($self->template_cells()) {
880: next if ($col=~/^[A-Z]/);
881: foreach my $row ($self->rows()) {
882: # Get the name of this cell
883: my $cell=$col.$row;
884: # Grab the template declaration
885: $t{$cell}=$self->formula('template_'.$col);
886: # Replace '#' with the row number
887: $t{$cell}=~s/\#/$row/g;
888: # Replace '....' with ','
889: $t{$cell}=~s/\.\.+/\,/g;
890: # Replace 'A0' with the value from 'A0'
891: $t{$cell}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
892: # Replace parameters
893: $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
894: }
895: }
896: #
897: # Deal with the normal cells
898: while (my($cell,$formula) = each(%{$self->{'formulas'}})) {
899: next if ($_=~/^template\_/);
900: my ($col,$row) = ($cell =~ /^([A-z])(\d+)$/);
901: if ($row eq '0') {
902: $t{$cell}=$formula;
903: $t{$cell}=~s/\.\.+/\,/g;
904: $t{$cell}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
905: $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
906: } elsif ( $col =~ /^[A-Z]$/ ) {
1.42 albertel 907: if ($formula !~ /^\!/ && exists($self->{'constants'}->{$cell})
908: && $self->{'constants'}->{$cell} ne '') {
1.46 albertel 909: $Apache::Spreadsheet::sheet_values{$cell}=
910: eval($self->{'constants'}->{$cell});
1.1 matthew 911: }
912: } else { # $row > 1 and $col =~ /[a-z]
913: $t{$cell}=$formula;
914: $t{$cell}=~s/\.\.+/\,/g;
915: $t{$cell}=~s/(^|[^\"\'])([A-Za-z]\d+)/$1\$sheet_values\{\'$2\'\}/g;
916: $t{$cell}=~s/(^|[^\"\'])\[([^\]]+)\]/$1.$self->expandnamed($2)/ge;
917: }
918: }
919: %{$self->{'safe'}->varglob('t')}=%t;
920: }
921:
922: ##
923: ## sync_safe_space: Called by calcsheet to make sure all the data we
924: # need to calculate is placed into the safe space
925: ##
926: sub sync_safe_space {
927: my $self = shift;
928: # Inside the safe space 'formulas' has a diabolical alter-ego named 'f'.
1.47 albertel 929: #%{$self->{'safe'}->varglob('f')}=%{$self->{'formulas'}};
1.1 matthew 930: # 'constants' leads a peaceful hidden life of 'c'.
931: %{$self->{'safe'}->varglob('c')}=%{$self->{'constants'}};
932: # 'othersheets' hides as 'os', a disguise few can penetrate.
1.47 albertel 933: #@{$self->{'safe'}->varglob('os')}=@{$self->{'othersheets'}};
1.1 matthew 934: }
935:
936: ##
937: ## Retrieve the error log from the safe space (used for debugging)
938: ##
939: sub get_errorlog {
940: my $self = shift;
941: $self->{'errorlog'} = $ { $self->{'safe'}->varglob('errorlog') };
942: return $self->{'errorlog'};
943: }
944:
945: ##
946: ## Clear the error log inside the safe space
947: ##
948: sub clear_errorlog {
949: my $self = shift;
950: $ {$self->{'safe'}->varglob('errorlog')} = '';
951: $self->{'errorlog'} = '';
952: }
953:
954: ##
955: ## constants: either set or get the constants
956: ##
957: sub constants {
958: my $self=shift;
959: my ($constants) = @_;
960: if (defined($constants)) {
961: if (! ref($constants)) {
962: my %tmp = @_;
963: $constants = \%tmp;
964: }
965: $self->{'constants'} = $constants;
966: return;
967: } else {
968: return %{$self->{'constants'}};
969: }
970: }
971:
972: ##
973: ## formulas: either set or get the formulas
974: ##
975: sub formulas {
976: my $self=shift;
977: my ($formulas) = @_;
978: if (defined($formulas)) {
979: if (! ref($formulas)) {
980: my %tmp = @_;
981: $formulas = \%tmp;
982: }
983: $self->{'formulas'} = $formulas;
984: $self->{'rows'} = [];
985: $self->{'template_cells'} = [];
1.54 albertel 986: $self->{'loaded'} = 1;
1.1 matthew 987: return;
988: } else {
1.54 albertel 989: $self->check_formulas_loaded();
990: return %{$self->{'formulas'}};
991: }
992: }
993:
994: sub check_formulas_loaded {
995: my $self=shift;
996: if (!$self->{'loaded'}) {
997: $self->{'loaded'}=1;
998: # Load in the spreadsheet definition
999: if (exists($env{'form.workcopy'}) &&
1000: $self->{'type'} eq $env{'form.workcopy'}) {
1001: $self->load_tmp();
1002: } else {
1003: $self->load();
1.49 albertel 1004: }
1.1 matthew 1005: }
1006: }
1007:
1008: sub set_formula {
1009: my $self = shift;
1010: my ($cell,$formula) = @_;
1.54 albertel 1011: $self->check_formulas_loaded();
1.1 matthew 1012: $self->{'formulas'}->{$cell}=$formula;
1013: return;
1014: }
1015:
1016: ##
1017: ## formulas_keys: Return the keys to the formulas hash.
1018: ##
1019: sub formulas_keys {
1020: my $self = shift;
1.54 albertel 1021: $self->check_formulas_loaded();
1.1 matthew 1022: return keys(%{$self->{'formulas'}});
1023: }
1024:
1025: ##
1026: ## formula: Return the formula for a given cell in the spreadsheet
1027: ## returns '' if the cell does not have a formula or does not exist
1028: ##
1029: sub formula {
1030: my $self = shift;
1031: my $cell = shift;
1.54 albertel 1032: $self->check_formulas_loaded();
1.1 matthew 1033: if (defined($cell) && exists($self->{'formulas'}->{$cell})) {
1034: return $self->{'formulas'}->{$cell};
1035: }
1036: return '';
1037: }
1038:
1039: ##
1040: ## logthis: write the input to lonnet.log
1041: ##
1042: sub logthis {
1043: my $self = shift;
1044: my $message = shift;
1045: &Apache::lonnet::logthis($self->{'type'}.':'.
1046: $self->{'name'}.':'.$self->{'domain'}.':'.
1047: $message);
1048: return;
1049: }
1050:
1051: ##
1052: ## dump_formulas_to_log: makes lonnet.log huge...
1053: ##
1054: sub dump_formulas_to_log {
1055: my $self =shift;
1056: $self->logthis("Spreadsheet formulas");
1057: $self->logthis("--------------------------------------------------------");
1058: while (my ($cell, $formula) = each(%{$self->{'formulas'}})) {
1059: $self->logthis(' '.$cell.' = '.$formula);
1060: }
1061: $self->logthis("--------------------------------------------------------");}
1062:
1063: ##
1064: ## value: returns the computed value of a particular cell
1065: ##
1066: sub value {
1067: my $self = shift;
1068: my $cell = shift;
1069: if (defined($cell) && exists($self->{'values'}->{$cell})) {
1070: return $self->{'values'}->{$cell};
1071: }
1072: return '';
1073: }
1074:
1075: ##
1076: ## dump_values_to_log: makes lonnet.log huge...
1077: ##
1078: sub dump_values_to_log {
1079: my $self =shift;
1080: $self->logthis("Spreadsheet Values");
1081: $self->logthis("------------------------------------------------------");
1082: while (my ($cell, $value) = each(%{$self->{'values'}})) {
1083: $self->logthis(' '.$cell.' = '.$value);
1084: }
1085: $self->logthis("------------------------------------------------------");
1086: }
1087:
1088: ##
1089: ## Yet another debugging function
1090: ##
1091: sub dump_hash_to_log {
1092: my $self= shift();
1093: my %tmp = @_;
1094: if (@_<2) {
1095: %tmp = %{$_[0]};
1096: }
1097: $self->logthis('---------------------------- (begin hash dump)');
1098: while (my ($key,$val) = each (%tmp)) {
1099: $self->logthis(' '.$key.' = '.$val.':');
1100: }
1101: $self->logthis('---------------------------- (finished hash dump)');
1102: }
1103:
1104: ##
1105: ## rebuild_stats: rebuilds the rows and template_cells arrays
1106: ##
1107: sub rebuild_stats {
1108: my $self = shift;
1109: $self->{'rows'}=[];
1110: $self->{'template_cells'}=[];
1.54 albertel 1111: $self->check_formulas_loaded();
1.1 matthew 1112: while (my ($cell,$formula) = each(%{$self->{'formulas'}})) {
1113: push(@{$self->{'rows'}},$1) if ($cell =~ /^A(\d+)/ && $1 != 0);
1114: push(@{$self->{'template_cells'}},$1) if ($cell =~ /^template_(\w+)/);
1115: }
1116: return;
1117: }
1118:
1119: ##
1120: ## template_cells returns a list of the cells defined in the template row
1121: ##
1122: sub template_cells {
1123: my $self = shift;
1124: $self->rebuild_stats() if (! defined($self->{'template_cells'}) ||
1125: ! @{$self->{'template_cells'}});
1126: return @{$self->{'template_cells'}};
1127: }
1128:
1129: ##
1130: ## Sigh....
1131: ##
1132: sub setothersheets {
1133: my $self = shift;
1134: my @othersheets = @_;
1135: $self->{'othersheets'} = \@othersheets;
1136: }
1137:
1138: ##
1139: ## rows returns a list of the names of cells defined in the A column
1140: ##
1141: sub rows {
1142: my $self = shift;
1143: $self->rebuild_stats() if (!@{$self->{'rows'}});
1144: return @{$self->{'rows'}};
1145: }
1146:
1147: #
1148: # calcsheet: makes all the calls to compute the spreadsheet.
1149: #
1150: sub calcsheet {
1151: my $self = shift;
1152: $self->sync_safe_space();
1153: $self->clear_errorlog();
1154: $self->sett();
1155: my $result = $self->{'safe'}->reval('&calc();');
1156: # $self->logthis($self->get_errorlog());
1157: %{$self->{'values'}} = %{$self->{'safe'}->varglob('sheet_values')};
1158: # $self->logthis($self->get_errorlog());
1.30 matthew 1159: if ($result ne 'okay') {
1160: $self->set_calcerror($result);
1161: }
1.1 matthew 1162: return $result;
1163: }
1164:
1.30 matthew 1165: sub set_badcalc {
1166: my $self = shift();
1167: $self->{'badcalc'} =1;
1168: return;
1169: }
1170:
1171: sub badcalc {
1172: my $self = shift;
1173: if (exists($self->{'badcalc'}) && $self->{'badcalc'}) {
1174: return 1;
1175: } else {
1176: return 0;
1177: }
1178: }
1179:
1180: sub set_calcerror {
1181: my $self = shift;
1182: if (@_) {
1183: $self->set_badcalc();
1184: if (exists($self->{'calcerror'})) {
1185: $self->{'calcerror'}.="\n".$_[0];
1186: } else {
1187: $self->{'calcerror'}.=$_[0];
1188: }
1189: }
1190: }
1191:
1192: sub calcerror {
1193: my $self = shift;
1194: if ($self->badcalc()) {
1195: if (exists($self->{'calcerror'})) {
1196: return $self->{'calcerror'};
1197: }
1198: }
1199: return;
1200: }
1201:
1.1 matthew 1202: ###########################################################
1203: ##
1204: ## Output Helpers
1205: ##
1206: ###########################################################
1.5 matthew 1207: sub display {
1208: my $self = shift;
1209: my ($r) = @_;
1210: my $outputmode = 'html';
1.31 matthew 1211: foreach ($self->output_options()) {
1.41 albertel 1212: if ($env{'form.output_format'} eq $_->{'value'}) {
1.31 matthew 1213: $outputmode = $_->{'value'};
1214: last;
1215: }
1.5 matthew 1216: }
1.62 bowersj2 1217: $self->{outputmode} = $outputmode;
1.5 matthew 1218: if ($outputmode eq 'html') {
1.31 matthew 1219: $self->compute($r);
1.5 matthew 1220: $self->outsheet_html($r);
1.31 matthew 1221: } elsif ($outputmode eq 'htmlclasslist') {
1222: # No computation neccessary... This is kludgy
1223: $self->outsheet_htmlclasslist($r);
1.62 bowersj2 1224: } elsif ($outputmode eq 'source') {
1225: # No computation necessary. Rumor has it that this is some
1226: # sort of kludge w.r.t. not "computing". It's also
1227: # a bit of of a kludge that we call "outsheet_html" and
1228: # let the 'outputmode' cause the outputting of source.
1229: $self->outsheet_html($r);
1.5 matthew 1230: } elsif ($outputmode eq 'excel') {
1.31 matthew 1231: $self->compute($r);
1.5 matthew 1232: $self->outsheet_excel($r);
1233: } elsif ($outputmode eq 'csv') {
1.31 matthew 1234: $self->compute($r);
1.5 matthew 1235: $self->outsheet_csv($r);
1.33 matthew 1236: } elsif ($outputmode eq 'xml') {
1237: # $self->compute($r);
1238: $self->outsheet_xml($r);
1.5 matthew 1239: }
1.22 matthew 1240: $self->cleanup();
1.5 matthew 1241: return;
1242: }
1243:
1.1 matthew 1244: ############################################
1245: ## HTML output routines ##
1246: ############################################
1.30 matthew 1247: sub html_report_error {
1248: my $self = shift();
1249: my $Str = '';
1250: if ($self->badcalc()) {
1251: $Str = '<h3 style="color:red">'.
1252: &mt('An error occurred while calculating this spreadsheet').
1253: "</h3>\n".
1254: '<pre>'.$self->calcerror()."</pre>\n";
1255: }
1256: return $Str;
1257: }
1258:
1.1 matthew 1259: sub html_export_row {
1260: my $self = shift();
1.17 matthew 1261: my ($color) = @_;
1262: $color = '#CCCCFF' if (! defined($color));
1.41 albertel 1263: my $allowed = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
1.1 matthew 1264: my $row_html;
1265: my @rowdata = $self->get_row(0);
1266: foreach my $cell (@rowdata) {
1267: if ($cell->{'name'} =~ /^[A-Z]/) {
1.17 matthew 1268: $row_html .= '<td bgcolor="'.$color.'">'.
1.62 bowersj2 1269: &html_editable_cell($cell,$color,$allowed,
1270: $self->{outputmode} eq 'source').'</td>';
1.1 matthew 1271: } else {
1272: $row_html .= '<td bgcolor="#DDCCFF">'.
1.62 bowersj2 1273: &html_editable_cell($cell,'#DDCCFF',$allowed,
1274: $self->{outputmode} eq 'source').'</td>';
1.1 matthew 1275: }
1276: }
1277: return $row_html;
1278: }
1279:
1280: sub html_template_row {
1281: my $self = shift();
1.41 albertel 1282: my $allowed = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
1.17 matthew 1283: my ($num_uneditable,$importcolor) = @_;
1.1 matthew 1284: my $row_html;
1285: my @rowdata = $self->get_template_row();
1286: my $count = 0;
1287: for (my $i = 0; $i<=$#rowdata; $i++) {
1288: my $cell = $rowdata[$i];
1289: if ($i < $num_uneditable) {
1.17 matthew 1290: $row_html .= '<td bgcolor="'.$importcolor.'">'.
1.7 matthew 1291: &html_uneditable_cell($cell,'#FFDDDD',$allowed).'</td>';
1.1 matthew 1292: } else {
1.70 albertel 1293: $row_html .= '<td bgcolor="#E0FFDD">'.
1294: &html_editable_cell($cell,'#E0FFDD',$allowed,
1.62 bowersj2 1295: $self->{outputmode} eq 'source').'</td>';
1.1 matthew 1296: }
1297: }
1298: return $row_html;
1299: }
1300:
1301: sub html_editable_cell {
1.62 bowersj2 1302: my ($cell,$bgcolor,$allowed,$showsource) = @_;
1.1 matthew 1303: my $result;
1304: my ($name,$formula,$value);
1305: if (defined($cell)) {
1306: $name = $cell->{'name'};
1307: $formula = $cell->{'formula'};
1308: $value = $cell->{'value'};
1309: }
1310: $name = '' if (! defined($name));
1311: $formula = '' if (! defined($formula));
1.65 bowersj2 1312: if ($showsource) {
1.62 bowersj2 1313: if (!defined($formula) || $formula =~ /^\s*$/) {
1314: $value = '<font color="'.$bgcolor.'">#</font>';
1315: } else {
1316: $value = &HTML::Entities::encode($formula, '<>&"');
1317: }
1.65 bowersj2 1318: } elsif (! defined($value)) {
1.1 matthew 1319: $value = '<font color="'.$bgcolor.'">#</font>';
1320: if ($formula ne '') {
1321: $value = '<i>undefined value</i>';
1322: }
1323: } elsif ($value =~ /^\s*$/ ) {
1324: $value = '<font color="'.$bgcolor.'">#</font>';
1325: } else {
1.37 albertel 1326: $value = &HTML::Entities::encode($value,'<>&"') if ($value !~/ /);
1.1 matthew 1327: }
1328: return $value if (! $allowed);
1.18 matthew 1329: #
1.1 matthew 1330: # The formula will be parsed by the browser twice before being
1.18 matthew 1331: # displayed to the user for editing.
1332: #
1333: # The encoding string "^A-blah" is placed in []'s inside a regexp, so
1334: # we specify the characters we want left alone by putting a '^' in front.
1.21 matthew 1335: $formula = &HTML::Entities::encode($formula,'^A-z0-9 !#$%-;=?~');
1336: # HTML::Entities::encode does not catch everything - we need '\' encoded
1337: $formula =~ s/\\/&\#092/g;
1.18 matthew 1338: # Escape it again - this time the only encodable character is '&'
1339: $formula =~ s/\&/\&/g;
1.1 matthew 1340: # Glue everything together
1341: $result .= "<a href=\"javascript:celledit(\'".
1342: $name."','".$formula."');\">".$value."</a>";
1343: return $result;
1344: }
1345:
1346: sub html_uneditable_cell {
1347: my ($cell,$bgcolor) = @_;
1348: my $value = (defined($cell) ? $cell->{'value'} : '');
1.37 albertel 1349: $value = &HTML::Entities::encode($value,'<>&"') if ($value !~/ /);
1.1 matthew 1350: return ' '.$value.' ';
1351: }
1352:
1353: sub html_row {
1354: my $self = shift();
1.17 matthew 1355: my ($num_uneditable,$row,$exportcolor,$importcolor) = @_;
1.41 albertel 1356: my $allowed = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
1.1 matthew 1357: my @rowdata = $self->get_row($row);
1358: my $num_cols_output = 0;
1359: my $row_html;
1.17 matthew 1360: my $color = $importcolor;
1361: if ($row == 0) {
1362: $color = $exportcolor;
1363: }
1364: $color = '#FFDDDD' if (! defined($color));
1.1 matthew 1365: foreach my $cell (@rowdata) {
1366: if ($num_cols_output++ < $num_uneditable) {
1.17 matthew 1367: $row_html .= '<td bgcolor="'.$color.'">';
1.1 matthew 1368: $row_html .= &html_uneditable_cell($cell,'#FFDDDD');
1369: } else {
1.70 albertel 1370: $row_html .= '<td bgcolor="#E0FFDD">';
1.62 bowersj2 1371: $row_html .= &html_editable_cell($cell,'#E0FFDD',$allowed,
1372: $self->{outputmode} eq 'source');
1.1 matthew 1373: }
1374: $row_html .= '</td>';
1375: }
1376: return $row_html;
1377: }
1378:
1.5 matthew 1379: sub html_header {
1380: my $self = shift;
1.41 albertel 1381: return '' if (! $env{'request.role.adv'});
1.5 matthew 1382: return "<table>\n".
1.29 matthew 1383: '<tr><th align="center">'.&mt('Output Format').'</th></tr>'."\n".
1.31 matthew 1384: '<tr><td>'.$self->output_selector()."</td></tr>\n".
1.5 matthew 1385: "</table>\n";
1386: }
1387:
1.31 matthew 1388: ##
1389: ## Default output types are HTML, Excel, and CSV
1390: sub output_options {
1391: my $self = shift();
1392: return ({value => 'html',
1393: description => 'HTML'},
1394: {value => 'excel',
1395: description => 'Excel'},
1.62 bowersj2 1396: {value => 'source',
1397: description => 'Show Source'},
1.33 matthew 1398: # {value => 'xml',
1399: # description => 'XML'},
1.31 matthew 1400: {value => 'csv',
1401: description => 'Comma Separated Values'},);
1402: }
1403:
1.5 matthew 1404: sub output_selector {
1.31 matthew 1405: my $self = shift();
1.5 matthew 1406: my $output_selector = '<select name="output_format" size="3">'."\n";
1407: my $default = 'html';
1.41 albertel 1408: if (exists($env{'form.output_format'})) {
1409: $default = $env{'form.output_format'}
1.5 matthew 1410: } else {
1.41 albertel 1411: $env{'form.output_format'} = $default;
1.5 matthew 1412: }
1.31 matthew 1413: foreach ($self->output_options()) {
1414: $output_selector.='<option value="'.$_->{'value'}.'"';
1415: if ($_->{'value'} eq $default) {
1.5 matthew 1416: $output_selector .= ' selected';
1417: }
1.31 matthew 1418: $output_selector .= ">".&mt($_->{'description'})."</option>\n";
1.5 matthew 1419: }
1420: $output_selector .= "</select>\n";
1421: return $output_selector;
1422: }
1423:
1424: ################################################
1425: ## Excel output routines ##
1426: ################################################
1427: sub excel_output_row {
1428: my $self = shift;
1429: my ($worksheet,$rownum,$rows_output,@prepend) = @_;
1430: my $cols_output = 0;
1431: #
1432: my @rowdata = $self->get_row($rownum);
1433: foreach my $cell (@prepend,@rowdata) {
1434: my $value = $cell;
1435: $value = $cell->{'value'} if (ref($value));
1436: $value =~ s/\ / /gi;
1437: $worksheet->write($rows_output,$cols_output++,$value);
1438: }
1439: return;
1440: }
1441:
1.31 matthew 1442: #
1443: # This routine is just a stub
1444: sub outsheet_htmlclasslist {
1445: my $self = shift;
1446: my ($r) = @_;
1447: $r->print('<h2>'.&mt("This output is not supported").'</h2>');
1448: $r->rflush();
1449: return;
1.5 matthew 1450: }
1451:
1452: sub outsheet_excel {
1453: my $self = shift;
1454: my ($r) = @_;
1.23 matthew 1455: my $connection = $r->connection();
1.32 matthew 1456: #
1457: $r->print($self->html_report_error());
1458: $r->rflush();
1459: #
1.28 www 1460: $r->print("<h2>".&mt('Preparing Excel Spreadsheet')."</h2>");
1.5 matthew 1461: #
1.40 matthew 1462: # Create excel workbook
1463: my ($workbook,$filename,$format)=&Apache::loncommon::create_workbook($r);
1.5 matthew 1464: return if (! defined($workbook));
1465: #
1466: # Create main worksheet
1467: my $worksheet = $workbook->addworksheet('main');
1468: my $rows_output = 0;
1469: my $cols_output = 0;
1470: #
1471: # Write excel header
1472: foreach my $value ($self->get_title()) {
1473: $cols_output = 0;
1.40 matthew 1474: $worksheet->write($rows_output++,$cols_output,$value,$format->{'h1'});
1.5 matthew 1475: }
1476: $rows_output++; # skip a line
1477: #
1478: # Write summary/export row
1479: $cols_output = 0;
1.40 matthew 1480: $self->excel_output_row($worksheet,0,$rows_output++,'Summary',
1481: $format->{'b'});
1.5 matthew 1482: $rows_output++; # skip a line
1483: #
1.40 matthew 1484: $self->excel_rows($connection,$worksheet,$cols_output,$rows_output,
1485: $format);
1.5 matthew 1486: #
1487: #
1488: # Close the excel file
1489: $workbook->close();
1490: #
1491: # Write a link to allow them to download it
1492: $r->print('<br />'.
1493: '<a href="'.$filename.'">Your Excel spreadsheet.</a>'."\n");
1.6 matthew 1494: return;
1495: }
1496:
1497: #################################
1498: ## CSV output routines ##
1499: #################################
1500: sub outsheet_csv {
1501: my $self = shift;
1502: my ($r) = @_;
1.23 matthew 1503: my $connection = $r->connection();
1.32 matthew 1504: #
1505: $r->print($self->html_report_error());
1506: $r->rflush();
1507: #
1.6 matthew 1508: my $csvdata = '';
1509: my @Values;
1510: #
1511: # Open the csv file
1512: my $filename = '/prtspool/'.
1.41 albertel 1513: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.6 matthew 1514: time.'_'.rand(1000000000).'.csv';
1515: my $file;
1516: unless ($file = Apache::File->new('>'.'/home/httpd'.$filename)) {
1517: $r->log_error("Couldn't open $filename for output $!");
1.28 www 1518: $r->print(&mt("Problems occured in writing the csv file. ".
1.6 matthew 1519: "This error has been logged. ".
1.28 www 1520: "Please alert your LON-CAPA administrator."));
1.6 matthew 1521: $r->print("<pre>\n".$csvdata."</pre>\n");
1522: return 0;
1523: }
1524: #
1525: # Output the title information
1526: foreach my $value ($self->get_title()) {
1527: print $file "'".&Apache::loncommon::csv_translate($value)."'\n";
1528: }
1529: #
1530: # Output the body of the spreadsheet
1.23 matthew 1531: $self->csv_rows($connection,$file);
1.6 matthew 1532: #
1533: # Close the csv file
1534: close($file);
1535: $r->print('<br /><br />'.
1.28 www 1536: '<a href="'.$filename.'">'.&mt('Your CSV spreadsheet.').'</a>'."\n");
1.6 matthew 1537: #
1538: return 1;
1539: }
1540:
1541: sub csv_output_row {
1542: my $self = shift;
1543: my ($filehandle,$rownum,@prepend) = @_;
1544: #
1545: my @rowdata = ();
1546: if (defined($rownum)) {
1547: @rowdata = $self->get_row($rownum);
1548: }
1549: my @output = ();
1550: foreach my $cell (@prepend,@rowdata) {
1551: my $value = $cell;
1552: $value = $cell->{'value'} if (ref($value));
1553: $value =~ s/\ / /gi;
1554: $value = "'".$value."'";
1555: push (@output,$value);
1556: }
1557: print $filehandle join(',',@output )."\n";
1.5 matthew 1558: return;
1.1 matthew 1559: }
1560:
1561: ############################################
1562: ## XML output routines ##
1563: ############################################
1564: sub outsheet_xml {
1565: my $self = shift;
1566: my ($r) = @_;
1567: ## Someday XML
1568: ## Will be rendered for the user
1569: ## But not on this day
1570: my $Str = '<spreadsheet type="'.$self->{'type'}.'">'."\n";
1.54 albertel 1571: $self->check_formulas_loaded();
1.1 matthew 1572: while (my ($cell,$formula) = each(%{$self->{'formulas'}})) {
1.34 matthew 1573: if ($cell =~ /^template_(\w+)/) {
1.1 matthew 1574: my $col = $1;
1575: $Str .= '<template col="'.$col.'">'.$formula.'</template>'."\n";
1576: } else {
1.33 matthew 1577: my ($col,$row) = ($cell =~ /^([A-z])(\d+)/);
1.1 matthew 1578: next if (! defined($row) || ! defined($col));
1.33 matthew 1579: next if ($row != 0);
1580: $Str .=
1581: '<field row="'.$row.'" col="'.$col.'" >'.$formula.'</field>'
1.1 matthew 1582: ."\n";
1583: }
1584: }
1585: $Str.="</spreadsheet>";
1.34 matthew 1586: $r->print("<pre>\n\n\n".$Str."\n\n\n</pre>");
1.1 matthew 1587: return $Str;
1588: }
1589:
1590: ############################################
1591: ### Filesystem routines ###
1592: ############################################
1593: sub parse_sheet {
1594: # $sheetxml is a scalar reference or a scalar
1595: my ($sheetxml) = @_;
1596: if (! ref($sheetxml)) {
1597: my $tmp = $sheetxml;
1598: $sheetxml = \$tmp;
1599: }
1600: my %formulas;
1601: my %sources;
1602: my $parser=HTML::TokeParser->new($sheetxml);
1603: my $token;
1604: while ($token=$parser->get_token) {
1605: if ($token->[0] eq 'S') {
1606: if ($token->[1] eq 'field') {
1607: my $cell = $token->[2]->{'col'}.$token->[2]->{'row'};
1608: my $source = $token->[2]->{'source'};
1609: my $formula = $parser->get_text('/field');
1610: $formulas{$cell} = $formula;
1611: $sources{$cell} = $source if (defined($source));
1612: $parser->get_text('/field');
1.34 matthew 1613: } elsif ($token->[1] eq 'template') {
1.1 matthew 1614: $formulas{'template_'.$token->[2]->{'col'}}=
1615: $parser->get_text('/template');
1616: }
1617: }
1618: }
1619: return (\%formulas,\%sources);
1620: }
1621:
1622: {
1623:
1624: my %spreadsheets;
1625:
1626: sub clear_spreadsheet_definition_cache {
1627: undef(%spreadsheets);
1628: }
1629:
1.13 matthew 1630: sub load_system_default_sheet {
1631: my $self = shift;
1632: my $includedir = $Apache::lonnet::perlvar{'lonIncludes'};
1633: # load in the default defined spreadsheet
1634: my $sheetxml='';
1635: my $fh;
1636: if ($fh=Apache::File->new($includedir.'/default_'.$self->{'type'})) {
1637: $sheetxml=join('',<$fh>);
1638: $fh->close();
1639: } else {
1640: # $sheetxml='<field row="0" col="A">"Error"</field>';
1641: $sheetxml='<field row="0" col="A"></field>';
1642: }
1643: $self->filename('default_');
1644: my ($formulas,undef) = &parse_sheet(\$sheetxml);
1645: return $formulas;
1646: }
1647:
1.1 matthew 1648: sub load {
1649: my $self = shift;
1650: #
1651: my $stype = $self->{'type'};
1652: my $cnum = $self->{'cnum'};
1653: my $cdom = $self->{'cdom'};
1654: #
1.13 matthew 1655: my $filename = $self->filename();
1.1 matthew 1656: my $cachekey = join('_',($cnum,$cdom,$stype,$filename));
1657: #
1658: # see if sheet is cached
1659: my ($formulas);
1660: if (exists($spreadsheets{$cachekey})) {
1661: $formulas = $spreadsheets{$cachekey}->{'formulas'};
1.51 albertel 1662: $self->formulas($formulas);
1663: $self->{'row_source'}=$spreadsheets{$cachekey}->{'row_source'};
1664: $self->{'row_numbers'}=$spreadsheets{$cachekey}->{'row_numbers'};
1665: $self->{'maxrow'}=$spreadsheets{$cachekey}->{'maxrow'};
1.57 albertel 1666: } else {
1.1 matthew 1667: # Not cached, need to read
1.13 matthew 1668: if (! defined($filename)) {
1669: $formulas = $self->load_system_default_sheet();
1.33 matthew 1670: } elsif($filename =~ /^\/res\/.*\.spreadsheet$/) {
1.1 matthew 1671: # Load a spreadsheet definition file
1672: my $sheetxml=&Apache::lonnet::getfile
1673: (&Apache::lonnet::filelocation('',$filename));
1674: if ($sheetxml == -1) {
1675: $sheetxml='<field row="0" col="A">"Error loading spreadsheet '
1676: .$self->filename().'"</field>';
1677: }
1678: ($formulas,undef) = &parse_sheet(\$sheetxml);
1.13 matthew 1679: # Get just the filename and set the sheets filename
1680: my ($newfilename) = ($filename =~ /\/([^\/]*)\.spreadsheet$/);
1681: if ($self->is_default()) {
1682: $self->filename($newfilename);
1683: $self->make_default();
1684: } else {
1685: $self->filename($newfilename);
1686: }
1.1 matthew 1687: } else {
1688: # Load the spreadsheet definition file from the save file
1.13 matthew 1689: my %tmphash = &Apache::lonnet::dump($filename,$cdom,$cnum);
1.1 matthew 1690: my ($tmp) = keys(%tmphash);
1.71 albertel 1691: if (%tmphash
1692: && $tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1 matthew 1693: while (my ($cell,$formula) = each(%tmphash)) {
1694: $formulas->{$cell}=$formula;
1695: }
1696: } else {
1.13 matthew 1697: $formulas = $self->load_system_default_sheet();
1.1 matthew 1698: }
1699: }
1.51 albertel 1700: $self->formulas($formulas);
1701: $self->set_row_sources();
1702: $self->set_row_numbers();
1.57 albertel 1703: $self->cache_sheet($formulas);
1704: }
1705: }
1706:
1707: sub cache_sheet {
1708: my $self = shift;
1.59 albertel 1709: my ($formulas) = @_;
1.57 albertel 1710: my $stype = $self->{'type'};
1711: my $cnum = $self->{'cnum'};
1712: my $cdom = $self->{'cdom'};
1713: #
1714: my $filename = $self->filename();
1715: my $cachekey = join('_',($cnum,$cdom,$stype,$filename));
1716:
1.58 albertel 1717: if (ref($formulas) eq 'HASH') {
1.57 albertel 1718: %{$spreadsheets{$cachekey}->{'formulas'}} = %{$formulas};
1719: }
1720: if (ref($self->{'row_source'})) {
1721: %{$spreadsheets{$cachekey}->{'row_source'}} =%{$self->{'row_source'}};
1722: }
1723: if (ref($self->{'row_numbers'})) {
1724: %{$spreadsheets{$cachekey}->{'row_numbers'}}=%{$self->{'row_numbers'}};
1.1 matthew 1725: }
1.57 albertel 1726: $spreadsheets{$cachekey}->{'maxrow'} = $self->{'maxrow'};
1.1 matthew 1727: }
1728:
1729: sub set_row_sources {
1730: my $self = shift;
1.54 albertel 1731: $self->check_formulas_loaded();
1.1 matthew 1732: while (my ($cell,$value) = each(%{$self->{'formulas'}})) {
1.22 matthew 1733: next if ($cell !~ /^A(\d+)/ || $1 < 1);
1.1 matthew 1734: my $row = $1;
1735: $self->{'row_source'}->{$row} = $value;
1736: }
1737: return;
1738: }
1739:
1.12 matthew 1740: sub set_row_numbers {
1741: my $self = shift;
1.54 albertel 1742: $self->check_formulas_loaded();
1.12 matthew 1743: while (my ($cell,$value) = each(%{$self->{'formulas'}})) {
1744: next if ($cell !~ /^A(\d+)$/);
1745: next if (! defined($value));
1746: $self->{'row_numbers'}->{$value} = $1;
1747: $self->{'maxrow'} = $1 if ($1 > $self->{'maxrow'});
1748: }
1749: }
1750:
1.1 matthew 1751: ##
1752: ## exportrow is *not* used to get the export row from a computed sub-sheet.
1753: ##
1754: sub exportrow {
1755: my $self = shift;
1.30 matthew 1756: if (exists($self->{'badcalc'}) && $self->{'badcalc'}) {
1757: return ();
1758: }
1.1 matthew 1759: my @exportarray;
1760: foreach my $column (@UC_Columns) {
1761: push(@exportarray,$self->value($column.'0'));
1762: }
1763: return @exportarray;
1764: }
1765:
1766: sub save {
1767: my $self = shift;
1768: my ($makedef)=@_;
1769: my $cid=$self->{'cid'};
1.4 matthew 1770: # If we are saving it, it must not be temporary
1771: $self->temporary(0);
1.1 matthew 1772: if (&Apache::lonnet::allowed('opa',$cid)) {
1773: my %f=$self->formulas();
1774: my $stype = $self->{'type'};
1775: my $cnum = $self->{'cnum'};
1776: my $cdom = $self->{'cdom'};
1.12 matthew 1777: my $filename = $self->{'filename'};
1.1 matthew 1778: # Cache new sheet
1.57 albertel 1779: $self->cache_sheet(\%f);
1.1 matthew 1780: # Write sheet
1781: foreach (keys(%f)) {
1782: delete($f{$_}) if ($f{$_} eq 'import');
1783: }
1.12 matthew 1784: my $reply = &Apache::lonnet::put($filename,\%f,$cdom,$cnum);
1.1 matthew 1785: return $reply if ($reply ne 'ok');
1786: $reply = &Apache::lonnet::put($stype.'_spreadsheets',
1.41 albertel 1787: {$filename => $env{'user.name'}.'@'.$env{'user.domain'}},
1.1 matthew 1788: $cdom,$cnum);
1789: return $reply if ($reply ne 'ok');
1790: if ($makedef) {
1791: $reply = &Apache::lonnet::put('environment',
1.12 matthew 1792: {'spreadsheet_default_'.$stype => $filename },
1.1 matthew 1793: $cdom,$cnum);
1794: return $reply if ($reply ne 'ok');
1.55 albertel 1795: &Apache::lonnet::appenv('course.'.$self->{'cid'}.'.spreadsheet_default_'.
1796: $self->{'type'} => $self->filename());
1.1 matthew 1797: }
1798: if ($self->is_default()) {
1.22 matthew 1799: if ($self->{'type'} eq 'studentcalc') {
1800: &Apache::lonnet::expirespread('','','studentcalc','');
1801: } elsif ($self->{'type'} eq 'assesscalc') {
1802: &Apache::lonnet::expirespread('','','assesscalc','');
1.16 matthew 1803: &Apache::lonnet::expirespread('','','studentcalc','');
1804: }
1.1 matthew 1805: }
1806: return $reply;
1807: }
1808: return 'unauthorized';
1809: }
1810:
1811: } # end of scope for %spreadsheets
1812:
1813: sub save_tmp {
1814: my $self = shift;
1.41 albertel 1815: my $filename=$env{'user.name'}.'_'.
1816: $env{'user.domain'}.'_spreadsheet_'.$self->{'symb'}.'_'.
1.1 matthew 1817: $self->{'filename'};
1.9 matthew 1818: $filename=~s/\W/\_/g;
1819: $filename=$Apache::lonnet::tmpdir.$filename.'.tmp';
1.4 matthew 1820: $self->temporary(1);
1.1 matthew 1821: my $fh;
1.9 matthew 1822: if ($fh=Apache::File->new('>'.$filename)) {
1.1 matthew 1823: my %f = $self->formulas();
1824: while( my ($cell,$formula) = each(%f)) {
1825: next if ($formula eq 'import');
1.69 www 1826: print $fh &escape($cell)."=".
1827: &escape($formula)."\n";
1.1 matthew 1828: }
1829: $fh->close();
1830: }
1831: }
1832:
1833: sub load_tmp {
1834: my $self = shift;
1.41 albertel 1835: my $filename=$env{'user.name'}.'_'.
1836: $env{'user.domain'}.'_spreadsheet_'.$self->{'symb'}.'_'.
1.1 matthew 1837: $self->{'filename'};
1838: $filename=~s/\W/\_/g;
1839: $filename=$Apache::lonnet::tmpdir.$filename.'.tmp';
1840: my %formulas = ();
1841: if (my $spreadsheet_file = Apache::File->new($filename)) {
1842: while (<$spreadsheet_file>) {
1843: chomp;
1844: my ($cell,$formula) = split(/=/);
1.69 www 1845: $cell = &unescape($cell);
1846: $formula = &unescape($formula);
1.1 matthew 1847: $formulas{$cell} = $formula;
1848: }
1849: $spreadsheet_file->close();
1850: }
1.4 matthew 1851: # flag the sheet as temporary
1852: $self->temporary(1);
1.1 matthew 1853: $self->formulas(\%formulas);
1854: $self->set_row_sources();
1855: $self->set_row_numbers();
1856: return;
1.4 matthew 1857: }
1858:
1859: sub temporary {
1860: my $self=shift;
1861: if (@_) {
1862: ($self->{'temporary'})= @_;
1863: }
1864: return $self->{'temporary'};
1.1 matthew 1865: }
1866:
1867: sub modify_cell {
1868: # studentcalc overrides this
1869: my $self = shift;
1870: my ($cell,$formula) = @_;
1871: if ($cell =~ /([A-z])\-/) {
1872: $cell = 'template_'.$1;
1873: } elsif ($cell !~ /^([A-z](\d+)|template_[A-z])$/) {
1874: return;
1875: }
1876: $self->set_formula($cell,$formula);
1877: $self->rebuild_stats();
1878: return;
1879: }
1880:
1881: ###########################################
1882: # othersheets: Returns the list of other spreadsheets available
1883: ###########################################
1884: sub othersheets {
1885: my $self = shift();
1886: my ($stype) = @_;
1887: $stype = $self->{'type'} if (! defined($stype) || $stype !~ /calc$/);
1888: #
1.71 albertel 1889: my @alternatives=(&mt('Default'), &mt('LON-CAPA Standard'));
1.1 matthew 1890: my %results=&Apache::lonnet::dump($stype.'_spreadsheets',
1891: $self->{'cdom'}, $self->{'cnum'});
1892: my ($tmp) = keys(%results);
1.71 albertel 1893: if (%results
1.72 ! albertel 1894: && $tmp !~ /^(con_lost|error|no_such_host)/i ) {
1.71 albertel 1895: push(@alternatives, sort(keys(%results)));
1.1 matthew 1896: }
1897: return @alternatives;
1.3 matthew 1898: }
1899:
1900: sub blackout {
1901: my $self = shift;
1902: $self->{'blackout'} = $_[0] if (@_);
1903: return $self->{'blackout'};
1.1 matthew 1904: }
1905:
1906: sub get_row {
1907: my $self = shift;
1908: my ($n)=@_;
1909: my @cols=();
1910: foreach my $col (@UC_Columns,@LC_Columns) {
1911: my $cell = $col.$n;
1912: push(@cols,{ name => $cell,
1913: formula => $self->formula($cell),
1914: value => $self->value($cell)});
1915: }
1916: return @cols;
1917: }
1918:
1919: sub get_template_row {
1920: my $self = shift;
1921: my @cols=();
1922: foreach my $col (@UC_Columns,@LC_Columns) {
1923: my $cell = 'template_'.$col;
1924: push(@cols,{ name => $cell,
1925: formula => $self->formula($cell),
1926: value => $self->formula($cell) });
1927: }
1928: return @cols;
1929: }
1930:
1.12 matthew 1931: sub need_to_save {
1.1 matthew 1932: my $self = shift;
1.12 matthew 1933: if ($self->{'new_rows'} && ! $self->temporary()) {
1934: return 1;
1.1 matthew 1935: }
1.12 matthew 1936: return 0;
1.1 matthew 1937: }
1938:
1939: sub get_row_number_from_key {
1940: my $self = shift;
1941: my ($key) = @_;
1942: if (! exists($self->{'row_numbers'}->{$key}) ||
1943: ! defined($self->{'row_numbers'}->{$key})) {
1944: # I used to set $f here to the new value, but the key passed for lookup
1945: # may not be the key we need to save
1946: $self->{'maxrow'}++;
1947: $self->{'row_numbers'}->{$key} = $self->{'maxrow'};
1.13 matthew 1948: # $self->logthis('added row '.$self->{'row_numbers'}->{$key}.
1949: # ' for '.$key);
1.12 matthew 1950: $self->{'new_rows'} = 1;
1.1 matthew 1951: }
1952: return $self->{'row_numbers'}->{$key};
1953: }
1954:
1955: 1;
1956:
1957: __END__
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>