File:  [LON-CAPA] / loncom / interface / spreadsheet / Spreadsheet.pm
Revision 1.46: download - view: text, annotated - select for diffs
Fri May 13 21:14:46 2005 UTC (19 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- minimizing the number of elments in %t, and moving sheet_values to be out int Spreadsheet not in the safe space (student level sheet not taking aroun 0.5 seconds to compute)

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

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