File:  [LON-CAPA] / loncom / interface / spreadsheet / Spreadsheet.pm
Revision 1.41: download - view: text, annotated - select for diffs
Thu Apr 7 06:56:23 2005 UTC (19 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: version_1_99_0_tmcc, HEAD
- ENV -> env

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

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