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

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

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