Annotation of loncom/interface/spreadsheet/Spreadsheet.pm, revision 1.25

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

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