File:  [LON-CAPA] / loncom / interface / spreadsheet / Spreadsheet.pm
Revision 1.16: download - view: text, annotated - select for diffs
Fri Jun 20 16:14:30 2003 UTC (20 years, 11 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
When changing the default assesscalc spreadsheet we now expire the
student level spreadsheets.

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

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