File:  [LON-CAPA] / loncom / interface / spreadsheet / Spreadsheet.pm
Revision 1.21: download - view: text, annotated - select for diffs
Tue Aug 26 19:14:06 2003 UTC (20 years, 10 months ago) by matthew
Branches: MAIN
CVS tags: version_1_0_3, version_1_0_2, version_1_0_1, HEAD
HTML::Entities::encode does not encode backslash.  How annoying.
Do it ourselves to make sure formulas come up properly when editing
spreadsheet cells.

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

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