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

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

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