File:  [LON-CAPA] / loncom / interface / spreadsheet / Spreadsheet.pm
Revision 1.51: download - view: text, annotated - select for diffs
Tue May 17 20:17:03 2005 UTC (19 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: version_1_99_1_tmcc, HEAD
- cache the parses of the formulas when there are alot of %f it can take a while to parse through them

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>